diff --git a/.devcontainer/devcontainer-lock.json b/.devcontainer/devcontainer-lock.json new file mode 100644 index 0000000..de51286 --- /dev/null +++ b/.devcontainer/devcontainer-lock.json @@ -0,0 +1,9 @@ +{ + "features": { + "ghcr.io/devcontainers/features/github-cli:1": { + "version": "1.1.3", + "resolved": "ghcr.io/devcontainers/features/github-cli@sha256:bd7ab48a832228f633239277552c30b353867fef2e5b037e064b4e64f0b843f2", + "integrity": "sha256:bd7ab48a832228f633239277552c30b353867fef2e5b037e064b4e64f0b843f2" + } + } +} diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..5b6a095 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,13 @@ +{ + "name": "bazel-github-actions-cache-v2s", + "image": "mcr.microsoft.com/devcontainers/go:2-1.27-trixie", + "features": { + "ghcr.io/devcontainers/features/github-cli:1": {} + }, + "initializeCommand": { + "gh-cli-auth": "gh auth token > .git/__gh_token || true" + }, + "postStartCommand": { + "gh-cli-auth": "test -s .git/__gh_token && gh auth login --with-token < .git/__gh_token || true" + } +} \ No newline at end of file diff --git a/.github/actions/publish-release/action.yml b/.github/actions/publish-release/action.yml new file mode 100644 index 0000000..0a2038f --- /dev/null +++ b/.github/actions/publish-release/action.yml @@ -0,0 +1,87 @@ +name: Publish release +description: >- + Builds the server binaries, attests their provenance, and publishes them as + assets on a tag pointing at the commit they were built from. + +inputs: + version: + description: Release tag to create + required: true + prerelease: + description: Mark the release as a pre-release + required: false + default: "false" + notes: + description: Release notes body + required: true + token: + description: Token used to create the tag and publish the release + required: true + +runs: + using: composite + steps: + - name: Build server binaries + shell: bash + env: + VERSION: ${{ inputs.version }} + run: scripts/build-dist.sh + + # The action verifies this attestation before it will run a downloaded + # binary, which is what lets the repository ship no build output at all. + - name: Attest the build provenance + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: | + dist/cache-optimiser-linux-amd64 + dist/cache-optimiser-linux-arm64 + dist/cache-server-darwin-arm64 + dist/cache-server-linux-amd64 + dist/cache-server-linux-arm64 + dist/cache-server-windows-amd64.exe + dist/cache-server-windows-arm64.exe + + # The tag points at the reviewed commit itself, so the tree a consumer + # checks out is exactly the tree CI ran against. + - name: Tag the release + shell: bash + env: + GH_TOKEN: ${{ inputs.token }} + VERSION: ${{ inputs.version }} + REPOSITORY: ${{ github.repository }} + BASE_SHA: ${{ github.sha }} + run: | + set -euo pipefail + gh api --method POST "repos/$REPOSITORY/git/refs" \ + --field ref="refs/tags/$VERSION" --field sha="$BASE_SHA" >/dev/null + + # Immutable releases lock assets at publication, so the release is drafted, + # populated, and only then published. + - name: Publish the release + shell: bash + env: + GH_TOKEN: ${{ inputs.token }} + VERSION: ${{ inputs.version }} + NOTES: ${{ inputs.notes }} + PRERELEASE: ${{ inputs.prerelease }} + run: | + set -euo pipefail + create=(gh release create "$VERSION" --draft --verify-tag --title "$VERSION" --notes "$NOTES") + if [[ "$PRERELEASE" == "true" ]]; then + create+=(--prerelease) + fi + "${create[@]}" + gh release upload "$VERSION" \ + dist/cache-optimiser-linux-amd64 \ + dist/cache-optimiser-linux-arm64 \ + dist/cache-server-darwin-arm64 \ + dist/cache-server-linux-amd64 \ + dist/cache-server-linux-arm64 \ + dist/cache-server-windows-amd64.exe \ + dist/cache-server-windows-arm64.exe \ + dist/SHA256SUMS + publish=(gh release edit "$VERSION" --draft=false) + if [[ "$PRERELEASE" != "true" ]]; then + publish+=(--latest) + fi + "${publish[@]}" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 30e21e9..e987400 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,16 +23,102 @@ jobs: - name: Go vet run: go vet ./... - name: Staticcheck - run: go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./... + run: go tool staticcheck ./... + - name: Deadcode + run: | + findings="$(go tool deadcode -test ./...)" + if [[ -n "$findings" ]]; then + printf '%s\n' "$findings" + exit 1 + fi - name: Govulncheck - run: go run golang.org/x/vuln/cmd/govulncheck@v1.6.0 ./... + run: go tool govulncheck ./... - name: Node wrapper tests - run: node --test action/*.test.js + run: node --test action/*.test.js optimise/*.test.js - name: Actionlint run: go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 - - name: Rebuild packaged binaries + - name: Build packaged binaries env: - VERSION: v0.3.2 + VERSION: ci-${{ github.sha }} run: scripts/build-dist.sh - name: Verify packaged binaries are reproducible - run: git diff --exit-code -- dist + env: + VERSION: ci-${{ github.sha }} + run: | + mv dist/SHA256SUMS "$RUNNER_TEMP/SHA256SUMS.first" + scripts/build-dist.sh + diff "$RUNNER_TEMP/SHA256SUMS.first" dist/SHA256SUMS + + macos: + runs-on: macos-15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: .go-version + cache: true + - name: Require Apple Silicon + run: test "$(uname -m)" = arm64 + - name: Cache server Go tests with race detector + run: go test -race ./cmd/cache-server ./internal/server ./internal/cache ./internal/artifact + - name: Node cache server wrapper tests + run: node --test action/*.test.js + - name: Build packaged binaries + env: + VERSION: ci-${{ github.sha }} + run: scripts/build-dist.sh + - name: Verify packaged checksums and native server + env: + VERSION: ci-${{ github.sha }} + run: | + (cd dist && shasum -a 256 --check SHA256SUMS) + test "$(dist/cache-server-darwin-arm64 --version)" = "$VERSION" + + windows: + strategy: + matrix: + include: + - runner: windows-2025 + architecture: amd64 + race: "-race" + - runner: windows-11-arm + architecture: arm64 + race: "" + runs-on: ${{ matrix.runner }} + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: .go-version + cache: true + architecture: ${{ matrix.architecture == 'amd64' && 'x64' || matrix.architecture }} + - name: Require native Go architecture + env: + EXPECTED_ARCH: ${{ matrix.architecture }} + run: test "$(go env GOHOSTARCH)" = "$EXPECTED_ARCH" + # Go does not support the race detector on Windows ARM64. + - name: Cache server Go tests + env: + RACE: ${{ matrix.race }} + run: | + flags=() + if [[ -n "$RACE" ]]; then + flags+=("$RACE") + fi + go test "${flags[@]}" ./cmd/cache-server ./internal/server ./internal/cache ./internal/artifact + - name: Node cache server wrapper and lifecycle tests + run: node --test action/*.test.js + - name: Build packaged binaries + env: + VERSION: ci-${{ github.sha }} + run: scripts/build-dist.sh + - name: Verify packaged checksums and native server + env: + VERSION: ci-${{ github.sha }} + ARCHITECTURE: ${{ matrix.architecture }} + run: | + (cd dist && sha256sum --check SHA256SUMS) + test "$("dist/cache-server-windows-$ARCHITECTURE.exe" --version)" = "$VERSION" diff --git a/.github/workflows/optimiser-smoke.yml b/.github/workflows/optimiser-smoke.yml new file mode 100644 index 0000000..6b57575 --- /dev/null +++ b/.github/workflows/optimiser-smoke.yml @@ -0,0 +1,60 @@ +name: Optimiser smoke + +# This repository has no production cache to maintain. The only packed cache it +# owns is the one the cache smoke test writes, so this workflow exists to prove +# the optimiser works against a real GitHub Actions cache, which nothing else +# covers: the unit tests run entirely against an in-memory backend. + +on: + schedule: + # Weekly, purely to catch drift in the Actions REST and artifact APIs. + - cron: "17 4 * * 0" + workflow_dispatch: + inputs: + dry-run: + description: "Plan and report without publishing or deleting" + type: boolean + default: true + +permissions: + contents: read + +# Shared with the cache smoke test, which writes the same key prefix. Deleting +# packs out from under it would fail it for reasons that have nothing to do +# with the change under test. +concurrency: + group: bazel-smoke-cache + cancel-in-progress: false + +jobs: + optimise: + runs-on: ubuntu-24.04 + permissions: + contents: read + # Deleting the cache entries a pass replaces is the only thing that needs + # write. + actions: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: .go-version + cache: true + + # The action prefers a local dist/ over a release, so this exercises the + # code under review rather than a published binary. + - name: Build the optimiser under review + env: + VERSION: smoke-${{ github.sha }} + run: scripts/build-dist.sh + + - name: Optimise the smoke cache + uses: ./optimise + with: + github-token: ${{ github.token }} + # Written by the cache smoke test; this repository has no other. + key-prefix: bazel-http-smoke-car-v1 + # The smoke cache holds a single object, so the default window would + # never find enough to plan from. + min-runs: "1" + dry-run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry-run || 'false' }} diff --git a/.github/workflows/pre-release.yml b/.github/workflows/pre-release.yml new file mode 100644 index 0000000..659b463 --- /dev/null +++ b/.github/workflows/pre-release.yml @@ -0,0 +1,42 @@ +name: Pre-release + +on: + push: + branches: [main] + paths-ignore: + - "**/*.md" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pre-release + cancel-in-progress: false + +jobs: + pre-release: + runs-on: ubuntu-24.04 + permissions: + contents: write + id-token: write + attestations: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: .go-version + cache: true + - name: Choose a timestamped version + id: version + run: echo "version=pre-$(date -u +%Y%m%dT%H%M%SZ)" >> "$GITHUB_OUTPUT" + - name: Publish + uses: ./.github/actions/publish-release + with: + version: ${{ steps.version.outputs.version }} + prerelease: "true" + token: ${{ github.token }} + notes: | + Automatic pre-release built from `${{ github.sha }}` on `main`. + + Not intended for production use. Pin a `v*` release instead. diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..83181f0 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,68 @@ +name: Release + +on: + workflow_dispatch: + inputs: + version: + description: "Release tag, for example v0.4.0" + required: true + type: string + +permissions: + contents: read + +concurrency: + group: release + cancel-in-progress: false + +jobs: + release: + runs-on: ubuntu-24.04 + permissions: + contents: write + id-token: write + attestations: write + steps: + - name: Validate the requested version + env: + VERSION: ${{ inputs.version }} + run: | + set -euo pipefail + if [[ ! "$VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then + echo "version must look like v1.2.3 or v1.2.3-rc.1; got $VERSION" >&2 + exit 1 + fi + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Refuse to reuse an existing tag + env: + GH_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} + VERSION: ${{ inputs.version }} + run: | + set -euo pipefail + if gh api "repos/$REPOSITORY/git/ref/tags/$VERSION" >/dev/null 2>&1; then + echo "tag $VERSION already exists; immutable releases cannot reuse a tag" >&2 + exit 1 + fi + + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: .go-version + cache: true + + - name: Publish + uses: ./.github/actions/publish-release + with: + version: ${{ inputs.version }} + prerelease: "false" + token: ${{ github.token }} + notes: | + Release ${{ inputs.version }}, built from `${{ github.sha }}`. + + Pin this action with: + + ```yaml + uses: ${{ github.repository }}@${{ inputs.version }} + ``` diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index d47a6d3..aeae663 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -18,25 +18,49 @@ permissions: contents: read actions: read +# Shared with the optimiser smoke test, which rewrites the same key prefix. +concurrency: + group: bazel-smoke-cache + cancel-in-progress: false + jobs: smoke: - runs-on: ubuntu-24.04 + strategy: + matrix: + runner: [ubuntu-24.04, macos-15, windows-2025, windows-11-arm] + runs-on: ${{ matrix.runner }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: .go-version + cache: true + architecture: ${{ runner.arch == 'ARM64' && 'arm64' || 'x64' }} + # Build locally so the smoke test exercises this commit rather than a + # binary downloaded from a release. + - name: Build server binaries + shell: bash + env: + VERSION: smoke-${{ github.sha }} + run: scripts/build-dist.sh - id: cache name: Start cache adapter uses: ./ with: write: ${{ github.event_name == 'push' || inputs.mode == 'seed' }} key-prefix: bazel-http-smoke-car-v1 - storage-mode: packs - name: Prepare stable object id: object shell: bash run: | - printf '%s' 'bazel-github-actions-cache-v2-smoke-v0.2.0' > "$RUNNER_TEMP/cache-object" - digest=$(sha256sum "$RUNNER_TEMP/cache-object" | cut -d' ' -f1) - echo "digest=$digest" >> "$GITHUB_OUTPUT" + node <<'NODE' + const crypto = require("node:crypto"); + const fs = require("node:fs"); + const path = require("node:path"); + const data = Buffer.from("bazel-github-actions-cache-v2-smoke-v0.2.0"); + fs.writeFileSync(path.join(process.env.RUNNER_TEMP, "cache-object"), data); + fs.appendFileSync(process.env.GITHUB_OUTPUT, `digest=${crypto.createHash("sha256").update(data).digest("hex")}\n`); + NODE - name: Seed cache if: github.event_name == 'push' || inputs.mode == 'seed' shell: bash diff --git a/.gitignore b/.gitignore index 65c6f21..bf4070c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ coverage.out *.prof -dist/*.tmp +.tools/ +dist/ diff --git a/.go-version b/.go-version index f250c8f..d620158 100644 --- a/.go-version +++ b/.go-version @@ -1 +1 @@ -1.26.6 +1.27.4 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b1fcf32..82367af 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,12 +1,14 @@ # Contributing Issues and pull requests are welcome. Keep the adapter small, fail-open by -default, and compatible with Bazel's documented HTTP remote-cache protocol. +default, and compatible with Bazel's documented HTTP and gRPC remote-cache +protocols. Before submitting a change, run every command in the development section of -the README. Changes to the Go server require rebuilding both checked-in -binaries with the pinned Go version. Changes to GitHub cache behavior should -also pass two separate smoke workflow runs: seed first, then restore-only. +the README. Built binaries are not committed; CI builds them on demand and the +release workflows publish them as release assets. Changes to GitHub cache +behavior should also pass two separate smoke workflow runs: seed first, then +restore-only. Never log `ACTIONS_RUNTIME_TOKEN`, signed Azure Blob URLs, or the shutdown token. New third-party GitHub Actions must be pinned to a complete commit SHA. diff --git a/README.md b/README.md index 51a1f30..3a5753c 100644 --- a/README.md +++ b/README.md @@ -16,14 +16,28 @@ removes its private runner temporary directory. > This project is experimental. It uses the cache-v2 runner service exposed to > GitHub Actions, through `github.com/tonistiigi/go-actions-cache`. GitHub does > not document that runner upload/download protocol as a stable public API. +> Publishing the usage record likewise speaks the runner's artifact service +> directly, the same undocumented API behind `actions/upload-artifact`. > Pin this action to a full commit SHA and evaluate the limits below before > making it a required CI dependency. ## Usage +The cache server supports Linux amd64/arm64, Apple Silicon macOS runners +(for example, `runs-on: macos-15`), and Windows x64/ARM64 runners +(`windows-2025` and `windows-11-arm`). Intel macOS and 32-bit Windows are not supported. +The cache optimiser remains Linux-only. + +On Windows the action selects the native server using `RUNNER_ARCH`, even if +the action's Node runtime runs under x64 emulation on an ARM64 runner. Shutdown +uses the same authenticated HTTP endpoint on every platform; forced termination +is a last resort and cannot flush pending uploads. Private files inherit the +runner temporary directory's Windows ACLs rather than Unix permission bits. + ```yaml permissions: contents: read + actions: read steps: - uses: actions/checkout@ @@ -35,7 +49,7 @@ steps: - name: Test env: - CACHE_URL: ${{ steps.bazel-cache.outputs.url }} + CACHE_URL: ${{ steps.bazel-cache.outputs.grpc-url }} CACHE_WRITABLE: ${{ steps.bazel-cache.outputs.writable }} run: > bazel test //... @@ -43,6 +57,9 @@ steps: --remote_upload_local_results="$CACHE_WRITABLE" ``` +Swap `grpc-url` for `url` to use the HTTP endpoint instead; both serve the same +cache and either can be used without changing anything else. + `write: auto` is deliberately conservative: only a `push` to the repository's default branch publishes entries. Pull requests are read-only by default, and fork pull requests remain read-only even if `write: true` is requested. The @@ -55,17 +72,16 @@ Bazel. ### CARv2 packs and manifest DAGs -`storage-mode: packs` is the v0.3 storage format. Instead of creating one -GitHub cache entry for every CAS or Action Cache object, it writes many values -to a modest CARv2 archive (8 MiB by default) and publishes one immutable -DAG-CBOR manifest after that archive is available. A large output is placed in -its own archive. The result is normally two Actions-cache creations per pack -(one pack and one manifest), rather than one per Bazel object. +The cache stores objects in modest CARv2 archives (8 MiB by default) and +publishes one immutable DAG-CBOR manifest after each archive is available. +A large output is placed in its own archive. The result is normally two +Actions-cache creations per pack (one pack and one manifest), rather than one +per Bazel object. ```yaml permissions: contents: read - actions: read # manifest discovery for storage-mode: packs + actions: read # manifest discovery steps: - id: bazel-cache @@ -73,30 +89,100 @@ steps: with: write: auto key-prefix: ironmesh-bazel-car-v1 - storage-mode: packs pack-size-mb: "8" ``` The `github-token` input defaults to `${{ github.token }}` and is used only to list immutable manifest keys through GitHub's documented Actions-cache REST endpoint. It must have `actions: read`; no external service, secret, or write -token is needed. Keep the packed mode in a new `key-prefix`: it deliberately -does not reinterpret or mix v0.2 object keys. +token is needed. Use a new `key-prefix` when moving from an earlier release: +the packed format does not read or migrate legacy object-per-entry keys. Writers discover all current manifest heads at startup and make each new manifest a child of every head they observed. Parallel writers can therefore publish siblings without overwriting each other. Readers discover and merge all heads. If two manifests contain different Action Results for the same action digest, that digest is treated as a cache miss rather than picking one result. + +Each manifest key names the pack it commits: + +```text +-car-pack-v1- +-car-manifest-v2-- +``` + +Discovery lists both namespaces in full, newest first. Listing reads metadata +only, so it does not renew any entry's retention, and it is the download that is +worth limiting. Every mapping a manifest introduces lives in the pack its key +names, so a manifest missing from the pack listing is never downloaded. That +matters because reading a cache entry renews its retention: a small manifest +that is read on every run would otherwise outlive the large pack it describes +indefinitely, and GitHub would keep evicting packs instead. Unread manifests +simply expire. + +`max-manifests` is applied after that filter, so the budget is spent on +manifests that can still produce a cache hit rather than on orphans. +`manifests_orphaned`, `manifests_skipped`, and `pack_loads_skipped` report this +in the final statistics. + Manifest discovery is eventually consistent by design: an unseen manifest is only a temporary miss. +A `HEAD /cas/` is answered from the manifest view without restoring the +pack, so `--remote_download_minimal` builds do not pull archives they never +read. Because reading an entry is what resets its retention, a pack that only +ever answers presence checks would then be evicted while Bazel still depends on +it. The server therefore renews it explicitly: once per pack per job, batched +for `pack-renew-seconds` so a pack that gets downloaded in the meantime costs no +extra API call, and flushed at shutdown. A renewal resolves cache metadata +without transferring the pack, and is reported as `pack_renewals`. + +Action results use the same presence check. `GET /ac/` restores only the +pack holding the result itself, then confirms every referenced blob is mapped to +a pack that still exists and that its recorded size matches the action result. +An action result is a cache miss whenever any output is unmapped, or lives in a +pack that eviction has removed. Serving it renews the retention of every pack in +its closure, so a result that Bazel keeps hitting keeps its outputs alive even +when they are never downloaded. + +The tradeoff is deliberate: availability is judged from the manifest view and +the pack listing rather than by restoring every output. A pack that disappears +between discovery and a later fetch yields a miss on that fetch instead of +suppressing the action result up front. + The server flushes a pending pack when it reaches `pack-size-mb`, at least once per `pack-flush-seconds`, and unconditionally during the action post step. It uploads the CARv2 file first and the manifest second; the manifest is the commit point. Thus cancellation, eviction, a corrupt pack, or a missing output closure can only lose a cache hit and cannot supply incomplete build output. +### Pack compression + +Nothing between this server and GitHub compresses anything: the cache-v2 client +uploads bytes verbatim and registers the raw length, which is what the 10 GB +repository quota is charged. Pack blocks are therefore compressed here, with +zstd, before upload. + +Compression is per block rather than per pack, so the CARv2 index stays useful: +restoring a pack and serving one object decompresses that object alone instead +of expanding the whole archive. It also lets one pack mix compressed and +verbatim blocks, which matters when a build produces both text and +already-compressed artifacts such as OCI layers. + +A block is stored verbatim when compression cannot pay for itself: below 256 +bytes, or when the result is not at least 5% smaller. Objects larger than 1 MiB +are sampled first, so an incompressible one is rejected after a few hundred KB +rather than after compressing the whole thing. `compressed_blocks` and +`compression_saved_bytes` report the outcome. + +A compressed block is addressed in the pack by the digest of its compressed +bytes, and the manifest records that block CID alongside the object's own CID. +A reader verifies the stored block against the block CID, decompresses it under +a size bound taken from the manifest, and then verifies the result against the +object CID, so a corrupt or truncated block is a cache miss rather than bad +build input. Disabling `pack-compression` stops writing compressed blocks but +never stops reading them. + ### IronMesh example The action can replace the external-cache URL and token in the Bazel job: @@ -121,36 +207,443 @@ The action can replace the external-cache URL and token in the Bazel job: Do not enable Bazel remote-cache compression with this release. +### Hidden MODULE lockfile cache + +Bazel can omit sections for reproducible module extensions from the tracked +`MODULE.bazel.lock` and keep those stable results in the complete +`/MODULE.bazel.lock`. Enable `hidden-lockfile` to restore that +file before the job's Bazel commands: + +```yaml +- id: bazel-cache + uses: cre4ture/bazel-github-actions-cache-v2@ + with: + write: auto + hidden-lockfile: "true" + fail-on-hidden-lockfile-change: "true" + hidden-lockfile-key-files: | + pnpm-lock.yaml +``` + +The action always keys the hidden lockfile by the contents of `MODULE.bazel`, +the tracked `MODULE.bazel.lock`, `.bazelversion`, and the runner OS and +architecture. Add extension inputs that Bazel does not declare in +`MODULE.bazel` with `hidden-lockfile-key-files`, one workspace-relative path +per line. A changed additional file misses the primary key but permits fallback +to a recent lockfile with the same module graph, which Bazel can then update. + +At post-step, jobs for which the existing `write` input is enabled run +`bazel mod deps --lockfile_mode=update` and publish the complete hidden +lockfile unless its primary key was already an exact hit. Exact hits are still +refreshed and compared, but are not republished under their immutable key. +`write: auto` +therefore provides the same default-branch and fork protections as the remote +cache. Cache restore and save outages warn without failing the job. A missing +input file or a failed `bazel info` command fails the restore step; a failed +`bazel mod deps` command is warned at post-step so it cannot turn an otherwise +successful job into a cache failure. + +The post-step compares the restored hidden lockfile with the refreshed one, +including for exact primary-key hits. +Its `hidden-lockfile-changed` output and a dedicated workflow-summary section +report a change, which can indicate that a significant undeclared extension +input is missing from `hidden-lockfile-key-files`. A read-only job or failed +refresh is reported as `unknown` rather than implying a comparison succeeded. +Set `fail-on-hidden-lockfile-change: true` to fail the action cleanup only +when a lockfile restored from an existing cache key changes. In strict mode the +changed lockfile is not published, preventing an incomplete key from creating +a new entry. A first creation without an existing cache entry does not fail. + +`hidden-lockfile-cache-hit` is `true` only for an exact primary-key restore. +The output is false for a fallback restore or when hidden-lockfile caching is +disabled. + ## Inputs and outputs | Input | Default | Meaning | |---|---:|---| | `write` | `auto` | `auto`, `true`, or `false`; forks are always read-only | | `fail-on-cache-error` | `false` | Strict mode; by default backend failures degrade to misses/soft upload success | -| `key-prefix` | `bazel-http-v1` | Immutable namespace; change to invalidate entries | -| `storage-mode` | `objects` | `objects` (v0.2) or `packs` (CARv2 and manifest DAG) | -| `pack-size-mb` | `8` | Target size for a CARv2 archive; only for `packs`, 1–32 MiB | -| `pack-flush-seconds` | `30` | Maximum local staging interval; only for `packs` | -| `max-manifests` | `2048` | Bound on REST-discovered immutable manifests; only for `packs` | +| `hidden-lockfile` | `false` | Restore Bazel's hidden `/MODULE.bazel.lock`; writable jobs refresh and publish it | +| `hidden-lockfile-key-files` | `` | Additional workspace-relative lock/input files included in the primary key, one per line | +| `fail-on-hidden-lockfile-change` | `false` | Fail cleanup if a restored hidden lockfile changes; changed content is not published | +| `key-prefix` | `bazel-http-v1` | Immutable Bazel remote-cache namespace; change to invalidate those entries | +| `pack-size-mb` | `8` | Target size for a CARv2 archive, 1–32 MiB | +| `pack-flush-seconds` | `30` | Maximum local staging interval | +| `pack-renew-seconds` | `15` | Batching delay for pack retention renewals | +| `pack-compression` | `true` | Compress pack blocks with zstd | +| `pack-compression-level` | `3` | zstd level for pack blocks, 1–19 | +| `max-manifests` | `2048` | Maximum manifests downloaded during discovery | | `github-token` | `${{ github.token }}` | `actions: read` token for packed-manifest discovery | | `max-blob-size-mb` | `512` | Maximum spooled upload/download size | | `max-concurrent-operations` | `4` | Backend-operation backpressure | | `max-uploads-per-minute` | `180` | Evenly spaced uploads; must be below 200 | | `backend-timeout-seconds` | `300` | Timeout for one GitHub cache operation and initial packed-manifest discovery | | `port` | `0` | Loopback port; zero chooses a free dynamic port | +| `grpc-port` | `0` | Loopback port for the gRPC API; zero chooses a free dynamic port | +| `asset-header-routes` | `` | URI patterns, one per line, whose credentials the downloader may forward | +| `usage-artifact` | `bazel-cache-usage` | Job artifact to publish the usage record to; empty disables it | +| `log-artifact` | `bazel-cache-server-log` | Job artifact to publish the full server log to; empty disables it | + +The main step outputs `url`, `grpc-url`, `stats-url`, `writable`, `bazel-args`, +`grpc-bazel-args`, `initial-stats`, and `hidden-lockfile-cache-hit`. The post +step emits `hidden-lockfile-changed` and `final-stats`, and always writes the +final counts to the job summary. Because post steps run after normal job +steps, consume `stats-url` during the job if a later step must read it. + +### Server log + +The post step prints an excerpt of the server log to the job output: its first +lines, the start of any Go runtime crash (`panic:`, `fatal error:`, or +`runtime:`), and its last lines. A crash dump lists every goroutine, so without +the middle section the fatal error itself would scroll out of a plain tail. + +The whole log is also published as a job artifact named by `log-artifact`, +holding a single `cache-server.log`, including when the server never became +ready. A log over 256 MiB keeps its first and last 128 MiB. As with +`usage-artifact`, use a distinct name per instance if one job runs this action +more than once, or an empty string to opt out. A failed upload warns and never +fails the job. + +### Which entries a job used + +The post step publishes a job artifact named by `usage-artifact`, holding a +single `cache-usage.json`. It reports every cache entry the job touched, and +whether it was downloaded or only presence-checked: + +```json +{ + "entries": [ + {"kind": "cas", "digest": "…", "pack": "…", + "presence_checks": 1, "downloads": 0}, + {"kind": "cas", "digest": "…", "pack": "…", "size": 4096, + "presence_checks": 1, "downloads": 1} + ], + "packs": [{"id": "…", "size": 8388608, "declared_bytes": 9437184, + "bytes_used": 4096, "restored": true}], + "pack_bytes_restored": 8388608, + "pack_bytes_declared": 9437184, + "pack_bytes_used": 4096 +} +``` + +`size` is absent when nothing reported one. It is never defaulted to zero, +because zero is a real size belonging to a blob with a well-known digest. + +The distinction matters. Under `--remote_download_minimal` most outputs are only +ever presence-checked: they still have to exist, or the action result referencing +them becomes a miss, but nothing needs their bytes. An entry with no presence +checks and no downloads is the only kind nothing depends on. + +`pack_bytes_used` against `pack_bytes_declared` is the headline number. It is +the share of a restored pack's content a job turned out to want, so a low +ratio means packs are placing frequently and rarely fetched content together. +`pack_bytes_restored` is what the transfers actually cost; +because blocks are compressed it is not comparable with either of the other two, +and a ratio built on it can exceed 1. All three appear in the final statistics. + +To keep the record, nothing is required. Set `usage-artifact` to an empty string +to opt out, or to a distinct name per instance if one job runs this action more +than once, since artifact names must be unique within a job. A failed upload +warns and never fails the job. + +### Rebuilding the layout around how it is read + +Packs group whatever a job happened to produce together. Over time that stops +matching how they are read, and restoring one pack to get one blob pays for the +rest. A second action regroups pack contents around the usage records and +deletes what it replaces. + +Run the optimiser on a schedule, in its own workflow: + +```yaml +name: Optimise Bazel cache + +on: + schedule: + - cron: "17 4 * * 0" + workflow_dispatch: + +permissions: + contents: read + +# A second pass would plan against a view the first is already changing. +concurrency: + group: optimise-bazel-cache + cancel-in-progress: false + +jobs: + optimise: + runs-on: ubuntu-24.04 + permissions: + contents: read + # Deleting the cache entries this pass replaces is the only thing that + # needs write. + actions: write + steps: + - uses: cre4ture/bazel-github-actions-cache-v2/optimise@ + with: + github-token: ${{ github.token }} + key-prefix: bazel-http-v1 +``` -The main step outputs `url`, `stats-url`, `writable`, `bazel-args`, and -`initial-stats`. The post step emits `final-stats` and always writes the final -counts to the job summary. Because post steps run after normal job steps, -consume `stats-url` during the job if a later step must assert statistics. +`key-prefix` must match the one the cache action uses, and `usage-artifact` must +match where it publishes its records. The action writes a job summary and sets +`summary`, `rebuilt`, `deleted` and `reaped` outputs. + +Start with `dry-run: true`. It reports the same numbers without publishing or +deleting anything, and never even constructs a client that can delete: + +```yaml + - uses: cre4ture/bazel-github-actions-cache-v2/optimise@ + with: + github-token: ${{ github.token }} + dry-run: true +``` + +A pass rewrites packs in two independent ways, both gated by pack age. + +**Eviction** removes entries no job has used for `evict-after-hours`, which +defaults to GitHub's own 7-day expiry of unused caches. An entry counts as used +if any job downloaded it or checked that it exists. Readers check the outputs of +every action result they serve, so outputs that are still needed stay. Each +affected pack is rewritten on its own, without its stale entries, and nothing +else moves. Only packs at least `evict-after-hours` old are considered, since a +newer entry may simply not have been needed yet. A pack every entry of which is +stale is left alone: nothing restores it, so GitHub expires it. + +Eviction needs every usage record from the whole window, so the pass reads all +of them and not just the newest `max-records`. If any record in the window has +expired or cannot be read, or the listing does not reach back past the start of +the window, nothing is evicted and the job summary says why. An entry still +referenced by an action result can be evicted only if no job has used that +action result for the whole window either. Even then, the reader rejects the +incomplete action result, so the cost is a cache miss, never a broken build. +A job that publishes no record, because it was cancelled before its cleanup +step or its usage artifact is disabled, is invisible here. Entries only it used +can be evicted. + +**Reshaping** regroups packs whose shape is at least twice `evict-after-hours` +old, and only when there are at least two: one pack can only have its contents +shuffled. Entries are grouped by the set of runs that downloaded them, so +entries wanted by the same jobs share a pack, entries nothing downloads are +moved out of the way, and action results never share a pack with outputs. +Restoring a pack is charged `download-overhead-mb` on top of its bytes, so small +packs that the same jobs restore are merged into fewer downloads. + +A pack is considered for reshaping when `min-waste-fraction` of what a restore +pays for, counting that overhead, is not wanted. It is only reshaped when the +regrouping cuts its restore cost by `min-improvement`. That cut is measured on a +quarter of the recent runs that the regrouping was not fitted to. Measured on +the runs it was fitted to, any regrouping looks like an improvement, and every +pass would rebuild packs no grouping can actually help. + +A reshaped pack's age starts afresh, so it is not reshaped again for another two +eviction periods. A pack rewritten for eviction keeps its source's age, which +its manifest records, so cleaning a pack never postpones reshaping it. The job +summary reports what was evicted, how many packs were old enough to reshape, +and per job the overfetch and downloads before and after. + +| Input | Default | Purpose | +| --- | --- | --- | +| `github-token` | required | Needs `actions: write` | +| `key-prefix` | `bazel-http-v1` | Must match the cache action | +| `usage-artifact` | `bazel-cache-usage` | Must match the cache action | +| `max-records` | `25` | How many recent usage records (one per job) to plan from | +| `min-runs` | `3` | Refuses to plan from a smaller window | +| `pack-size-mb` | `8` | Target size of a rebuilt pack | +| `min-waste-fraction` | `0.25` | How wasteful a pack must be to be considered | +| `min-improvement` | `0.25` | How much of its restore cost a reshape must remove | +| `evict-after-hours` | `168` | Unused entries are evicted after this; reshaping waits twice as long | +| `download-overhead-mb` | `8` | What one pack download costs, in MiB it is worth | +| `max-new-mb` | `2048` | Stop once this much has been published | +| `uploads-per-minute` | `180` | Evenly spaced uploads; must be below 200 | +| `reap-unmanifested-packs` | `false` | Delete packs no manifest names | +| `reap-older-than-hours` | `24` | Age below which a pack is never reaped | +| `dry-run` | `false` | Plan and report only | + +A rebuilt pack is published before the one it replaces is deleted, so a cache +near its quota would briefly have to hold both layouts. `max-new-mb` bounds +that: a pass stops once it has published that much, and each source pack is +deleted as soon as every entry it served has been republished. Stopping early is +safe, because the packs not yet rebuilt were never touched. The next pass +re-plans from where this one left off. + +Three properties are worth knowing before enabling it: + +- **Nothing is deleted until its replacement is published.** An interrupted pass + leaves duplicated storage, never a hole. +- **Only disuse drops an entry.** The optimiser cannot prove a blob is + unreferenced from manifest metadata alone. It drops only entries no job has + used for `evict-after-hours`, and packs whose every copy already lost the + merge. A reader validates an action result's outputs before serving it, so + the worst an eviction can do is cause a miss. +- **A job running during the pass may lose hits, not data.** It resolved the old + layout and will find packs gone. Scheduling the pass when the repository is + quiet narrows that window; nothing can close it. + +It only applies from the default branch. A pass reads, rebuilds and deletes +entirely within the Git reference it runs on, so running it from a branch would +rebuild that branch's own caches rather than the ones jobs read. `dry-run` works +from any ref. + +Everything a pass touches belongs to one reference. The listing is narrowed to +it, so entries another branch owns never appear, and deletion names the same +reference, so a copy this pass never listed is never removed. That also means +the "not restorable here" count reflects genuine eviction rather than entries +that were only ever visible to another branch. + +A pack is never a deletion candidate unless the manifest describing it was read +successfully. + +### Reaping unreachable packs + +A reader only ever finds a pack through a manifest naming it, so a pack no +manifest names is unreachable and is pure storage cost. `reap-unmanifested-packs` +deletes those. It is off by default and is the one thing here that removes data +without publishing a replacement. + +Two things keep it from taking anything live. A pack whose manifest exists but +this job could not read is *not* unmanifested and is never a candidate, because +another ref may still be reading it. And `reap-older-than-hours` keeps a pack a +running job has published but not yet committed a manifest for out of reach: the +two are indistinguishable except by age. A pack whose creation time the listing +does not report is left alone. + +Fractions of an hour are accepted so that a test can reap something it has just +created. Anything under an hour warns, because it is short enough to take a pack +a running job is still publishing. + +A dry run applies the age filter and reports how many packs it would take, so +"packs old enough to reap" is the number to look at before enabling it. + +This is worth enabling when the job summary shows a large "packs no manifest +names" count, which usually means manifests were evicted while their packs +survived. + +The same option also deletes manifests whose pack is gone, subject to the same +age threshold. Readers already skip those, and they would expire unread within a +week, but until then they take quota. Packs get evicted for lack of quota, and +those evictions are what leave the manifests behind. Failing to delete one of +these manifests is logged rather than failing the pass. + +`min-runs` refuses to plan from too small a window, since a handful of records +describes those particular jobs rather than the repository. A pass with too few +records, or with nothing worth rebuilding, reports that in the job summary and +succeeds; a quiet week does not turn a scheduled workflow red. ## Protocol support -Supported: +The adapter serves two endpoints from one process against one cache: HTTP on +`url` and gRPC on `grpc-url`. Point Bazel at either with `--remote_cache`. The +gRPC endpoint is the faster of the two because `FindMissingBlobs` settles a +whole input closure in one call, where HTTP needs a `HEAD` per blob. + +Supported over HTTP: - `GET`, `HEAD`, and `PUT` on exactly `/cas/` - `GET`, `HEAD`, and `PUT` on exactly `/ac/` - mandatory `Content-Length` and identity encoding + +Supported over gRPC: + +- `ContentAddressableStorage.FindMissingBlobs`, `BatchUpdateBlobs`, + `BatchReadBlobs`, and `GetTree` +- `ActionCache.GetActionResult` and `UpdateActionResult` +- `Capabilities.GetCapabilities` +- `ByteStream.Read` and `Write` for blobs above the 4 MiB batch limit +- `asset.v1.Fetch.FetchBlob`, backing Bazel's remote downloader + +## Caching repository downloads + +Action and CAS caching never covers the archives that repository rules fetch, +because those are extracted outside the action graph. Bazel's remote downloader +closes that gap: + +```bash +bazel test //... \ + --remote_cache="$CACHE_URL" \ + --experimental_remote_downloader="$CACHE_URL" \ + --experimental_remote_downloader_local_fallback +``` + +The fallback flag matters: it defaults to `false`, and Bazel treats any non-OK +fetch as an error rather than a miss, so without it the first build that cannot +be served fails outright. + +A repository rule must declare a checksum for its download to be cached. Bazel +sends it as a `checksum.sri` qualifier, in any of the algorithms it supports: +`sha1`, `sha256`, `sha384`, `sha512`, and `blake3`. That matters in practice +because checksums arrive from lockfiles rather than by hand, and npm integrity +is `sha512`. When a rule declares no checksum Bazel explicitly forbids cached +content, and this server answers `NOT_FOUND`. + +Content is always stored under its sha256, so a `sha256` checksum addresses the +cache directly. Any other algorithm resolves through an alias recorded the first +time the asset was fetched. An alias is an action-cache record pointing at the +blob, which means the existing closure validation applies to it: an alias whose +blob has been evicted reads as a miss, and in packed mode it travels inside a +CARv2 pack and renews that pack's retention, rather than costing one +Actions-cache creation each. + +Bazel's downloader never pushes a fetched archive back, so a cache-only +implementation could never be populated. On a miss this server fetches the asset +itself, over `https` only, verifies it against the declared checksum before +storing anything, and publishes it so that later jobs get a hit. +`asset_downloads` and `asset_fetch_errors` report that activity. + +Private origins are supported through the `http_header` and `http_header_url` +qualifiers, so registries such as `ghcr.io` can be fetched through the cache. +It takes two opt-ins, because each side defaults to refusing. + +Bazel only sends credentials when you ask it to: + +``` +common --remote_downloader_propagate_credentials +``` + +Without that flag Bazel strips `Authorization`, `Proxy-Authorization` and +`Cookie` before the request leaves it, and an authenticated origin answers with +`401`. + +This server only forwards them to routes you name, one per line: + +```yaml +- uses: cre4ture/bazel-github-actions-cache-v2@ + with: + asset-header-routes: | + https://ghcr.io/v2/acme/* + https://*.jfrog.example/artifactory/ +``` + +A trailing `*` makes the path a prefix; without one the match still falls on a +segment boundary, so `https://ghcr.io/v2/acme` does not admit `/v2/acme-private`. +`*.example.com` covers subdomains but not the apex, and a different port is a +different origin. A request carrying a credential for any route you have not +named is refused outright rather than retried without it, so the asset is left +to Bazel's own downloader and never reaches the cache. Headers that carry no +credential need no route. + +That refusal is the mechanism for keeping a private asset out of a shared cache, +and it is worth understanding why you might want it: a fetched asset is stored +under its checksum in the same cache every job in the repository reads, so +content pulled with your credentials becomes readable by any job in that +repository. Name a route only when that is acceptable for the content behind it. + +Headers that decide routing or framing, such as `Host` and `Content-Length`, are +refused outright, as is any value containing a control character. Credentials do +not survive a redirect that leaves the origin they were issued for, matching what +browsers and `curl` do. Header values are never logged. + +Every failure names the resource it refers to, because Bazel reports the message +on its own: + +```text +WARNING: Remote Cache: NOT_FOUND: https://registry.npmjs.org/pkg/-/pkg-1.0.0.tgz: origin returned HTTP 401 +``` + +Supported by both: + - CAS SHA-256 verification before publication and after download - structural validation of REAPI `ActionResult`, `Tree`, and `Directory` messages @@ -158,28 +651,41 @@ Supported: - AC publication only after every referenced CAS object is persistent - implicit handling of the standard SHA-256 zero-byte CAS digest - immutable cache keys -- per-job coalescing of duplicate immutable `PUT`s before rate limiting and backend publication -- opt-in CARv2 archives with footer indexes, DAG-CBOR manifests, concurrent - writer head merging, and action-result conflict detection +- per-job coalescing of duplicate immutable uploads before rate limiting and backend publication +- CARv2 archives with footer indexes, DAG-CBOR manifests, concurrent + writer head merging, and deterministic resolution of conflicting action results Not currently supported: -- Bazel `instance_name` path prefixes -- HTTP or zstd remote-cache compression -- gRPC or remote execution +- Bazel `instance_name` prefixes; a non-empty one is rejected rather than ignored +- HTTP or zstd remote-cache compression, including `compressed-blobs` resources +- resumable `ByteStream` uploads; `QueryWriteStatus` always reports no progress +- `asset.v1.Push`, `FetchDirectory`, and authenticated asset origins +- remote execution - range requests - Windows or macOS runners ## Limits and operational model -The `objects` format maps every Bazel AC or CAS object to one GitHub Actions -cache entry. It remains the default rollback path. GitHub documents a limit of -200 cache creations per minute; the action defaults to 180 evenly spaced -uploads. In `packs` mode a successful flush consumes one creation for the CARv2 -pack and one for its manifest, so a large build graph is governed by pack count -instead of object count. `pack_uploads`, `manifest_uploads`, and +Earlier releases mapped every Bazel AC or CAS object to one GitHub Actions +cache entry. The current packed format avoids that scaling problem. GitHub +documents a limit of 200 cache creations per minute; the action defaults to +180 evenly spaced uploads. A successful flush consumes one creation for the +CARv2 pack and one for its manifest, so a large build graph is governed by pack +count instead of object count. `pack_uploads`, `manifest_uploads`, and `pack_downloads` make that distinction explicit in the final statistics. +Three counters describe load, and they deliberately do not agree: + +| Counter | Counts | Reading it | +| --- | --- | --- | +| `requests` | One per client call: an HTTP request, or a gRPC RPC | Over gRPC this should be far below `operations`; if it is not, the client is not batching | +| `operations` | One per cache object the client asked about | Comparable between HTTP and gRPC, so it measures the build rather than the protocol | +| `backend_requests` | One per call into the GitHub Actions cache | Tracks API pressure and quota risk; closure validation and packed reads raise it without any matching client call | + +Manifest discovery talks to the GitHub REST API instead, under a separate quota, +and is reported by `manifests_discovered` and `packs_discovered`. + GitHub's repository cache quota, eviction policy, and branch restrictions all apply. At the time of writing, the default repository quota is 10 GB and caches not accessed for seven days may be evicted. Pull-request caches are scoped, while @@ -190,8 +696,9 @@ correctness. Because GitHub evicts entries independently, an AC entry can outlive one of its referenced CAS entries. The adapter checks the complete output closure before serving or publishing an action result and degrades an incomplete closure to an -ordinary cache miss. In packed mode this restores and verifies each referenced -CARv2 pack and CAS block before serving the Action Result. One action result is +ordinary cache miss. In packed mode that check resolves each referenced blob +through the manifest view and the pack listing, without restoring the packs, and +renews their retention. One action result is limited to 100,000 distinct validation operations to bound amplification from a malformed cache entry. @@ -220,8 +727,8 @@ not a source of truth. The server binds only to `127.0.0.1` on a dynamic port. Its shutdown token is random, masked, stored only as action post-state, and never exposed as a normal output. The GitHub runtime token is inherited by the Go process but never -logged. Uploads are bounded on disk, backend concurrency is limited, and CAS -content is verified in both directions. +logged. Uploads are bounded on disk, request filesystem calls and backend +concurrency are limited, and CAS content is verified in both directions. Code running in the same job can still reach loopback, inspect its own runner environment, exhaust the job's local disk, or submit valid AC objects. Do not @@ -229,6 +736,12 @@ run untrusted code in a cache-writing job. Fork pull requests are forced read-only, but GitHub's general guidance about untrusted workflows and self-hosted runners still applies. +Serving Bazel's remote downloader means the server makes outbound requests to +URIs a caller supplies. Those are restricted to `https`, may not be redirected +off it, are bounded by `max-blob-size-mb`, and are discarded unless they match +the checksum the caller asked for. No credential is ever attached, so this +grants a caller nothing it could not already do by fetching the URI itself. + Action-cache values cannot be content-verified against the action digest (the digest addresses the action, not the serialized result). Cache poisoning is therefore controlled by restricting writes to trusted workflows. Their @@ -240,20 +753,78 @@ validated before use. The repository pins Go in `.go-version` and pins `go-actions-cache` to a full upstream commit through a Go pseudo-version. +REAPI messages are decoded with generated protobuf code (the opaque API of +`google.golang.org/protobuf`). The upstream `.proto` sources are vendored under +`proto/` and the generated Go code is committed under `internal/proto/gen`, so +the commands below need neither `buf` nor `protoc`. Run +`scripts/generate-proto.sh` after changing the vendored definitions or the +pinned generator versions. + ```bash go test -race ./... go vet ./... go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./... +go tool deadcode -test ./... go run golang.org/x/vuln/cmd/govulncheck@v1.6.0 ./... -node --test action/*.test.js -VERSION=v0.3.2 scripts/build-dist.sh -git diff --exit-code -- dist -(cd dist && sha256sum --check SHA256SUMS) +node --test action/*.test.js optimise/*.test.js +VERSION=dev scripts/build-dist.sh +(cd dist && shasum -a 256 --check SHA256SUMS) ``` Release binaries are built with `CGO_ENABLED=0`, `-trimpath`, and an empty Go -build ID, with VCS stamping disabled, for deterministic Linux amd64/arm64 output. CI rebuilds them and -requires a byte-for-byte match. +build ID, with VCS stamping disabled, for deterministic Linux amd64/arm64 +output for both programs, plus macOS arm64 and Windows amd64/arm64 output for +the cache server only. +CI builds them twice and requires both builds to produce identical checksums, +and runs native cache server tests on Apple Silicon macOS and both Windows +architectures. Windows ARM64 Go tests run without the unsupported race detector. +Build scripts use Bash (Git Bash on Windows). For checksum verification on +Windows, use `(cd dist && sha256sum --check SHA256SUMS)` instead of `shasum`. + +`dist/` is not tracked in Git, and neither is any other build output. Both +actions resolve their binary in two steps: + +1. If `dist/--` exists in the checkout (`os` is `linux`, + `darwin`, or `windows`, with `.exe` appended on Windows), it is used + directly. This is how local development, CI, and the smoke workflow exercise + the code under review rather than a published artifact. +2. Otherwise the binary is downloaded from the release the action itself was + pinned to, and its build provenance is verified with + `gh attestation verify` before it is allowed to run. + +Nothing in the repository records which release to use. `GITHUB_ACTION_REF` is +the ref from your `uses:` line, so `@v0.4.0` names its release directly, and a +commit pin is mapped back to the tag released from it. `GITHUB_ACTION_REPOSITORY` +supplies the repository, so a fork downloads its own releases instead of binaries +built from somebody else's source, with nothing to edit after forking. + +Integrity rests on +[artifact attestations](https://docs.github.com/en/actions/concepts/security/artifact-attestations): +the release workflows sign the binaries with `actions/attest-build-provenance`, +and the action refuses to run one that does not verify against the publishing +repository. Only someone who can add a workflow to that repository can produce a +passing attestation, so no checksum has to be committed alongside the action. + +## Releases + +Both release workflows include `cache-server-darwin-arm64`, +`cache-server-windows-amd64.exe`, and `cache-server-windows-arm64.exe`, their +SHA-256 checksums in `SHA256SUMS`, and build provenance alongside the Linux +binaries. No macOS or Windows optimiser binary is published. + +Release tags point at the reviewed commit itself, so the tree a consumer checks +out is exactly the tree CI ran against. Enable +[immutable releases](https://docs.github.com/en/code-security/concepts/supply-chain-security/immutable-releases) +on the repository to lock those tags and assets after publication; the workflows +already draft, attach, then publish, which is the order that requires. + +| Workflow | Trigger | Tag | Marked | +| --- | --- | --- | --- | +| `Pre-release` | push to `main` | `pre-` | pre-release | +| `Release` | `workflow_dispatch` with a `version` input | the given `v*` tag | latest | + +Neither workflow commits anything. A release is a tag, a set of assets, and an +attestation; the default branch is never rewritten by CI. The smoke workflow has two modes. A default-branch push seeds a stable packed object. A separate `workflow_dispatch` restore run downloads the manifest and diff --git a/action.yml b/action.yml index c462575..24014d1 100644 --- a/action.yml +++ b/action.yml @@ -13,28 +13,48 @@ inputs: description: "Fail Bazel requests when GitHub cache is unavailable instead of degrading to misses/soft upload success" required: false default: "false" + hidden-lockfile: + description: "Restore Bazel's hidden output-base MODULE.bazel.lock; writable jobs refresh and publish it during cleanup" + required: false + default: "false" + hidden-lockfile-key-files: + description: "Newline-separated workspace-relative files whose contents additionally key the hidden lockfile" + required: false + default: "" + fail-on-hidden-lockfile-change: + description: "Fail cleanup when a post-step refresh changes a hidden lockfile restored from an existing cache key" + required: false + default: "false" key-prefix: - description: "Immutable GitHub cache-key namespace; change it to invalidate all entries" + description: "Immutable remote-cache key namespace; change it to invalidate all Bazel remote-cache entries" required: false default: bazel-http-v1 - storage-mode: - description: "objects keeps the v0.2 object-per-entry format; packs enables CARv2 packs and manifest DAGs" - required: false - default: objects pack-size-mb: - description: "Target CARv2 pack size in MiB when storage-mode is packs (1-32)" + description: "Target CARv2 pack size in MiB (1-32)" required: false default: "8" pack-flush-seconds: description: "Maximum seconds that staged CARv2 objects wait before publication" required: false default: "30" + pack-renew-seconds: + description: "Seconds that pack retention renewals are batched before being sent; renewals also flush at shutdown" + required: false + default: "15" + pack-compression: + description: "Compress individual pack blocks with zstd when they shrink meaningfully" + required: false + default: "true" + pack-compression-level: + description: "zstd level used for pack blocks (1-19); higher trades flush time for size" + required: false + default: "3" max-manifests: - description: "Maximum immutable manifest entries to discover through the GitHub Actions REST API" + description: "Maximum manifests to download during discovery; any beyond this are ignored and become cache misses" required: false default: "2048" github-token: - description: "GitHub token with actions: read, used only by storage-mode=packs to discover manifest cache keys" + description: "GitHub token with actions: read to discover manifest cache keys" required: false default: ${{ github.token }} max-blob-size-mb: @@ -57,17 +77,41 @@ inputs: description: "Loopback port; zero selects an available dynamic port" required: false default: "0" + grpc-port: + description: "Loopback port for the gRPC remote-cache API; zero selects an available dynamic port" + required: false + default: "0" + usage-artifact: + description: "Publish the cache usage record as a job artifact during cleanup; set to an empty string to disable" + required: false + default: bazel-cache-usage + log-artifact: + description: "Publish the full cache server log as a job artifact during cleanup; set to an empty string to disable" + required: false + default: bazel-cache-server-log + asset-header-routes: + description: "Newline-separated https URI patterns, such as https://ghcr.io/v2/acme/*, whose credentials the remote downloader may forward to the origin. Empty refuses every one, leaving authenticated assets to Bazel rather than caching them where the whole repository can read them" + required: false + default: "" outputs: url: description: "Loopback Bazel HTTP remote-cache URL" + grpc-url: + description: "Loopback Bazel gRPC remote-cache URL" stats-url: description: "Loopback JSON statistics endpoint available until the post-step" writable: description: "Whether validated objects are published to GitHub Actions cache" bazel-args: - description: "Ready-to-use --remote_cache and --remote_upload_local_results flags" + description: "Ready-to-use --remote_cache and --remote_upload_local_results flags for the HTTP endpoint" + grpc-bazel-args: + description: "Ready-to-use --remote_cache and --remote_upload_local_results flags for the gRPC endpoint" initial-stats: description: "Initial statistics JSON" + hidden-lockfile-cache-hit: + description: "Whether the hidden lockfile was restored from its primary key" + hidden-lockfile-changed: + description: "Whether the hidden lockfile changed during the post-step refresh; unknown when not refreshed" final-stats: description: "Final statistics JSON emitted during post cleanup; also written to the job summary" runs: diff --git a/action/lib.js b/action/lib.js index a66b2e0..2460bcf 100644 --- a/action/lib.js +++ b/action/lib.js @@ -111,12 +111,94 @@ function safeTemporaryDirectory(candidate) { return resolved; } +const BYTE_UNITS = [ + ["TiB", 1024 ** 4], + ["GiB", 1024 ** 3], + ["MiB", 1024 ** 2], + ["KiB", 1024], + ["B", 1], +]; + +// formatCount groups digits so a long number can be read at a glance. The +// locale is fixed so a job summary does not depend on the runner's. +function formatCount(value) { + const number = Number(value); + if (!Number.isFinite(number)) return String(value); + return number.toLocaleString("en-US"); +} + +// formatBytes renders a size in the largest unit that fits, as "2.32GiB". +// Trailing zeros are dropped so a round number stays short. +function formatBytes(value) { + const total = Number(value); + if (!Number.isFinite(total)) return String(value); + if (total < 0) return `-${formatBytes(-total)}`; + for (const [unit, size] of BYTE_UNITS) { + // Bytes are the floor, so anything under a kibibyte lands there. + if (total < size && size > 1) continue; + const scaled = (total / size).toFixed(3).replace(/0+$/, "").replace(/\.$/, ""); + const [integer, fraction] = scaled.split("."); + return `${formatCount(integer)}${fraction ? `.${fraction}` : ""}${unit}`; + } + return "0B"; +} + +// The first line of a Go runtime crash: a panic, a fatal error, or the +// runtime's own diagnostic that precedes some fatal errors. +const crashLine = /^(?:panic: |fatal error: |runtime: )/m; + +function omission(count) { + return `[... ${formatCount(count)} characters omitted ...]\n`; +} + +// logExcerpt keeps a log readable in the job output. Its head shows how the +// server started, its tail what it did last, and the start of a crash is kept +// in between because a runtime dump lists every goroutine and pushes the fatal +// error itself far out of the tail. Cuts fall on line boundaries. +function logExcerpt(text, { headChars = 4000, crashChars = 4000, tailChars = 16000 } = {}) { + if (text.length <= headChars + crashChars + tailChars) { + return text; + } + const cutBefore = (limit) => { + const newline = text.lastIndexOf("\n", limit - 1); + return newline >= 0 ? newline + 1 : limit; + }; + const cutAfter = (start) => { + const newline = text.indexOf("\n", start); + return newline >= 0 ? newline + 1 : start; + }; + + const headEnd = cutBefore(headChars); + const tailStart = Math.max(headEnd, cutAfter(text.length - tailChars)); + const ranges = [[0, headEnd]]; + const crash = crashLine.exec(text.slice(headEnd, tailStart)); + if (crash) { + const start = headEnd + crash.index; + ranges.push([start, Math.min(tailStart, cutBefore(start + crashChars))]); + } + ranges.push([tailStart, text.length]); + + let excerpt = ""; + let previousEnd = 0; + for (const [start, end] of ranges) { + if (start > previousEnd) { + excerpt += omission(start - previousEnd); + } + excerpt += text.slice(start, end); + previousEnd = end; + } + return excerpt; +} + module.exports = { appendCommand, booleanFlag, eventPayload, + formatBytes, + formatCount, input, isForkPullRequest, + logExcerpt, mask, parseBoolean, request, diff --git a/action/lib.test.js b/action/lib.test.js index 346e069..a655421 100644 --- a/action/lib.test.js +++ b/action/lib.test.js @@ -7,8 +7,11 @@ const path = require("node:path"); const test = require("node:test"); const { appendCommand, + formatBytes, + formatCount, booleanFlag, isForkPullRequest, + logExcerpt, resolveWriteMode, safeTemporaryDirectory, } = require("./lib"); @@ -60,3 +63,82 @@ test("Go boolean flags use equals syntax", () => { assert.equal(booleanFlag("fail-open", false), "--fail-open=false"); assert.throws(() => booleanFlag("unsafe flag", true)); }); + +test("byte sizes use the largest unit that fits", () => { + assert.equal(formatBytes(0), "0B"); + assert.equal(formatBytes(12), "12B"); + assert.equal(formatBytes(1023), "1,023B"); + assert.equal(formatBytes(1024), "1KiB"); + assert.equal(formatBytes(2491416576), "2.32GiB"); + assert.equal(formatBytes(241432494), "230.248MiB"); + assert.equal(formatBytes(1024 ** 4 * 3), "3TiB"); + // Trailing zeros go, so a round size stays short. + assert.equal(formatBytes(2 * 1024 ** 2), "2MiB"); + assert.equal(formatBytes(-1024), "-1KiB"); +}); + +test("long counts are grouped so they can be read", () => { + assert.equal(formatCount(0), "0"); + assert.equal(formatCount(999), "999"); + assert.equal(formatCount(999999), "999,999"); + assert.equal(formatCount(1000000), "1,000,000"); +}); + +function crashLog({ before = 2000, goroutines = 5000 } = {}) { + const lines = ["bazel-gha-cache: ready on http://127.0.0.1:1234"]; + for (let i = 0; i < before; i += 1) lines.push(`bazel-gha-cache: request ${i}`); + lines.push("runtime: program exceeds 10000-thread limit", "fatal error: thread exhaustion", ""); + for (let i = 0; i < goroutines; i += 1) lines.push(`goroutine ${i} gp=0x1 m=nil [select]:`); + return `${lines.join("\n")}\n`; +} + +test("a short log is printed whole", () => { + const log = "ready\nstopped\n"; + assert.equal(logExcerpt(log), log); +}); + +// The tail alone held only goroutine traces when the server crashed in CI, so +// neither its start nor the fatal error was visible. +test("a long log keeps its head, the start of a crash, and its tail", () => { + const log = crashLog(); + const excerpt = logExcerpt(log); + assert.ok(excerpt.length < 25_000, `excerpt is ${excerpt.length} characters`); + assert.ok(excerpt.startsWith("bazel-gha-cache: ready on http://127.0.0.1:1234\n")); + assert.match(excerpt, /^runtime: program exceeds 10000-thread limit\nfatal error: thread exhaustion\n/m); + assert.ok(excerpt.endsWith("goroutine 4999 gp=0x1 m=nil [select]:\n")); + assert.equal([...excerpt.matchAll(/^\[\.\.\. [\d,]+ characters omitted \.\.\.\]$/gm)].length, 2); +}); + +test("excerpts only cut on line boundaries", () => { + const excerpt = logExcerpt(crashLog()); + const original = new Set(crashLog().split("\n")); + for (const line of excerpt.split("\n")) { + assert.ok(original.has(line) || /^\[\.\.\. /.test(line), `partial line ${JSON.stringify(line)}`); + } +}); + +test("omitted counts account for every character left out", () => { + const log = crashLog(); + const excerpt = logExcerpt(log); + const omitted = [...excerpt.matchAll(/^\[\.\.\. ([\d,]+) characters omitted \.\.\.\]\n/gm)]; + const kept = omitted.reduce((length, match) => length - match[0].length, excerpt.length); + const dropped = omitted.reduce((total, match) => total + Number(match[1].replaceAll(",", "")), 0); + assert.equal(kept + dropped, log.length); +}); + +test("a crash already inside the head or tail is not repeated", () => { + const early = logExcerpt(crashLog({ before: 10 })); + assert.equal(early.match(/fatal error: thread exhaustion/g).length, 1); + assert.equal([...early.matchAll(/characters omitted/g)].length, 1); + const late = logExcerpt(crashLog({ goroutines: 10 })); + assert.equal(late.match(/fatal error: thread exhaustion/g).length, 1); + assert.equal([...late.matchAll(/characters omitted/g)].length, 1); +}); + +test("a long log without a crash keeps only its head and tail", () => { + const lines = []; + for (let i = 0; i < 5000; i += 1) lines.push(`bazel-gha-cache: request ${i}`); + const excerpt = logExcerpt(`${lines.join("\n")}\n`); + assert.equal([...excerpt.matchAll(/characters omitted/g)].length, 1); + assert.ok(excerpt.endsWith("bazel-gha-cache: request 4999\n")); +}); diff --git a/action/lifecycle.test.js b/action/lifecycle.test.js new file mode 100644 index 0000000..1668f83 --- /dev/null +++ b/action/lifecycle.test.js @@ -0,0 +1,195 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const crypto = require("node:crypto"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { spawn, spawnSync } = require("node:child_process"); +const { after, before, test } = require("node:test"); +const { serverArchitecture } = require("./main"); +const { processExists, waitForProcessExit } = require("./post"); +const { assetName } = require("./release"); + +const repoRoot = path.resolve(__dirname, ".."); +const architecture = serverArchitecture( + process.platform, + process.platform === "win32" && process.env.RUNNER_ARCH + ? process.env.RUNNER_ARCH.toLowerCase() + : process.arch, +); +let root; +let tools; +let action; +let catalogServer; +let catalogPort; + +before(async () => { + catalogServer = spawn(process.execPath, ["-e", ` + require("node:http").createServer((_request, response) => { + response.writeHead(200, { "Content-Type": "application/json" }); + response.end('{"actions_caches":[]}'); + }).listen(0, "127.0.0.1", function () { + process.stdout.write(String(this.address().port)); + }); + `], { stdio: ["ignore", "pipe", "inherit"] }); + catalogPort = await new Promise((resolve, reject) => { + catalogServer.once("error", reject); + catalogServer.stdout.once("data", (data) => resolve(Number(data.toString()))); + }); + root = fs.mkdtempSync(path.join(os.tmpdir(), "cache lifecycle ")); + tools = path.join(root, "tools"); + action = path.join(root, "action"); + fs.mkdirSync(action); + for (const name of ["main.js", "post.js", "lib.js", "release.js"]) { + fs.copyFileSync(path.join(__dirname, name), path.join(action, name)); + } + const binary = path.join( + tools, "bazel-gha-cache-server", "lifecycle", architecture, + assetName("cache-server", architecture, process.platform), + ); + fs.mkdirSync(path.dirname(binary), { recursive: true }); + const build = spawnSync("go", ["build", "-o", binary, "./cmd/cache-server"], { + cwd: repoRoot, + env: { + ...process.env, + CGO_ENABLED: "0", + GOOS: process.platform === "win32" ? "windows" : process.platform, + GOARCH: architecture, + }, + encoding: "utf8", + timeout: 120_000, + }); + assert.ifError(build.error); + assert.equal(build.status, 0, build.stdout + build.stderr); +}); + +after(async () => { + if (catalogServer?.exitCode === null) { + catalogServer.kill(); + await new Promise((resolve) => catalogServer.once("exit", resolve)); + } + if (root) fs.rmSync(root, { recursive: true, force: true }); +}); + +function values(file) { + return Object.fromEntries(fs.readFileSync(file, "utf8").trim().split("\n").map((line) => { + const at = line.indexOf("="); + return [line.slice(0, at), line.slice(at + 1)]; + })); +} + +function runtimeToken() { + const encode = (value) => Buffer.from(JSON.stringify(value)).toString("base64url"); + const now = Math.floor(Date.now() / 1000); + return `${encode({ alg: "HS256" })}.${encode({ ac: "[]", nbf: now - 60, exp: now + 3600 })}.test`; +} + +function start(t, inputs = {}) { + const runnerTemp = fs.mkdtempSync(path.join(root, "runner temp ")); + const stateFile = path.join(runnerTemp, "state"); + const outputFile = path.join(runnerTemp, "output"); + const env = { + // Use only synthetic credentials: these tests never contact GitHub. + PATH: process.env.PATH, + SystemRoot: process.env.SystemRoot, + RUNNER_ARCH: process.env.RUNNER_ARCH, + RUNNER_TEMP: runnerTemp, + RUNNER_TOOL_CACHE: tools, + GITHUB_ACTION_REPOSITORY: "cre4ture/bazel-github-actions-cache-v2", + GITHUB_ACTION_REF: "lifecycle", + GITHUB_REPOSITORY: "cre4ture/bazel-github-actions-cache-v2", + GITHUB_API_URL: `http://127.0.0.1:${catalogPort}`, + "INPUT_GITHUB-TOKEN": "synthetic-token", + GITHUB_STATE: stateFile, + GITHUB_OUTPUT: outputFile, + ACTIONS_CACHE_SERVICE_V2: "true", + ACTIONS_RESULTS_URL: "https://results.example.invalid/", + ACTIONS_RUNTIME_TOKEN: runtimeToken(), + "INPUT_WRITE": "false", + "INPUT_USAGE-ARTIFACT": "", + "INPUT_LOG-ARTIFACT": "", + ...inputs, + }; + t.after(async () => { + if (!fs.existsSync(stateFile)) return; + const pid = Number(values(stateFile).pid); + if (Number.isSafeInteger(pid) && pid > 0 && processExists(pid)) { + process.kill(pid, "SIGKILL"); + assert.ok(await waitForProcessExit(pid, 10_000), "test server did not exit"); + } + }); + const result = spawnSync(process.execPath, [path.join(action, "main.js")], { + env, encoding: "utf8", timeout: 25_000, + }); + assert.ifError(result.error); + const state = values(stateFile); + return { result, state, env, outputFile }; +} + +function finish(run, overrides = {}) { + const result = spawnSync(process.execPath, [path.join(action, "post.js")], { + env: { + ...run.env, + ...Object.fromEntries(Object.entries(run.state).map(([key, value]) => [`STATE_${key}`, value])), + ...overrides, + }, + encoding: "utf8", + timeout: 20_000, + }); + assert.ifError(result.error); + assert.equal(result.status, 0, result.stdout + result.stderr); + assert.doesNotMatch(result.stderr, /::warning::/); + return result; +} + +test("the detached server survives the main step and shuts down before cleanup", async (t) => { + const run = start(t); + assert.equal(run.result.status, 0, run.result.stdout + run.result.stderr); + assert.ok(processExists(Number(run.state.pid))); + if (process.platform === "win32") assert.ok(run.state.binary.endsWith(".exe")); + const payload = Buffer.from("cross-platform cache server lifecycle"); + const digest = crypto.createHash("sha256").update(payload).digest("hex"); + assert.equal((await fetch(`${run.state.url}/ready`)).status, 200); + const upload = await fetch(`${run.state.url}/cas/${digest}`, { method: "PUT", body: payload }); + assert.equal(upload.status, 204); + const download = await fetch(`${run.state.url}/cas/${digest}`); + assert.equal(download.status, 200); + assert.deepEqual(Buffer.from(await download.arrayBuffer()), payload); + finish(run); + assert.ok(!processExists(Number(run.state.pid))); + assert.ok(!fs.existsSync(run.state.temp_dir), "post-step left its temporary directory behind"); + const stats = JSON.parse(values(run.outputFile)["final-stats"]); + assert.equal(stats.discarded_uploads, 1); + assert.equal(stats.hits, 1); +}); + +test("a server without readiness state is terminated before cleanup", (t) => { + const run = start(t); + assert.equal(run.result.status, 0, run.result.stdout + run.result.stderr); + const result = spawnSync(process.execPath, [path.join(action, "post.js")], { + env: { + ...run.env, + ...Object.fromEntries(Object.entries(run.state).map(([key, value]) => [`STATE_${key}`, value])), + STATE_url: "", + }, + encoding: "utf8", + timeout: 20_000, + }); + assert.ifError(result.error); + assert.equal(result.status, 0, result.stdout + result.stderr); + assert.match(result.stderr, /did not stop gracefully; terminating it/); + assert.doesNotMatch(result.stderr, /cannot remove|still running|cannot terminate/); + assert.ok(!processExists(Number(run.state.pid))); + assert.ok(!fs.existsSync(run.state.temp_dir)); +}); + +test("failed server startup retains cleanup state and leaves no temporary directory", (t) => { + const run = start(t, { ACTIONS_RUNTIME_TOKEN: "invalid-token" }); + assert.equal(run.result.status, 1); + assert.match(run.result.stderr, /cache server did not become ready/); + assert.ok(run.state.pid); + assert.ok(!run.state.url); + finish(run); + assert.ok(!fs.existsSync(run.state.temp_dir)); +}); diff --git a/action/main.js b/action/main.js index 5740db4..181e426 100644 --- a/action/main.js +++ b/action/main.js @@ -4,10 +4,11 @@ const crypto = require("node:crypto"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); -const { spawn } = require("node:child_process"); +const { spawn, spawnSync } = require("node:child_process"); const { input, booleanFlag, + logExcerpt, mask, parseBoolean, request, @@ -16,14 +17,22 @@ const { saveState, setOutput, } = require("./lib"); +const { resolveBinary } = require("./release"); const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); -function startupTimeoutMilliseconds(storageMode, backendTimeoutSeconds) { - // Packed mode restores every discoverable manifest before accepting Bazel - // requests. Its server-side discovery already has this deadline, so the - // wrapper must not report a false startup failure after a fixed 15 seconds. - return (storageMode === "packs" ? backendTimeoutSeconds : 15) * 1000; +function startupTimeoutMilliseconds(backendTimeoutSeconds) { + // The server restores every discoverable manifest before accepting Bazel + // requests, so startup may take as long as backend discovery. + return backendTimeoutSeconds * 1000; +} + +function artifactName(name) { + const value = input(name, "").trim(); + if (value && !/^[A-Za-z0-9._-]{1,180}$/.test(value)) { + throw new Error(`${name} must match [A-Za-z0-9._-]{1,180}`); + } + return value; } function positiveInteger(name, fallback, maximum = Number.MAX_SAFE_INTEGER) { @@ -34,25 +43,96 @@ function positiveInteger(name, fallback, maximum = Number.MAX_SAFE_INTEGER) { return value; } -async function main() { - if (process.platform !== "linux") { - throw new Error("this release supports Linux GitHub Actions runners only"); +function portNumber(name) { + const value = Number.parseInt(input(name, "0"), 10); + if (!Number.isSafeInteger(value) || value < 0 || value > 65535) { + throw new Error(`${name} must be an integer between 0 and 65535`); } - if (process.env.ACTIONS_CACHE_SERVICE_V2?.toLowerCase() !== "true") { - throw new Error("GitHub Actions cache v2 is unavailable (ACTIONS_CACHE_SERVICE_V2 != true)"); + return value; +} + +function keyFileList(value) { + return String(value) + .split(/\r?\n/) + .map((entry) => entry.trim()) + .filter(Boolean); +} + +function restoreHiddenLockfile({ + binary, + workspace, + keyFiles, + timeoutSeconds, + spawn = spawnSync, + warn = (message) => process.stderr.write(message), +}) { + const args = [ + "hidden-lockfile", + "restore", + "--workspace", + workspace, + "--timeout", + `${timeoutSeconds}s`, + ...keyFiles.flatMap((file) => ["--key-file", file]), + ]; + const result = spawn(binary, args, { + encoding: "utf8", + timeout: (timeoutSeconds + 30) * 1000, + stdio: ["ignore", "pipe", "pipe"], + }); + if (result.error || result.status !== 0) { + const reason = result.error?.message || String(result.stderr || "").trim() || `exit status ${result.status}`; + throw new Error(`cannot restore the hidden Bazel lockfile: ${reason}`); } - if (!process.env.ACTIONS_RESULTS_URL || !process.env.ACTIONS_RUNTIME_TOKEN) { - throw new Error("GitHub Actions cache v2 credentials are unavailable in this step"); + let restored; + try { + restored = JSON.parse(result.stdout); + } catch (error) { + throw new Error(`cannot parse hidden Bazel lockfile restore result: ${error.message}`); + } + if ( + typeof restored.lockfile !== "string" || + typeof restored.primary_key !== "string" || + typeof restored.cache_hit !== "boolean" || + (restored.matched_key !== undefined && typeof restored.matched_key !== "string") || + (restored.warnings !== undefined && !Array.isArray(restored.warnings)) + ) { + throw new Error("hidden Bazel lockfile restore returned invalid metadata"); + } + for (const warning of restored.warnings || []) { + warn(`::warning::hidden Bazel lockfile restore: ${String(warning).replaceAll("\n", " ")}\n`); } + return restored; +} - const architecture = { x64: "amd64", arm64: "arm64" }[process.arch]; +function serverArchitecture(platform, arch) { + if (!["linux", "darwin", "win32"].includes(platform)) { + throw new Error("this release supports Linux, Apple Silicon macOS, and Windows GitHub Actions runners only"); + } + if (platform === "darwin" && arch !== "arm64") { + throw new Error(`macOS requires Apple Silicon (arm64); unsupported architecture: ${arch}`); + } + const architecture = { x64: "amd64", arm64: "arm64" }[arch]; if (!architecture) { - throw new Error(`unsupported Linux architecture: ${process.arch}`); + throw new Error(`unsupported ${platform === "win32" ? "Windows" : "Linux"} architecture: ${arch}`); + } + return architecture; +} + +async function main() { + // An ARM64 Windows runner may execute the action's Node runtime under x64 + // emulation. Select the native server from the runner's architecture. + const architecture = serverArchitecture( + process.platform, + process.platform === "win32" && process.env.RUNNER_ARCH + ? process.env.RUNNER_ARCH.toLowerCase() + : process.arch, + ); + if (process.env.ACTIONS_CACHE_SERVICE_V2?.toLowerCase() !== "true") { + throw new Error("GitHub Actions cache v2 is unavailable (ACTIONS_CACHE_SERVICE_V2 != true)"); } - const actionRoot = path.resolve(__dirname, ".."); - const binary = path.join(actionRoot, "dist", `cache-server-linux-${architecture}`); - if (!fs.existsSync(binary)) { - throw new Error(`packaged server binary is missing: ${binary}`); + if (!process.env.ACTIONS_RESULTS_URL || !process.env.ACTIONS_RUNTIME_TOKEN) { + throw new Error("GitHub Actions cache v2 credentials are unavailable in this step"); } const writeEnabled = resolveWriteMode(input("write", "auto")); @@ -61,27 +141,42 @@ async function main() { const maxConcurrent = positiveInteger("max-concurrent-operations", 4, 32); const uploadsPerMinute = positiveInteger("max-uploads-per-minute", 180, 199); const backendTimeoutSeconds = positiveInteger("backend-timeout-seconds", 300, 3600); - const storageMode = input("storage-mode", "objects").trim().toLowerCase(); - if (!["objects", "packs"].includes(storageMode)) { - throw new Error("storage-mode must be objects or packs"); - } + const hiddenLockfile = parseBoolean(input("hidden-lockfile", "false"), "hidden-lockfile"); + const hiddenLockfileKeyFiles = keyFileList(input("hidden-lockfile-key-files", "")); + const failOnHiddenLockfileChange = parseBoolean( + input("fail-on-hidden-lockfile-change", "false"), + "fail-on-hidden-lockfile-change", + ); const packSizeMB = positiveInteger("pack-size-mb", 8, 32); const packFlushSeconds = positiveInteger("pack-flush-seconds", 30, 3600); + const packRenewSeconds = positiveInteger("pack-renew-seconds", 15, 3600); + const packCompression = parseBoolean(input("pack-compression", "true"), "pack-compression"); + const packCompressionLevel = positiveInteger("pack-compression-level", 3, 19); const maxManifests = positiveInteger("max-manifests", 2048, 10_000); const githubToken = input("github-token", ""); - if (storageMode === "packs" && !githubToken) { - throw new Error("storage-mode=packs requires github-token with actions: read"); + if (!githubToken) { + throw new Error("github-token with actions: read is required to discover cache manifests"); } if (githubToken) mask(githubToken); - const portText = input("port", "0"); - const port = Number.parseInt(portText, 10); - if (!Number.isSafeInteger(port) || port < 0 || port > 65535) { - throw new Error("port must be an integer between 0 and 65535"); + const port = portNumber("port"); + const grpcPort = portNumber("grpc-port"); + if (port !== 0 && port === grpcPort) { + throw new Error("port and grpc-port must differ"); + } + // Artifact names must be unique within a job, so two instances of this action + // cannot both publish under the same one. + const usageArtifact = artifactName("usage-artifact"); + const logArtifact = artifactName("log-artifact"); + if (usageArtifact && usageArtifact === logArtifact) { + throw new Error("usage-artifact and log-artifact must differ"); } + // Validated by the server, which is what decides whether a credential is sent. + const assetHeaderRoutes = input("asset-header-routes", "").trim(); const tempDir = safeTemporaryDirectory( fs.mkdtempSync(path.join(path.resolve(process.env.RUNNER_TEMP), "bazel-gha-cache-v2-")), ); + saveState("temp_dir", tempDir); const readyFile = path.join(tempDir, "ready.json"); const statsFile = path.join(tempDir, "stats.json"); const logFile = path.join(tempDir, "server.log"); @@ -89,19 +184,39 @@ async function main() { const shutdownToken = crypto.randomBytes(32).toString("hex"); mask(shutdownToken); + const binary = await resolveBinary({ + program: "cache-server", + actionRoot: path.resolve(__dirname, ".."), + architecture, + platform: process.platform, + // Installing under a fixed name keeps every part of the spawned path a + // constant, so no release name can influence which program runs. + installPath: path.join(tempDir, process.platform === "win32" ? "cache-server.exe" : "cache-server"), + repository: process.env.GITHUB_ACTION_REPOSITORY, + ref: process.env.GITHUB_ACTION_REF, + token: githubToken || process.env.GITHUB_TOKEN || "", + toolCacheRoot: path.resolve(process.env.RUNNER_TOOL_CACHE || process.env.RUNNER_TEMP || os.tmpdir()), + log: (message) => process.stdout.write(`${message}${os.EOL}`), + }); + const args = [ "--port", String(port), + "--grpc-port", + String(grpcPort), "--cache-dir", spoolDir, "--key-prefix", input("key-prefix", "bazel-http-v1"), - "--storage-mode", - storageMode, "--pack-size", String(packSizeMB * 1024 * 1024), "--pack-flush-interval", `${packFlushSeconds}s`, + "--pack-renew-interval", + `${packRenewSeconds}s`, + booleanFlag("pack-compression", packCompression), + "--pack-compression-level", + String(packCompressionLevel), "--max-manifests", String(maxManifests), booleanFlag("write-enabled", writeEnabled), @@ -118,10 +233,41 @@ async function main() { readyFile, "--stats-file", statsFile, + "--usage-artifact", + usageArtifact, + "--asset-header-routes", + assetHeaderRoutes, ]; + // Saved before startup so that the post step can publish the log of a server + // that never became ready. + saveState("binary", binary); + saveState("log_file", logFile); + saveState("log_artifact", logArtifact); + setOutput("hidden-lockfile-cache-hit", "false"); + if (hiddenLockfile) { + const restored = restoreHiddenLockfile({ + binary, + workspace: process.env.GITHUB_WORKSPACE || process.cwd(), + keyFiles: hiddenLockfileKeyFiles, + timeoutSeconds: backendTimeoutSeconds, + }); + saveState("hidden_lockfile", restored.lockfile); + saveState("hidden_lockfile_primary", restored.primary_key); + saveState("hidden_lockfile_matched", restored.matched_key || ""); + saveState("hidden_lockfile_write", String(writeEnabled)); + saveState("hidden_lockfile_timeout", String(backendTimeoutSeconds)); + saveState("hidden_lockfile_fail_on_change", String(failOnHiddenLockfileChange)); + setOutput("hidden-lockfile-cache-hit", String(restored.cache_hit)); + process.stdout.write( + restored.matched_key + ? `Restored hidden Bazel lockfile from ${restored.matched_key}${os.EOL}` + : `No hidden Bazel lockfile restored${os.EOL}`, + ); + } const logDescriptor = fs.openSync(logFile, "a", 0o600); const child = spawn(binary, args, { detached: true, + windowsHide: true, env: { ...process.env, BAZEL_GHA_CACHE_SHUTDOWN_TOKEN: shutdownToken, @@ -130,9 +276,17 @@ async function main() { stdio: ["ignore", logDescriptor, logDescriptor], }); fs.closeSync(logDescriptor); + await new Promise((resolve, reject) => { + child.once("spawn", resolve); + child.once("error", reject); + }); child.unref(); + saveState("pid", String(child.pid)); + saveState("shutdown_token", shutdownToken); + saveState("stats_file", statsFile); + saveState("shutdown_wait_seconds", String(Math.max(60, backendTimeoutSeconds + 30))); - const readyDeadline = Date.now() + startupTimeoutMilliseconds(storageMode, backendTimeoutSeconds); + const readyDeadline = Date.now() + startupTimeoutMilliseconds(backendTimeoutSeconds); let ready; while (Date.now() < readyDeadline) { if (fs.existsSync(readyFile)) { @@ -143,7 +297,9 @@ async function main() { await sleep(100); } if (!ready) { - const log = fs.existsSync(logFile) ? fs.readFileSync(logFile, "utf8").slice(-8000) : ""; + const log = fs.existsSync(logFile) + ? logExcerpt(fs.readFileSync(logFile, "utf8"), { headChars: 2000, crashChars: 2000, tailChars: 4000 }) + : ""; throw new Error(`cache server did not become ready\n${log}`); } const health = await request(`${ready.url}/ready`, { method: "GET", timeout: 2000 }); @@ -152,22 +308,21 @@ async function main() { } saveState("url", ready.url); - saveState("pid", String(ready.pid)); - saveState("shutdown_token", shutdownToken); - saveState("stats_file", statsFile); - saveState("log_file", logFile); - saveState("temp_dir", tempDir); - saveState("shutdown_wait_seconds", String(Math.max(60, backendTimeoutSeconds + 30))); setOutput("url", ready.url); + setOutput("grpc-url", ready.grpc_url); setOutput("stats-url", ready.stats_url); setOutput("writable", String(writeEnabled)); setOutput( "bazel-args", `--remote_cache=${ready.url} --remote_upload_local_results=${writeEnabled}`, ); + setOutput( + "grpc-bazel-args", + `--remote_cache=${ready.grpc_url} --remote_upload_local_results=${writeEnabled}`, + ); setOutput("initial-stats", '{"requests":0,"hits":0,"misses":0,"uploads":0}'); process.stdout.write( - `Bazel cache adapter ready at ${ready.url} (write=${writeEnabled}, mode=${storageMode}, fail_open=${failOpen}, pid=${ready.pid})${os.EOL}`, + `Bazel cache adapter ready at ${ready.url} and ${ready.grpc_url} (write=${writeEnabled}, fail_open=${failOpen}, pid=${ready.pid})${os.EOL}`, ); } @@ -178,4 +333,10 @@ if (require.main === module) { }); } -module.exports = { startupTimeoutMilliseconds }; +module.exports = { + artifactName, + keyFileList, + restoreHiddenLockfile, + serverArchitecture, + startupTimeoutMilliseconds, +}; diff --git a/action/main.test.js b/action/main.test.js index a849eae..3158eb8 100644 --- a/action/main.test.js +++ b/action/main.test.js @@ -3,12 +3,115 @@ const test = require("node:test"); const assert = require("node:assert/strict"); -const { startupTimeoutMilliseconds } = require("./main"); +const { + artifactName, + keyFileList, + restoreHiddenLockfile, + serverArchitecture, + startupTimeoutMilliseconds, +} = require("./main"); -test("packed startup waits for its configured manifest-discovery deadline", () => { - assert.equal(startupTimeoutMilliseconds("packs", 300), 300_000); +test("the server supports Linux and Windows amd64/arm64 and Apple Silicon macOS", () => { + assert.equal(serverArchitecture("linux", "x64"), "amd64"); + assert.equal(serverArchitecture("linux", "arm64"), "arm64"); + assert.equal(serverArchitecture("darwin", "arm64"), "arm64"); + assert.equal(serverArchitecture("win32", "x64"), "amd64"); + assert.equal(serverArchitecture("win32", "arm64"), "arm64"); }); -test("object startup retains the short local-server readiness deadline", () => { - assert.equal(startupTimeoutMilliseconds("objects", 300), 15_000); +test("Intel macOS and unsupported runner platforms or architectures are rejected", () => { + assert.throws(() => serverArchitecture("darwin", "x64"), /macOS requires Apple Silicon/); + assert.throws(() => serverArchitecture("darwin", "ia32"), /macOS requires Apple Silicon/); + assert.throws(() => serverArchitecture("linux", "riscv64"), /unsupported Linux architecture/); + assert.throws(() => serverArchitecture("win32", "ia32"), /unsupported Windows architecture/); + for (const platform of ["freebsd", undefined]) { + assert.throws(() => serverArchitecture(platform, "arm64"), /supports Linux, Apple Silicon macOS, and Windows/); + } +}); + +test("startup waits for the configured manifest-discovery deadline", () => { + assert.equal(startupTimeoutMilliseconds(300), 300_000); +}); + +function withInput(name, value, run) { + const key = `INPUT_${name.toUpperCase()}`; + const previous = process.env[key]; + process.env[key] = value; + try { + return run(); + } finally { + if (previous === undefined) delete process.env[key]; + else process.env[key] = previous; + } +} + +test("artifact names are trimmed and may be empty to disable publishing", () => { + assert.equal(withInput("log-artifact", " bazel-cache-server-log ", () => artifactName("log-artifact")), "bazel-cache-server-log"); + assert.equal(withInput("log-artifact", "", () => artifactName("log-artifact")), ""); +}); + +test("artifact names outside the safe character set are rejected", () => { + assert.throws( + () => withInput("log-artifact", "../server log", () => artifactName("log-artifact")), + /log-artifact must match/, + ); +}); + +test("hidden-lockfile key files are parsed as non-empty workspace-relative lines", () => { + assert.deepEqual( + keyFileList(" pnpm-lock.yaml\r\n\r\nfrontend/package-lock.json \n"), + ["pnpm-lock.yaml", "frontend/package-lock.json"], + ); +}); + +test("the hidden lockfile restore uses the cache-server subcommand and returns metadata", () => { + let invocation; + const restored = restoreHiddenLockfile({ + binary: "/tmp/cache-server", + workspace: "/repo", + keyFiles: ["pnpm-lock.yaml", "frontend/package-lock.json"], + timeoutSeconds: 45, + spawn: (command, args, options) => { + invocation = { command, args, options }; + return { + status: 0, + stdout: JSON.stringify({ + lockfile: "/output/MODULE.bazel.lock", + primary_key: "primary", + matched_key: "fallback", + cache_hit: false, + warnings: ["listing was unavailable"], + }), + stderr: "", + }; + }, + warn: () => {}, + }); + assert.equal(restored.matched_key, "fallback"); + assert.equal(invocation.command, "/tmp/cache-server"); + assert.deepEqual(invocation.args.slice(0, 8), [ + "hidden-lockfile", + "restore", + "--workspace", + "/repo", + "--timeout", + "45s", + "--key-file", + "pnpm-lock.yaml", + ]); + assert.deepEqual(invocation.args.slice(-2), ["--key-file", "frontend/package-lock.json"]); + assert.ok(invocation.options.timeout > 45_000); +}); + +test("a hidden lockfile restore command failure is surfaced", () => { + assert.throws( + () => restoreHiddenLockfile({ + binary: "/tmp/cache-server", + workspace: "/repo", + keyFiles: [], + timeoutSeconds: 45, + spawn: () => ({ status: 1, stdout: "", stderr: "MODULE.bazel is missing" }), + }), + /MODULE\.bazel is missing/, + ); }); diff --git a/action/post.js b/action/post.js index 9efabf8..1649359 100644 --- a/action/post.js +++ b/action/post.js @@ -1,7 +1,15 @@ "use strict"; const fs = require("node:fs"); -const { request, safeTemporaryDirectory, setOutput } = require("./lib"); +const { spawnSync } = require("node:child_process"); +const { + formatBytes, + formatCount, + logExcerpt, + request, + safeTemporaryDirectory, + setOutput, +} = require("./lib"); const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); @@ -9,9 +17,299 @@ function processExists(pid) { try { process.kill(pid, 0); return true; - } catch { + } catch (error) { + if (error.code === "ESRCH") return false; + if (error.code === "EPERM") return true; + throw error; + } +} + +async function waitForProcessExit(pid, timeoutMilliseconds) { + const deadline = Date.now() + timeoutMilliseconds; + while (processExists(pid)) { + if (Date.now() >= deadline) return false; + await sleep(100); + } + return true; +} + +// buildSummary is separated from the post step so the rendered tables can +// be tested without standing a server up. +function buildSummary(stats) { + const count = (name) => formatCount(stats[name] ?? 0); + const bytes = (name) => formatBytes(stats[name] ?? 0); + const declared = Number(stats.pack_bytes_declared ?? 0); + const packed = ["packs_discovered", "pack_downloads", "pack_uploads"].some( + (name) => Number(stats[name] ?? 0) > 0, + ); + // Collapsing the detail hides an error count behind a click, so the total + // is surfaced here: a non-zero value is the cue to expand. + const failures = [ + "backend_load_errors", + "backend_save_errors", + "manifest_discovery_errors", + "manifest_load_errors", + "asset_fetch_errors", + ].reduce((total, name) => total + Number(stats[name] ?? 0), 0); + + const headline = [ + ["Hits", count("hits")], + ["Misses", count("misses")], + ["Published uploads", count("uploads")], + ...(packed + ? [ + ["CARv2 pack downloads", count("pack_downloads")], + ["Pack bytes transferred", bytes("pack_bytes_restored")], + // Used over declared, since a transferred total is compressed and + // so is not comparable with either. + [ + "Pack yield", + declared > 0 + ? `${((100 * Number(stats.pack_bytes_used ?? 0)) / declared).toFixed(1)}%` + : "n/a", + ], + ] + : []), + ["Served", bytes("bytes_served")], + ["Received", bytes("bytes_received")], + ["Errors", formatCount(failures)], + ]; + + // Everything the JSON carries that is not in the headline, so expanding + // always answers the question rather than sending you to the raw output. + const detail = [ + ["Requests", count("requests")], + ["Operations", count("operations")], + ["Missing action results", count("misses_ac")], + ["Missing CAS objects", count("misses_cas")], + ["Failed presence checks", count("misses_presence")], + ["Unusable action results", count("misses_rejected")], + ["Misses from degraded backend", count("misses_degraded")], + ["Rejected requests", count("rejected_requests")], + ["Deduplicated uploads", count("deduplicated_uploads")], + ["Read-only discarded uploads", count("discarded_uploads")], + ["Upload throttle waits", count("throttle_waits")], + ["CARv2 pack uploads", count("pack_uploads")], + ["Manifest uploads", count("manifest_uploads")], + ["Pack retention renewals", count("pack_renewals")], + ["Unavailable packs skipped", count("pack_loads_skipped")], + ["Compressed blocks", count("compressed_blocks")], + ["Saved by compression", bytes("compression_saved_bytes")], + ["Packs discovered", count("packs_discovered")], + ["Manifests discovered", count("manifests_discovered")], + ["Manifests skipped", count("manifests_skipped")], + ["Orphaned manifests", count("manifests_orphaned")], + ["Manifest discovery errors", count("manifest_discovery_errors")], + ["Manifest load errors", count("manifest_load_errors")], + ["Action keys with several results", count("action_digest_conflicts")], + ["Validated action results", count("validated_action_results")], + ["Incomplete action results", count("incomplete_action_results")], + ["Invalid action results", count("invalid_action_results")], + ["Skipped action-result uploads", count("skipped_action_result_uploads")], + ["Asset requests", count("asset_requests")], + ["Asset hits", count("asset_hits")], + ["Asset downloads", count("asset_downloads")], + ["Asset requests rejected", count("asset_rejected")], + ["Asset fetch errors", count("asset_fetch_errors")], + ["Backend requests", count("backend_requests")], + ["Backend downloads", count("backend_downloads")], + ["Backend existence checks", count("backend_existence_checks")], + ["Backend load errors", count("backend_load_errors")], + ["Backend save errors", count("backend_save_errors")], + ["Pack content restored", bytes("pack_bytes_declared")], + ["Pack content used", bytes("pack_bytes_used")], + ...(packed ? [] : [["Pack bytes transferred", bytes("pack_bytes_restored")]]), + ]; + + const table = (rows) => [ + "| Metric | Value |", + "|---|---:|", + ...rows.map(([label, value]) => `| ${label} | ${value} |`), + ]; + const summary = [ + "### Bazel GitHub Actions cache v2", + "", + ...table(headline), + "", + "
", + "All statistics", + // A table needs a blank line after the summary tag to render at all. + "", + ...table(detail), + "", + "
", + "", + ].join("\n"); + return summary; +} + +const logEntryName = "cache-server.log"; +const logUploadTimeoutSeconds = 120; + +// publishLog keeps the whole server log as a job artifact, since the excerpt +// printed to the job output drops the middle of a long one. The server binary +// does the upload because a crashed server cannot publish its own log. +function publishLog({ + binary, + logFile, + name, + spawn = spawnSync, + write = (text) => process.stdout.write(text), + warn = (text) => process.stderr.write(text), +}) { + if (!name) { + return false; + } + if (!binary || !fs.existsSync(binary)) { + warn("::warning::cannot publish the cache server log: the server binary is gone\n"); return false; } + const result = spawn( + binary, + [ + "upload-artifact", + "--name", + name, + "--file", + logFile, + "--entry-name", + logEntryName, + "--timeout", + `${logUploadTimeoutSeconds}s`, + ], + { encoding: "utf8", timeout: (logUploadTimeoutSeconds + 30) * 1000, stdio: ["ignore", "pipe", "pipe"] }, + ); + if (result.error || result.status !== 0) { + const reason = result.error?.message || String(result.stderr || "").trim() || `exit status ${result.status}`; + warn(`::warning::cannot publish the cache server log: ${reason.replaceAll("\n", " ")}\n`); + return false; + } + write(String(result.stdout || "")); + return true; +} + +function publishHiddenLockfile({ + binary, + workspace, + lockfile, + primary, + matched, + publish = matched !== primary, + publishIfChanged = true, + timeoutSeconds, + spawn = spawnSync, + write = (text) => process.stdout.write(text), + warn = (text) => process.stderr.write(text), +}) { + if (!binary || !lockfile || !primary) { + return null; + } + const result = spawn( + binary, + [ + "hidden-lockfile", + "save", + "--workspace", + workspace, + "--lockfile", + lockfile, + "--key", + primary, + "--timeout", + `${timeoutSeconds}s`, + `--publish=${publish}`, + `--publish-if-changed=${publishIfChanged}`, + ], + { encoding: "utf8", timeout: (timeoutSeconds + 30) * 1000, stdio: ["ignore", "pipe", "pipe"] }, + ); + if (result.error || result.status !== 0) { + const reason = result.error?.message || String(result.stderr || "").trim() || `exit status ${result.status}`; + warn(`::warning::cannot save the hidden Bazel lockfile: ${reason.replaceAll("\n", " ")}\n`); + return null; + } + if (result.stderr) { + write(String(result.stderr)); + } + let saved; + try { + saved = JSON.parse(result.stdout); + } catch (error) { + warn(`::warning::cannot parse hidden Bazel lockfile save result: ${error.message}\n`); + return null; + } + if ( + typeof saved.changed !== "boolean" || + typeof saved.previously_existed !== "boolean" || + typeof saved.saved !== "boolean" || + typeof saved.key !== "string" + ) { + warn("::warning::hidden Bazel lockfile save returned invalid metadata\n"); + return null; + } + const message = saved.changed + ? saved.previously_existed + ? `The hidden Bazel lockfile changed during the post refresh${saved.saved ? " and was saved" : "; publication was skipped"}.\n` + : `The hidden Bazel lockfile was created during the post refresh${saved.saved ? " and was saved" : "; publication was skipped"}.\n` + : `The hidden Bazel lockfile was unchanged during the post refresh${saved.saved ? ` and was saved as ${saved.key}` : "; exact-hit publication was skipped"}.\n`; + write(message); + return saved; +} + +function buildHiddenLockfileSummary(status) { + if (!status?.enabled) return ""; + let result; + let detail; + if (status.saved) { + if (!status.saved.changed) { + result = "Unchanged"; + detail = "The configured primary-key inputs reproduced the restored lockfile."; + } else if (!status.saved.previously_existed) { + result = "Created during refresh"; + detail = "No hidden lockfile was restored, so this does not establish whether the key-file list is complete."; + } else { + result = "Changed during refresh"; + detail = "The refreshed output differed from the restored lockfile. Check that `hidden-lockfile-key-files` includes every significant undeclared input."; + if (status.strict) { + result += " (failed)"; + detail += " The action is configured to fail on this condition, and the changed lockfile was not published."; + } + } + } else { + result = status.reason; + detail = status.detail; + } + return [ + "### Hidden Bazel lockfile", + "", + "| Result | Details |", + "|---|---|", + `| ${result} | ${detail} |`, + "", + ].join("\n"); +} + +function hiddenLockfileChangeViolation({ failOnChange, matched, saved }) { + return Boolean( + failOnChange && + matched && + saved?.changed && + saved.previously_existed, + ); +} + +function reportLog({ logFile, name, binary, print }) { + if (!logFile || !fs.existsSync(logFile)) { + return; + } + if (print) { + const log = fs.readFileSync(logFile, "utf8"); + const where = name ? `; the full log is published as artifact "${name}"` : ""; + process.stdout.write(`Cache server log (${formatBytes(Buffer.byteLength(log))}${where}):\n${logExcerpt(log)}`); + if (log && !log.endsWith("\n")) { + process.stdout.write("\n"); + } + } + publishLog({ binary, logFile, name }); } async function post() { @@ -20,37 +318,103 @@ async function post() { const pid = Number.parseInt(process.env.STATE_pid || "", 10); const statsFile = process.env.STATE_stats_file; const logFile = process.env.STATE_log_file; + const logArtifact = process.env.STATE_log_artifact || ""; + const binary = process.env.STATE_binary; const tempDir = process.env.STATE_temp_dir; const shutdownWaitSeconds = Number.parseInt(process.env.STATE_shutdown_wait_seconds || "330", 10); - if (!url || !token || !Number.isSafeInteger(pid)) { - process.stdout.write("Cache server state is absent; no cleanup is needed.\n"); - return; - } - - try { - const response = await request(`${url}/shutdown`, { - method: "POST", - headers: { "X-Shutdown-Token": token }, - timeout: 3000, + const hiddenLockfileEnabled = Boolean(process.env.STATE_hidden_lockfile); + const hiddenLockfileWrite = process.env.STATE_hidden_lockfile_write === "true"; + const hiddenLockfilePrimary = process.env.STATE_hidden_lockfile_primary; + const hiddenLockfileMatched = process.env.STATE_hidden_lockfile_matched || ""; + const hiddenLockfileFailOnChange = + process.env.STATE_hidden_lockfile_fail_on_change === "true"; + let hiddenLockfileViolation = false; + let hiddenLockfileStatus = { + enabled: hiddenLockfileEnabled, + reason: "Not refreshed", + detail: "Hidden-lockfile persistence is read-only for this job.", + }; + setOutput("hidden-lockfile-changed", "unknown"); + if (hiddenLockfileWrite) { + const saved = publishHiddenLockfile({ + binary, + workspace: process.env.GITHUB_WORKSPACE || process.cwd(), + lockfile: process.env.STATE_hidden_lockfile, + primary: hiddenLockfilePrimary, + matched: hiddenLockfileMatched, + publish: hiddenLockfileMatched !== hiddenLockfilePrimary, + publishIfChanged: !(hiddenLockfileFailOnChange && hiddenLockfileMatched), + timeoutSeconds: Math.max(1, Number.parseInt(process.env.STATE_hidden_lockfile_timeout || "", 10) || 300), }); - if (response.status !== 202) { - process.stderr.write(`::warning::cache shutdown returned HTTP ${response.status}\n`); + if (saved) { + hiddenLockfileStatus = { enabled: hiddenLockfileEnabled, saved }; + setOutput("hidden-lockfile-changed", String(saved.changed)); + hiddenLockfileViolation = hiddenLockfileChangeViolation({ + failOnChange: hiddenLockfileFailOnChange, + matched: hiddenLockfileMatched, + saved, + }); + if (hiddenLockfileViolation) { + hiddenLockfileStatus.strict = true; + } + } else { + hiddenLockfileStatus = { + enabled: hiddenLockfileEnabled, + reason: "Refresh or save failed", + detail: "See the post-step warning; the job is not failed.", + }; } - } catch (error) { - process.stderr.write(`::warning::cache shutdown request failed: ${error.message}\n`); + } + const hasProcess = Number.isSafeInteger(pid) && pid > 0; + const canShutdown = Boolean(hasProcess && url && token); + if (!hasProcess) { + // The main step already printed an excerpt when the server failed to start. + reportLog({ logFile, name: logArtifact, binary, print: false }); + process.stdout.write("Cache server process state is absent; no shutdown is needed.\n"); } - const shutdownAttempts = Number.isSafeInteger(shutdownWaitSeconds) && shutdownWaitSeconds > 0 - ? shutdownWaitSeconds * 10 - : 3300; - for (let attempt = 0; attempt < shutdownAttempts && processExists(pid); attempt += 1) { - await sleep(100); + if (canShutdown) { + try { + const response = await request(`${url}/shutdown`, { + method: "POST", + headers: { "X-Shutdown-Token": token }, + timeout: 3000, + }); + if (response.status !== 202) { + process.stderr.write(`::warning::cache shutdown returned HTTP ${response.status}\n`); + } + } catch (error) { + process.stderr.write(`::warning::cache shutdown request failed: ${error.message}\n`); + } } - if (processExists(pid)) { - process.stderr.write("::warning::cache server did not stop gracefully; sending SIGTERM\n"); + + const shutdownMilliseconds = Number.isSafeInteger(shutdownWaitSeconds) && shutdownWaitSeconds > 0 + ? shutdownWaitSeconds * 1000 + : 330_000; + let stopped = !hasProcess || await waitForProcessExit(pid, canShutdown ? shutdownMilliseconds : 0); + if (!stopped) { + // Node terminates the process unconditionally on Windows; it does not + // deliver a graceful SIGTERM. Wait for released file handles on every OS. + process.stderr.write("::warning::cache server did not stop gracefully; terminating it\n"); try { process.kill(pid, "SIGTERM"); - } catch {} + } catch (error) { + if (error.code !== "ESRCH") { + process.stderr.write(`::warning::cannot terminate cache server: ${error.message}\n`); + } + } + stopped = await waitForProcessExit(pid, 10_000); + if (!stopped) { + process.stderr.write("::warning::cache server ignored termination; killing it\n"); + try { + process.kill(pid, "SIGKILL"); + } catch (error) { + if (error.code !== "ESRCH") { + process.stderr.write(`::warning::cannot kill cache server: ${error.message}\n`); + } + } + stopped = await waitForProcessExit(pid, 10_000); + } } let stats = {}; @@ -63,48 +427,45 @@ async function post() { } } if (process.env.GITHUB_STEP_SUMMARY) { - const summary = [ - "### Bazel GitHub Actions cache v2", - "", - "| Metric | Value |", - "|---|---:|", - `| Hits | ${stats.hits ?? 0} |`, - `| Misses | ${stats.misses ?? 0} |`, - `| Published uploads | ${stats.uploads ?? 0} |`, - `| CARv2 pack uploads | ${stats.pack_uploads ?? 0} |`, - `| Manifest uploads | ${stats.manifest_uploads ?? 0} |`, - `| CARv2 pack downloads | ${stats.pack_downloads ?? 0} |`, - `| Manifests discovered | ${stats.manifests_discovered ?? 0} |`, - `| Action-digest conflicts | ${stats.action_digest_conflicts ?? 0} |`, - `| Read-only discarded uploads | ${stats.discarded_uploads ?? 0} |`, - `| Backend downloads | ${stats.backend_downloads ?? 0} |`, - `| Backend existence checks | ${stats.backend_existence_checks ?? 0} |`, - `| Backend load errors | ${stats.backend_load_errors ?? 0} |`, - `| Backend save errors | ${stats.backend_save_errors ?? 0} |`, - `| Validated action results | ${stats.validated_action_results ?? 0} |`, - `| Incomplete action results | ${stats.incomplete_action_results ?? 0} |`, - `| Invalid action results | ${stats.invalid_action_results ?? 0} |`, - `| Skipped action-result uploads | ${stats.skipped_action_result_uploads ?? 0} |`, - `| Bytes served | ${stats.bytes_served ?? 0} |`, - `| Bytes received | ${stats.bytes_received ?? 0} |`, - "", - ].join("\n"); - fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary); - } - - if (logFile && fs.existsSync(logFile)) { - const log = fs.readFileSync(logFile, "utf8"); - process.stdout.write(`Cache server log:\n${log.slice(-16000)}`); + fs.appendFileSync( + process.env.GITHUB_STEP_SUMMARY, + buildSummary(stats) + buildHiddenLockfileSummary(hiddenLockfileStatus), + ); + } + + if (hasProcess) { + reportLog({ logFile, name: logArtifact, binary, print: true }); + } + if (!stopped) { + process.stderr.write("::warning::cache server is still running; leaving its temporary directory intact\n"); } - if (tempDir) { + if (tempDir && stopped) { try { fs.rmSync(safeTemporaryDirectory(tempDir), { recursive: true, force: true }); } catch (error) { process.stderr.write(`::warning::cannot remove cache temporary directory: ${error.message}\n`); } } + if (hiddenLockfileViolation) { + process.stderr.write( + "::error::hidden Bazel lockfile changed after restore; the configured cache key is incomplete\n", + ); + process.exitCode = 1; + } +} + +if (require.main === module) { + post().catch((error) => { + process.stderr.write(`::warning::cache post-step failed: ${error.message}\n`); + }); } -post().catch((error) => { - process.stderr.write(`::warning::cache post-step failed: ${error.message}\n`); -}); +module.exports = { + buildHiddenLockfileSummary, + buildSummary, + hiddenLockfileChangeViolation, + processExists, + publishHiddenLockfile, + publishLog, + waitForProcessExit, +}; diff --git a/action/post.test.js b/action/post.test.js new file mode 100644 index 0000000..557265e --- /dev/null +++ b/action/post.test.js @@ -0,0 +1,382 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const test = require("node:test"); + +const os = require("node:os"); + +const { + buildHiddenLockfileSummary, + buildSummary, + hiddenLockfileChangeViolation, + publishHiddenLockfile, + publishLog, +} = require("./post"); + +const statsSource = fs.readFileSync( + path.join(__dirname, "..", "internal", "server", "stats.go"), + "utf8", +); + +function statsFields() { + return [...statsSource.matchAll(/json:"([a-z_]+)"/g)].map((match) => match[1]); +} + +// Every field gets a distinct value, so a row showing the wrong one is visible. +function everyField() { + const stats = {}; + statsFields().forEach((field, index) => { + stats[field] = (index + 1) * 1000; + }); + return stats; +} + +function headline(summary) { + return summary.slice(0, summary.indexOf("
")); +} + +function detail(summary) { + return summary.slice(summary.indexOf("
")); +} + +// A summary that leaves a counter out looks healthy when it is not, which +// matters most for the error counts. +test("every statistic the server reports reaches one of the two tables", () => { + const summary = buildSummary(everyField()); + const labelled = new Set( + [...summary.matchAll(/^\| ([^|]+?) \| /gm)].map((match) => match[1]), + ); + // Counted by label rather than field name, since the tables are what a + // person reads. + assert.ok(labelled.size >= statsFields().length, `only ${labelled.size} rows for ${statsFields().length} fields`); + for (const expected of ["Asset fetch errors", "Manifest load errors", "Backend save errors"]) { + assert.ok(labelled.has(expected), `${expected} is in neither table`); + } +}); + +test("the headline stays short and the rest is collapsed", () => { + const summary = buildSummary(everyField()); + const rows = (text) => [...text.matchAll(/^\| /gm)].length - 2; + assert.ok(rows(headline(summary)) <= 10, "the headline table has grown past a glance"); + assert.ok(rows(detail(summary)) > 20, "the detail table is missing rows"); + assert.match(summary, /
\nAll statistics<\/summary>\n\n\| Metric/); + assert.match(summary, /\n<\/details>/); +}); + +// The cue to open the detail is a non-zero error count, so it has to total the +// failures rather than report any single one. +test("the headline totals the error counters", () => { + const clean = buildSummary({ hits: 1 }); + assert.match(headline(clean), /\| Errors \| 0 \|/); + + const failing = buildSummary({ + backend_load_errors: 2, + backend_save_errors: 3, + manifest_discovery_errors: 4, + manifest_load_errors: 5, + asset_fetch_errors: 6, + }); + assert.match(headline(failing), /\| Errors \| 20 \|/); +}); + +// Objects mode never touches a pack, so those rows would all read zero. +test("pack rows are promoted only when packs are in use", () => { + const objects = buildSummary({ hits: 1 }); + assert.doesNotMatch(headline(objects), /Pack yield/); + + const packs = buildSummary({ + packs_discovered: 4, + pack_bytes_declared: 1000, + pack_bytes_used: 250, + }); + assert.match(headline(packs), /\| Pack yield \| 25\.0% \|/); +}); + +test("yield is unavailable rather than wrong when nothing was restored", () => { + const summary = buildSummary({ packs_discovered: 1, pack_bytes_used: 500 }); + assert.match(headline(summary), /\| Pack yield \| n\/a \|/); +}); + +// Byte counts and plain counts are easy to confuse, and the wrong one reads as +// a nonsense size. +test("byte statistics render as sizes and the rest as counts", () => { + const summary = buildSummary({ bytes_served: 2 * 1024 ** 3, hits: 1024 }); + assert.match(summary, /\| Served \| 2GiB \|/); + assert.match(summary, /\| Hits \| 1,024 \|/); +}); + +const uploadCommandSource = fs.readFileSync( + path.join(__dirname, "..", "cmd", "cache-server", "upload_artifact.go"), + "utf8", +); + +function existingBinary(t) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "post-test-")); + t.after(() => fs.rmSync(directory, { recursive: true, force: true })); + const binary = path.join(directory, "cache-server"); + fs.writeFileSync(binary, ""); + return binary; +} + +function capture() { + const output = { stdout: "", stderr: "" }; + return { + output, + write: (text) => { + output.stdout += text; + }, + warn: (text) => { + output.stderr += text; + }, + }; +} + +test("the server log is published through the server binary", (t) => { + const binary = existingBinary(t); + const calls = []; + const { output, write, warn } = capture(); + const published = publishLog({ + binary, + logFile: "/tmp/server.log", + name: "bazel-cache-server-log", + spawn: (command, args, options) => { + calls.push({ command, args, options }); + return { status: 0, stdout: 'published cache-server.log as artifact "bazel-cache-server-log"\n' }; + }, + write, + warn, + }); + assert.equal(published, true); + assert.equal(calls.length, 1); + assert.equal(calls[0].command, binary); + assert.deepEqual(calls[0].args.slice(0, 5), [ + "upload-artifact", + "--name", + "bazel-cache-server-log", + "--file", + "/tmp/server.log", + ]); + assert.ok(calls[0].options.timeout > 0, "the upload must not be able to hang the post step"); + assert.match(output.stdout, /published cache-server\.log/); + assert.equal(output.stderr, ""); +}); + +// The binary is invoked by name and flag, so a rename on either side would +// silently stop logs from being published. +test("the upload uses the subcommand and flags the server binary defines", (t) => { + let args; + publishLog({ + binary: existingBinary(t), + logFile: "/tmp/server.log", + name: "log", + spawn: (_command, given) => { + args = given; + return { status: 0, stdout: "" }; + }, + write: () => {}, + }); + const command = uploadCommandSource.match(/uploadArtifactCommandName = "([^"]+)"/); + assert.equal(args[0], command?.[1]); + const defined = new Set( + [...uploadCommandSource.matchAll(/flags\.[A-Za-z0-9]+\("([a-z-]+)"/g)].map((match) => match[1]), + ); + for (const flag of args.filter((arg) => arg.startsWith("--"))) { + assert.ok(defined.has(flag.slice(2)), `${flag} is not a flag of ${args[0]}`); + } +}); + +test("a failed log upload warns rather than failing the job", (t) => { + const { output, write, warn } = capture(); + const published = publishLog({ + binary: existingBinary(t), + logFile: "/tmp/server.log", + name: "log", + spawn: () => ({ status: 1, stdout: "", stderr: "upload-artifact: FinalizeArtifact returned HTTP 409\n" }), + write, + warn, + }); + assert.equal(published, false); + assert.match(output.stderr, /^::warning::cannot publish the cache server log: .*HTTP 409\n$/); +}); + +test("a log upload that cannot start warns", (t) => { + const { output, write, warn } = capture(); + const published = publishLog({ + binary: existingBinary(t), + logFile: "/tmp/server.log", + name: "log", + spawn: () => ({ error: new Error("spawnSync ETIMEDOUT"), status: null }), + write, + warn, + }); + assert.equal(published, false); + assert.match(output.stderr, /ETIMEDOUT/); +}); + +test("an empty log-artifact disables publishing", () => { + const published = publishLog({ + binary: "/nonexistent", + logFile: "/tmp/server.log", + name: "", + spawn: () => assert.fail("nothing should be spawned"), + }); + assert.equal(published, false); +}); + +test("a missing server binary warns instead of spawning", () => { + const { output, write, warn } = capture(); + const published = publishLog({ + binary: "/nonexistent/cache-server", + logFile: "/tmp/server.log", + name: "log", + spawn: () => assert.fail("nothing should be spawned"), + write, + warn, + }); + assert.equal(published, false); + assert.match(output.stderr, /server binary is gone/); +}); + +test("the hidden lockfile is refreshed and published through the server binary", () => { + let invocation; + const { output, write, warn } = capture(); + const published = publishHiddenLockfile({ + binary: "/tmp/cache-server", + workspace: "/repo", + lockfile: "/output/MODULE.bazel.lock", + primary: "primary", + matched: "fallback", + timeoutSeconds: 45, + spawn: (command, args, options) => { + invocation = { command, args, options }; + return { + status: 0, + stdout: JSON.stringify({ + changed: true, + previously_existed: true, + saved: true, + key: "primary", + }), + stderr: "bazel mod deps output\n", + }; + }, + write, + warn, + }); + assert.equal(published.changed, true); + assert.deepEqual(invocation.args.slice(0, 7), [ + "hidden-lockfile", + "save", + "--workspace", + "/repo", + "--lockfile", + "/output/MODULE.bazel.lock", + "--key", + ]); + assert.deepEqual(invocation.args.slice(7), [ + "primary", + "--timeout", + "45s", + "--publish=true", + "--publish-if-changed=true", + ]); + assert.match(output.stdout, /bazel mod deps output/); + assert.match(output.stdout, /changed during the post refresh/); + assert.equal(output.stderr, ""); +}); + +test("an exact hidden lockfile hit is audited without publication", () => { + let invocation; + const published = publishHiddenLockfile({ + binary: "/tmp/cache-server", + workspace: "/repo", + lockfile: "/output/MODULE.bazel.lock", + primary: "primary", + matched: "primary", + publishIfChanged: false, + timeoutSeconds: 45, + spawn: (command, args) => { + invocation = { command, args }; + return { + status: 0, + stdout: JSON.stringify({ + changed: true, + previously_existed: true, + saved: false, + key: "primary", + }), + stderr: "", + }; + }, + }); + assert.equal(published.changed, true); + assert.equal(published.saved, false); + assert.ok(invocation.args.includes("--publish=false")); + assert.ok(invocation.args.includes("--publish-if-changed=false")); +}); + +test("a hidden lockfile save failure warns rather than failing the post step", () => { + const { output, warn } = capture(); + publishHiddenLockfile({ + binary: "/tmp/cache-server", + workspace: "/repo", + lockfile: "/output/MODULE.bazel.lock", + primary: "primary", + matched: "", + timeoutSeconds: 45, + spawn: () => ({ status: 1, stdout: "", stderr: "refresh failed" }), + warn, + }); + assert.match(output.stderr, /cannot save the hidden Bazel lockfile: refresh failed/); +}); + +test("the hidden lockfile summary signals changed and unchanged refreshes", () => { + const changed = buildHiddenLockfileSummary({ + enabled: true, + saved: { changed: true, previously_existed: true, saved: false, key: "primary" }, + }); + assert.match(changed, /Changed during refresh/); + assert.match(changed, /hidden-lockfile-key-files/); + + const unchanged = buildHiddenLockfileSummary({ + enabled: true, + saved: { changed: false, previously_existed: true, saved: false, key: "primary" }, + }); + assert.match(unchanged, /Unchanged/); +}); + +test("strict mode fails only changes after an existing cache restore", () => { + const changed = { + changed: true, + previously_existed: true, + saved: false, + key: "primary", + }; + assert.equal(hiddenLockfileChangeViolation({ + failOnChange: true, + matched: "primary", + saved: changed, + }), true); + assert.equal(hiddenLockfileChangeViolation({ + failOnChange: false, + matched: "primary", + saved: changed, + }), false); + assert.equal(hiddenLockfileChangeViolation({ + failOnChange: true, + matched: "", + saved: { ...changed, previously_existed: false }, + }), false); +}); + +test("the hidden lockfile summary explains read-only refreshes", () => { + const summary = buildHiddenLockfileSummary({ + enabled: true, + reason: "Not refreshed", + detail: "Hidden-lockfile persistence is read-only for this job.", + }); + assert.match(summary, /read-only/); + assert.equal(buildHiddenLockfileSummary({ enabled: false }), ""); +}); diff --git a/action/release.js b/action/release.js new file mode 100644 index 0000000..fa8d7ab --- /dev/null +++ b/action/release.js @@ -0,0 +1,216 @@ +"use strict"; + +const fs = require("node:fs"); +const path = require("node:path"); +const { execFile } = require("node:child_process"); + +const PROGRAMS = new Set(["cache-server", "cache-optimiser"]); +const ARCHITECTURES = new Set(["amd64", "arm64"]); +const USER_AGENT = "bazel-github-actions-cache-v2"; +const DOWNLOAD_TIMEOUT_MS = 120_000; +const VERIFY_TIMEOUT_MS = 60_000; +const API_TIMEOUT_MS = 30_000; +const REPOSITORY_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; +const TAG_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; +const COMMIT_PATTERN = /^[0-9a-f]{40}$/; + +// Only names this action publishes are accepted, so a caller cannot steer the +// download or the install path towards something else, and an argument left +// undefined fails here rather than as a path error further down. +function assetName(program, architecture, platform = "linux") { + if (!PROGRAMS.has(program)) { + throw new Error(`unknown program ${program}`); + } + if (!ARCHITECTURES.has(architecture)) { + throw new Error(`unknown architecture ${architecture}`); + } + if ( + platform !== "linux" && + !(platform === "darwin" && program === "cache-server" && architecture === "arm64") && + !(platform === "win32" && program === "cache-server") + ) { + throw new Error(`unsupported platform for ${program}: ${platform}-${architecture}`); + } + const os = platform === "win32" ? "windows" : platform; + return `${program}-${os}-${architecture}${platform === "win32" ? ".exe" : ""}`; +} + +function releaseAssetUrl(repository, version, asset) { + return `https://github.com/${repository}/releases/download/${version}/${asset}`; +} + +async function download(url) { + const response = await fetch(url, { + headers: { "user-agent": USER_AGENT }, + signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS), + }); + if (!response.ok) { + throw new Error(`GET ${url} returned HTTP ${response.status}`); + } + // Release downloads redirect to object storage, and fetch follows that itself. + // The body is still unread here, so a redirect chain that ended up on plain + // HTTP is rejected before any of the binary travels over it. + if (!response.url.startsWith("https://")) { + throw new Error(`refusing to download ${url} over ${new URL(response.url).protocol}`); + } + return Buffer.from(await response.arrayBuffer()); +} + +async function githubJson(url, token) { + const headers = { "user-agent": USER_AGENT, accept: "application/vnd.github+json" }; + if (token) { + headers.authorization = `Bearer ${token}`; + } + const response = await fetch(url, { headers, signal: AbortSignal.timeout(API_TIMEOUT_MS) }); + if (!response.ok) { + throw new Error(`GET ${url} returned HTTP ${response.status}`); + } + return response.json(); +} + +// requireTag rejects anything that could not be a release tag. The value becomes +// both a URL segment and a path segment on the way to an executable, so it is +// checked here rather than at each use. +function requireTag(tag, problem) { + if (!TAG_PATTERN.test(String(tag ?? ""))) { + throw new Error(problem); + } + return String(tag); +} + +// releaseVersion works out which release publishes the binary for the running +// copy of the action. `uses: owner/repo@v1.2.3` names its release directly; a +// commit pin has to be mapped back to the tag that was released from it. +async function releaseVersion({ repository, ref, token }) { + if (COMMIT_PATTERN.test(String(ref ?? ""))) { + const refs = await githubJson( + `https://api.github.com/repos/${repository}/git/matching-refs/tags/`, + token, + ); + // Release tags are lightweight, so they point straight at the release commit. + const match = refs.find((entry) => entry.object?.type === "commit" && entry.object.sha === ref); + if (!match) { + throw new Error(`no release tag points at ${ref}; pin a released tag or commit`); + } + const tag = String(match.ref).replace(/^refs\/tags\//, ""); + return requireTag(tag, `${repository} has an unusable release tag at ${ref}`); + } + return requireTag( + ref, + "cannot tell which release to use; pin this action to a release tag or commit", + ); +} + +// verifyAttestation proves the binary came out of a workflow in the repository +// that published it. Only someone who can add a workflow there can produce a +// passing attestation, which is what makes a committed checksum unnecessary. +function verifyAttestation({ file, repository, token }) { + return new Promise((resolve, reject) => { + execFile( + "gh", + ["attestation", "verify", file, "--repo", repository], + { env: { ...process.env, GH_TOKEN: token }, timeout: VERIFY_TIMEOUT_MS }, + (error, _stdout, stderr) => { + if (!error) { + resolve(); + return; + } + if (error.code === "ENOENT") { + reject(new Error("the GitHub CLI is required to verify the server binary's provenance")); + return; + } + reject( + new Error( + `build provenance for ${path.basename(file)} could not be verified: ` + + `${String(stderr).trim() || error.message}`, + ), + ); + }, + ); + }); +} + +// install places a verified binary at a caller-chosen constant path. The value +// that reaches the process spawner is then built entirely from constants, so a +// release name cannot influence which program runs. +function install(source, destination) { + fs.rmSync(destination, { force: true }); + try { + fs.linkSync(source, destination); + } catch { + fs.copyFileSync(source, destination); + } + if (process.platform !== "win32") { + fs.chmodSync(destination, 0o700); + } + return destination; +} + +// resolveBinary returns one of this action's binaries for this runner. A +// locally built dist/ always wins so that CI and the smoke workflow exercise +// the code under review rather than a published artifact. +async function resolveBinary({ + program, + actionRoot, + architecture, + platform = "linux", + installPath, + repository, + ref, + token, + toolCacheRoot, + log, +}) { + // Every one of these becomes part of a filesystem path. Checking them here + // turns a caller that omits one into a clear error rather than a path fault + // several frames away. + for (const [name, value] of Object.entries({ actionRoot, installPath, toolCacheRoot })) { + if (typeof value !== "string" || value === "") { + throw new Error(`resolveBinary needs a ${name}`); + } + } + const asset = assetName(program, architecture, platform); + const localBinary = path.join(actionRoot, "dist", asset); + if (fs.existsSync(localBinary)) { + log(`using locally built dist/${asset}`); + return localBinary; + } + // The repository comes from whichever copy of the action is running, so a fork + // downloads its own releases rather than binaries built from other sources. + if (!REPOSITORY_PATTERN.test(String(repository ?? ""))) { + throw new Error( + "cannot tell which repository published this action; run scripts/build-dist.sh to use a local build", + ); + } + + const version = await releaseVersion({ repository, ref, token }); + const cached = path.join(toolCacheRoot, `bazel-gha-${program}`, version, architecture, asset); + if (fs.existsSync(cached)) { + log(`using cached ${asset} from ${version}`); + return install(cached, installPath); + } + + const url = releaseAssetUrl(repository, version, asset); + log(`downloading ${url}`); + const bytes = await download(url); + fs.mkdirSync(path.dirname(cached), { recursive: true }); + const spool = `${cached}.${process.pid}.part`; + fs.writeFileSync(spool, bytes, { mode: 0o700 }); + try { + await verifyAttestation({ file: spool, repository, token }); + } catch (error) { + fs.rmSync(spool, { force: true }); + throw error; + } + log(`verified the build provenance of ${asset} from ${version}`); + fs.renameSync(spool, cached); + return install(cached, installPath); +} + +module.exports = { + assetName, + download, + releaseAssetUrl, + releaseVersion, + resolveBinary, +}; diff --git a/action/release.test.js b/action/release.test.js new file mode 100644 index 0000000..7c8fccb --- /dev/null +++ b/action/release.test.js @@ -0,0 +1,393 @@ +"use strict"; + +const assert = require("node:assert"); +const fs = require("node:fs"); +const http = require("node:http"); +const os = require("node:os"); +const path = require("node:path"); +const { test } = require("node:test"); + +const { + assetName, + download, + releaseAssetUrl, + releaseVersion, + resolveBinary, +} = require("./release"); + +const REPOSITORY = "cre4ture/bazel-github-actions-cache-v2"; +const COMMIT = "b".repeat(40); +const realFetch = globalThis.fetch.bind(globalThis); + +function workspace(t) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "release-test-")); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + return root; +} + +function resolve(overrides) { + return resolveBinary({ + program: "cache-server", + architecture: "amd64", + actionRoot: "/action", + installPath: "/tmp/installed", + toolCacheRoot: "/tmp/tools", + repository: REPOSITORY, + ref: "v1.2.3", + token: "", + log: () => {}, + ...overrides, + }); +} + +function stubFetch(t, handler) { + globalThis.fetch = handler; + t.after(() => { + globalThis.fetch = realFetch; + }); +} + +function jsonResponse(body) { + return Promise.resolve({ ok: true, url: "https://api.github.com/", json: async () => body }); +} + +async function localServer(t, handler) { + const server = http.createServer(handler); + await new Promise((ready) => server.listen(0, "127.0.0.1", ready)); + t.after(() => server.close()); + return `127.0.0.1:${server.address().port}`; +} + +test("release assets are addressed by tag, not by latest", () => { + assert.strictEqual( + releaseAssetUrl(REPOSITORY, "v1.2.3", assetName("cache-server", "arm64")), + "https://github.com/cre4ture/bazel-github-actions-cache-v2/releases/download/v1.2.3/cache-server-linux-arm64", + ); + assert.strictEqual( + releaseAssetUrl(REPOSITORY, "v1.2.3", assetName("cache-optimiser", "amd64")), + "https://github.com/cre4ture/bazel-github-actions-cache-v2/releases/download/v1.2.3/cache-optimiser-linux-amd64", + ); + assert.strictEqual( + releaseAssetUrl(REPOSITORY, "pre-20261108T120614Z", assetName("cache-server", "arm64", "darwin")), + "https://github.com/cre4ture/bazel-github-actions-cache-v2/releases/download/pre-20261108T120614Z/cache-server-darwin-arm64", + ); +}); + +test("only the server is published for macOS, and only for Apple Silicon", () => { + assert.throws(() => assetName("cache-server", "amd64", "darwin"), /unsupported platform/); + for (const architecture of ["amd64", "arm64"]) { + assert.throws(() => assetName("cache-optimiser", architecture, "darwin"), /unsupported platform/); + for (const program of ["cache-server", "cache-optimiser"]) { + assert.equal(assetName(program, architecture, "linux"), `${program}-linux-${architecture}`); + } + } + for (const platform of ["freebsd", "../linux", ""]) { + assert.throws(() => assetName("cache-server", "arm64", platform), /unsupported platform/); + } +}); + +test("Windows publishes only amd64/arm64 server executables", () => { + for (const architecture of ["amd64", "arm64"]) { + const asset = assetName("cache-server", architecture, "win32"); + assert.equal(asset, `cache-server-windows-${architecture}.exe`); + assert.equal( + releaseAssetUrl(REPOSITORY, "pre-20261108T120614Z", asset), + `https://github.com/${REPOSITORY}/releases/download/pre-20261108T120614Z/${asset}`, + ); + assert.throws(() => assetName("cache-optimiser", architecture, "win32"), /unsupported platform/); + } + assert.throws(() => assetName("cache-server", "386", "win32"), /unknown architecture/); +}); + +// The program name reaches a download URL and an install path, so only names +// this action actually publishes may be used. An argument left undefined has to +// fail here rather than as a path error further down. +test("an unknown program or architecture is rejected", () => { + for (const program of ["", "sh", "../cache-server", undefined]) { + assert.throws(() => assetName(program, "amd64"), /unknown program/); + } + for (const architecture of ["", "x64", "../../etc", undefined]) { + assert.throws(() => assetName("cache-server", architecture), /unknown architecture/); + } +}); + +test("an option that would become part of a path is required", async () => { + const complete = { + program: "cache-server", + actionRoot: "/action", + architecture: "amd64", + installPath: "/tmp/installed", + repository: REPOSITORY, + ref: "v1.2.3", + token: "", + toolCacheRoot: "/tmp/tools", + log: () => {}, + }; + for (const name of ["actionRoot", "installPath", "toolCacheRoot"]) { + await assert.rejects( + resolveBinary({ ...complete, [name]: undefined }), + new RegExp(`resolveBinary needs a ${name}`), + ); + } + await assert.rejects( + resolveBinary({ ...complete, architecture: undefined }), + /unknown architecture/, + ); +}); + +// Both binaries are cached under the same root, so sharing a directory would +// let one be served in place of the other. +test("each program has its own tool-cache directory", async (t) => { + const root = workspace(t); + const toolCacheRoot = path.join(root, "tools"); + const optimiser = path.join( + toolCacheRoot, + "bazel-gha-cache-optimiser", + "v1.2.3", + "amd64", + assetName("cache-optimiser", "amd64"), + ); + fs.mkdirSync(path.dirname(optimiser), { recursive: true }); + fs.writeFileSync(optimiser, "cached optimiser"); + + const installPath = path.join(root, "installed"); + const resolved = await resolveBinary({ + program: "cache-optimiser", + actionRoot: path.join(root, "checkout"), + architecture: "amd64", + installPath, + repository: REPOSITORY, + ref: "v1.2.3", + token: "", + toolCacheRoot, + log: () => {}, + }); + assert.strictEqual(resolved, installPath); + assert.strictEqual(fs.readFileSync(installPath, "utf8"), "cached optimiser"); +}); + +test("a tag ref names its own release", async () => { + assert.strictEqual(await releaseVersion({ repository: REPOSITORY, ref: "v1.2.3" }), "v1.2.3"); +}); + +test("a commit pin resolves to the tag released from it", async (t) => { + stubFetch(t, (url) => { + assert.match(String(url), /git\/matching-refs\/tags\//); + return jsonResponse([ + { ref: "refs/tags/v1.0.0", object: { type: "commit", sha: "a".repeat(40) } }, + { ref: "refs/tags/v1.2.3", object: { type: "commit", sha: COMMIT } }, + ]); + }); + assert.strictEqual(await releaseVersion({ repository: REPOSITORY, ref: COMMIT }), "v1.2.3"); +}); + +test("a commit that was never released is reported as such", async (t) => { + stubFetch(t, () => jsonResponse([])); + await assert.rejects( + releaseVersion({ repository: REPOSITORY, ref: COMMIT }), + /no release tag points at/, + ); +}); + +// A tag name reaches both a download URL and the path of the binary that gets +// executed, so a hostile one must never be taken at face value. +test("a tag name that could escape its directory is rejected", async (t) => { + for (const ref of [ + "refs/tags/../../../../tmp/evil", + "refs/tags/v1.2.3/../../..", + "refs/tags/v1;rm -rf /", + "refs/tags/", + ]) { + stubFetch(t, () => jsonResponse([{ ref, object: { type: "commit", sha: COMMIT } }])); + await assert.rejects( + releaseVersion({ repository: REPOSITORY, ref: COMMIT }), + /unusable release tag/, + ); + } +}); + +test("a ref that names no release at all is rejected", async () => { + for (const ref of [undefined, "", "refs/heads/main", "feature branch"]) { + await assert.rejects( + releaseVersion({ repository: REPOSITORY, ref }), + /pin this action to a release tag or commit/, + ); + } +}); + +test("a locally built binary is preferred over any published release", async (t) => { + const root = workspace(t); + const actionRoot = path.join(root, "checkout"); + const local = path.join(actionRoot, "dist", assetName("cache-server", "amd64")); + fs.mkdirSync(path.dirname(local), { recursive: true }); + fs.writeFileSync(local, "locally built"); + + assert.strictEqual( + await resolve({ actionRoot, toolCacheRoot: path.join(root, "tools") }), + local, + ); +}); + +test("macOS resolves its local server binary rather than a Linux ARM64 binary", async (t) => { + const root = workspace(t); + const actionRoot = path.join(root, "checkout"); + const dist = path.join(actionRoot, "dist"); + fs.mkdirSync(dist, { recursive: true }); + fs.writeFileSync(path.join(dist, assetName("cache-server", "arm64", "linux")), "Linux server"); + const local = path.join(dist, assetName("cache-server", "arm64", "darwin")); + fs.writeFileSync(local, "macOS server"); + stubFetch(t, () => { + throw new Error("a local binary must not require a release download"); + }); + + assert.strictEqual( + await resolve({ actionRoot, platform: "darwin", architecture: "arm64", repository: undefined }), + local, + ); +}); + +for (const architecture of ["amd64", "arm64"]) { + test(`Windows resolves its local ${architecture} executable rather than a Linux binary`, async (t) => { + const root = workspace(t); + const actionRoot = path.join(root, "checkout with spaces"); + const dist = path.join(actionRoot, "dist"); + fs.mkdirSync(dist, { recursive: true }); + fs.writeFileSync(path.join(dist, assetName("cache-server", architecture)), "Linux server"); + const local = path.join(dist, assetName("cache-server", architecture, "win32")); + fs.writeFileSync(local, "Windows server"); + stubFetch(t, () => { + throw new Error("a local binary must not require a release download"); + }); + assert.equal( + await resolve({ actionRoot, platform: "win32", architecture, repository: undefined }), + local, + ); + }); +} + +test("Linux, macOS, and Windows ARM64 server binaries do not collide in the tool cache", async (t) => { + const root = workspace(t); + const toolCacheRoot = path.join(root, "tools"); + const cacheDir = path.join(toolCacheRoot, "bazel-gha-cache-server", "v1.2.3", "arm64"); + fs.mkdirSync(cacheDir, { recursive: true }); + for (const platform of ["linux", "darwin", "win32"]) { + fs.writeFileSync(path.join(cacheDir, assetName("cache-server", "arm64", platform)), platform); + } + stubFetch(t, () => { + throw new Error("a cached binary must not require a release download"); + }); + + for (const platform of ["linux", "darwin", "win32"]) { + const installPath = path.join(root, platform === "win32" ? "cache-server.exe" : "cache-server"); + const resolved = await resolve({ + actionRoot: path.join(root, "checkout"), + architecture: "arm64", + platform, + installPath, + toolCacheRoot, + }); + assert.strictEqual(resolved, installPath); + assert.strictEqual(fs.readFileSync(resolved, "utf8"), platform); + if (process.platform !== "win32") { + assert.strictEqual(fs.statSync(resolved).mode & 0o777, 0o700); + } + } +}); + +test("an action running from an unknown repository will not guess where to download", async (t) => { + const root = workspace(t); + await assert.rejects( + resolve({ + actionRoot: path.join(root, "checkout"), + repository: undefined, + toolCacheRoot: path.join(root, "tools"), + }), + /cannot tell which repository/, + ); +}); + +test("an already verified binary is installed at the fixed path that gets executed", async (t) => { + const root = workspace(t); + const toolCacheRoot = path.join(root, "tools"); + const version = "v1.2.3"; + const cached = path.join( + toolCacheRoot, + "bazel-gha-cache-server", + version, + "amd64", + assetName("cache-server", "amd64"), + ); + fs.mkdirSync(path.dirname(cached), { recursive: true }); + fs.writeFileSync(cached, "previously verified"); + const installPath = path.join(root, "cache-server"); + + const resolved = await resolve({ + actionRoot: path.join(root, "checkout"), + installPath, + toolCacheRoot, + }); + assert.strictEqual(resolved, installPath); + assert.strictEqual(fs.readFileSync(resolved, "utf8"), "previously verified"); + // The executed path must carry no trace of the release it came from. + assert.ok(!resolved.includes(version), `${resolved} still names the release`); +}); + +test("a download that lands on plain HTTP is refused before the body is read", async (t) => { + let served = false; + const address = await localServer(t, (_, response) => { + served = true; + response.writeHead(200).end("a binary that must never be trusted"); + }); + + await assert.rejects( + download(`http://${address}/${assetName("cache-server", "amd64")}`), + /refusing to download/, + ); + assert.ok(served, "the endpoint should have been reached and then rejected"); +}); + +for (const platform of ["linux", "darwin", "win32"]) { + test(`a ${platform} binary whose provenance cannot be verified is discarded`, async (t) => { + const root = workspace(t); + const toolCacheRoot = path.join(root, "tools"); + const actionRoot = path.join(root, "checkout"); + if (platform !== "linux") { + fs.mkdirSync(path.join(actionRoot, "dist"), { recursive: true }); + fs.writeFileSync(path.join(actionRoot, "dist", assetName("cache-server", "arm64")), "Linux server"); + } + const address = await localServer(t, (_, response) => { + response.writeHead(200).end("an unattested binary"); + }); + // Serve the asset locally while reporting the HTTPS origin the download + // requires, so that verification rather than transport is what fails. + stubFetch(t, async (url) => { + assert.strictEqual( + url, + releaseAssetUrl(REPOSITORY, "v1.2.3", assetName("cache-server", "arm64", platform)), + ); + const served = await realFetch(String(url).replace(/^https:\/\/github\.com/, `http://${address}`)); + return { ok: true, url: "https://github.com/", arrayBuffer: () => served.arrayBuffer() }; + }); + // Hide the GitHub CLI so verification fails locally instead of reaching out. + const realPath = process.env.PATH; + process.env.PATH = path.join(root, "empty"); + t.after(() => { + process.env.PATH = realPath; + }); + + await assert.rejects( + resolve({ + actionRoot, + architecture: "arm64", + platform, + installPath: path.join(root, "cache-server"), + toolCacheRoot, + }), + /provenance|GitHub CLI/, + ); + const cacheDir = path.join(toolCacheRoot, "bazel-gha-cache-server", "v1.2.3", "arm64"); + const leftovers = fs.existsSync(cacheDir) ? fs.readdirSync(cacheDir) : []; + assert.deepStrictEqual(leftovers, [], "an unverified download must not be left behind"); + assert.ok(!fs.existsSync(path.join(root, "cache-server")), "nothing must be installed"); + }); +} diff --git a/buf.gen.yaml b/buf.gen.yaml new file mode 100644 index 0000000..e0e3807 --- /dev/null +++ b/buf.gen.yaml @@ -0,0 +1,28 @@ +# Generated code is committed to the repository; run scripts/generate-proto.sh to refresh it. +# The googleapis commit below must match the one pinned in proto/buf.lock. +version: v2 +inputs: + - directory: proto + - module: buf.build/googleapis/googleapis:c17df5b2beca46928cc87d5656bd5343 + paths: + - google/bytestream/bytestream.proto +plugins: + # google.golang.org/protobuf >= 1.36 opaque API: struct fields are hidden behind + # accessors, which lets the runtime pick a more compact in-memory layout. + - local: protoc-gen-go + out: internal/proto/gen + opt: + - paths=source_relative + - default_api_level=API_OPAQUE + - Mbuild/bazel/semver/semver.proto=github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/semver;semver + - Mbuild/bazel/remote/execution/v2/remote_execution.proto=github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/execution/v2;remoteexecution + - Mbuild/bazel/remote/asset/v1/remote_asset.proto=github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/asset/v1;remoteasset + - Mgoogle/bytestream/bytestream.proto=github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/google/bytestream;bytestream + - local: protoc-gen-go-grpc + out: internal/proto/gen + opt: + - paths=source_relative + - Mbuild/bazel/semver/semver.proto=github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/semver;semver + - Mbuild/bazel/remote/execution/v2/remote_execution.proto=github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/execution/v2;remoteexecution + - Mbuild/bazel/remote/asset/v1/remote_asset.proto=github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/asset/v1;remoteasset + - Mgoogle/bytestream/bytestream.proto=github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/google/bytestream;bytestream diff --git a/cmd/cache-optimiser/main.go b/cmd/cache-optimiser/main.go new file mode 100644 index 0000000..9cb7130 --- /dev/null +++ b/cmd/cache-optimiser/main.go @@ -0,0 +1,149 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "log" + "os" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/cache" + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/optimiser" + cacheserver "github.com/cre4ture/bazel-github-actions-cache-v2/internal/server" +) + +var version = "dev" + +func main() { + if err := run(); err != nil { + log.Printf("fatal: %v", err) + os.Exit(1) + } +} + +func run() error { + var ( + cacheDir = flag.String("cache-dir", "", "local spool directory") + keyPrefix = flag.String("key-prefix", "bazel-http-v1", "GitHub cache key prefix") + usageArtifact = flag.String("usage-artifact", "bazel-cache-usage", "job artifact holding the usage records") + maxRecords = flag.Int("max-records", 25, "how many recent usage records, one per job, to plan from") + packSize = flag.Int64("pack-size", 8*1024*1024, "target size of a rebuilt pack, in object bytes") + minWasteFraction = flag.Float64("min-waste-fraction", 0.25, "how much of a pack must be bytes a restore does not want before rebuilding it") + minImprovement = flag.Float64("min-improvement", 0.25, "how much of a pack's overfetch a rebuild must remove, judged on runs the regrouping was not fitted to") + minRuns = flag.Int("min-runs", 3, "refuse to plan from fewer usage records than this") + maxBlobSize = flag.Int64("max-blob-size", 512*1024*1024, "maximum object size in bytes") + uploadsPerMinute = flag.Int("uploads-per-minute", 180, "maximum GitHub cache uploads per minute; must be below 200") + concurrency = flag.Int("concurrency", 4, "how many packs to rebuild at once") + maxNewBytes = flag.Int64("max-new-bytes", 2*1024*1024*1024, "stop a pass once it has published this many bytes; zero means no limit") + reap = flag.Bool("reap", false, "delete packs that no manifest names at all") + reapOlderThan = flag.Duration("reap-older-than", 24*time.Hour, "only reap packs older than this") + evictAfter = flag.Duration("evict-after", 7*24*time.Hour, "evict entries nothing has used for this long; only packs twice as old are reshaped") + downloadOverhead = flag.Int64("download-overhead", 8*1024*1024, "fixed cost of restoring one pack, in bytes it is worth") + scope = flag.String("ref", os.Getenv("GITHUB_REF"), "full Git reference whose caches this pass reads and replaces") + timeout = flag.Duration("backend-timeout", 5*time.Minute, "timeout per backend operation") + dryRun = flag.Bool("dry-run", false, "plan and report without publishing or deleting") + summaryFile = flag.String("summary-file", "", "write the result as JSON to this file") + showVersion = flag.Bool("version", false, "print version and exit") + ) + flag.Parse() + if *showVersion { + fmt.Println(version) + return nil + } + + logger := log.New(os.Stderr, "cache-optimiser: ", log.LstdFlags|log.LUTC) + if *evictAfter <= 0 { + return fmt.Errorf("--evict-after must be positive") + } + if *downloadOverhead < 0 { + return fmt.Errorf("--download-overhead must not be negative") + } + if *scope == "" { + return fmt.Errorf("--ref is required; it is what keeps this pass inside one cache scope") + } + dir, err := cacheserver.SafeCacheDir(*cacheDir) + if err != nil { + return fmt.Errorf("prepare spool directory: %w", err) + } + defer os.RemoveAll(dir) + + backend, err := cache.NewActionsBackend(*timeout) + if err != nil { + return err + } + // Scoped to one reference so that everything listed is something this pass + // can also restore and replace. + catalog, err := cache.NewScopedActionsCatalog(*timeout, logger, *scope) + if err != nil { + return err + } + records, err := optimiser.NewRecordSource(*usageArtifact, *timeout) + if err != nil { + return err + } + options := optimiser.RunOptions{ + Backend: backend, + Catalog: catalog, + Records: records, + CacheDir: dir, + KeyPrefix: *keyPrefix, + MaxRecords: *maxRecords, + MaxBlobSize: *maxBlobSize, + UploadsPerMinute: *uploadsPerMinute, + Concurrency: *concurrency, + MaxNewBytes: *maxNewBytes, + Reap: *reap, + ReapOlderThan: *reapOlderThan, + EvictAfter: *evictAfter, + Lister: catalog, + Timeout: *timeout, + DryRun: *dryRun, + Plan: optimiser.Options{ + TargetPackSize: *packSize, + MinWasteFraction: *minWasteFraction, + MinImprovement: *minImprovement, + DownloadOverhead: *downloadOverhead, + MinRuns: *minRuns, + }, + Log: logger.Printf, + } + // The pruner is the only thing here that needs actions: write, so a dry run + // never even constructs one. + if !*dryRun { + pruner, err := cache.NewActionsPruner(*timeout, *scope) + if err != nil { + return err + } + options.Pruner = pruner + } + + ctx, cancel := context.WithTimeout(context.Background(), 6*time.Hour) + defer cancel() + result, runErr := optimiser.Run(ctx, options) + if *summaryFile != "" { + if err := writeSummary(*summaryFile, result); err != nil { + logger.Printf("write summary: %v", err) + } + } + if runErr != nil { + return runErr + } + if result.Skipped != "" { + logger.Printf("read %d usage records; nothing to do: %s", result.Records, result.Skipped) + return nil + } + logger.Printf("read %d usage records; rebuilt %d packs (%s published), deleted %d, reaped %d of %d reapable", + result.Records, result.Rebuilt, optimiser.HumanBytes(result.PublishedBytes), + result.Deleted, result.Reaped, result.Reapable) + return nil +} + +func writeSummary(path string, result optimiser.Result) error { + data, err := json.Marshal(result) + if err != nil { + return err + } + return os.WriteFile(path, append(data, '\n'), 0o600) +} diff --git a/cmd/cache-server/hidden_lockfile.go b/cmd/cache-server/hidden_lockfile.go new file mode 100644 index 0000000..0dc7138 --- /dev/null +++ b/cmd/cache-server/hidden_lockfile.go @@ -0,0 +1,438 @@ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/cache" +) + +const hiddenLockfileCommandName = "hidden-lockfile" +const hiddenLockfileKeyRoot = "bazel-gha-cache-hidden-lockfile-v1" + +type hiddenLockfileRestoreResult struct { + Lockfile string `json:"lockfile"` + PrimaryKey string `json:"primary_key"` + MatchedKey string `json:"matched_key,omitempty"` + CacheHit bool `json:"cache_hit"` + Warnings []string `json:"warnings,omitempty"` +} + +type hiddenLockfileSaveResult struct { + Changed bool `json:"changed"` + PreviouslyExisted bool `json:"previously_existed"` + Saved bool `json:"saved"` + Key string `json:"key"` +} + +type hiddenLockfileBackend interface { + Restore(ctx context.Context, keys []string, dst io.Writer) (string, error) + Save(ctx context.Context, key string, src *os.File, size int64) error +} + +type repeatedFlag []string + +func (r *repeatedFlag) String() string { + return strings.Join(*r, "\n") +} + +func (r *repeatedFlag) Set(value string) error { + *r = append(*r, value) + return nil +} + +func hiddenLockfileCommand(args []string, stdout, stderr io.Writer) error { + if len(args) == 0 { + return fmt.Errorf("%s: restore or save is required", hiddenLockfileCommandName) + } + switch args[0] { + case "restore": + return hiddenLockfileRestoreCommand(args[1:], stdout) + case "save": + return hiddenLockfileSaveCommand(args[1:], stdout, stderr) + default: + return fmt.Errorf("%s: unknown operation %q", hiddenLockfileCommandName, args[0]) + } +} + +func hiddenLockfileRestoreCommand(args []string, stdout io.Writer) error { + flags := flag.NewFlagSet(hiddenLockfileCommandName+" restore", flag.ContinueOnError) + flags.SetOutput(io.Discard) + var ( + workspace = flags.String("workspace", "", "workspace containing the Bazel project") + timeout = flags.Duration("timeout", 5*time.Minute, "timeout for cache operations") + keyFiles repeatedFlag + ) + flags.Var(&keyFiles, "key-file", "additional workspace-relative key file; repeatable") + if err := flags.Parse(args); err != nil { + return fmt.Errorf("%s restore: %w", hiddenLockfileCommandName, err) + } + if flags.NArg() != 0 { + return fmt.Errorf("%s restore: unexpected arguments %q", hiddenLockfileCommandName, flags.Args()) + } + if *workspace == "" { + return fmt.Errorf("%s restore: --workspace is required", hiddenLockfileCommandName) + } + if *timeout <= 0 { + return fmt.Errorf("%s restore: --timeout must be positive", hiddenLockfileCommandName) + } + + backend, err := cache.NewActionsBackend(*timeout) + if err != nil { + return fmt.Errorf("%s restore: %w", hiddenLockfileCommandName, err) + } + platform, err := hiddenLockfilePlatform() + if err != nil { + return fmt.Errorf("%s restore: %w", hiddenLockfileCommandName, err) + } + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + result, err := restoreHiddenLockfile( + ctx, + backend, + *workspace, + []string(keyFiles), + platform, + bazelOutputBase, + ) + if err != nil { + return fmt.Errorf("%s restore: %w", hiddenLockfileCommandName, err) + } + return json.NewEncoder(stdout).Encode(result) +} + +func hiddenLockfileSaveCommand(args []string, stdout, stderr io.Writer) error { + flags := flag.NewFlagSet(hiddenLockfileCommandName+" save", flag.ContinueOnError) + flags.SetOutput(io.Discard) + var ( + workspace = flags.String("workspace", "", "workspace containing the Bazel project") + lockfile = flags.String("lockfile", "", "restored hidden lockfile path") + key = flags.String("key", "", "immutable cache key") + timeout = flags.Duration("timeout", 5*time.Minute, "timeout for the refresh and save") + publish = flags.Bool("publish", true, "publish the refreshed lockfile") + publishIfChanged = flags.Bool( + "publish-if-changed", + true, + "publish when the refreshed lockfile differs from an existing file", + ) + ) + if err := flags.Parse(args); err != nil { + return fmt.Errorf("%s save: %w", hiddenLockfileCommandName, err) + } + if flags.NArg() != 0 { + return fmt.Errorf("%s save: unexpected arguments %q", hiddenLockfileCommandName, flags.Args()) + } + if *workspace == "" || *lockfile == "" || *key == "" { + return fmt.Errorf("%s save: --workspace, --lockfile, and --key are required", hiddenLockfileCommandName) + } + if *timeout <= 0 { + return fmt.Errorf("%s save: --timeout must be positive", hiddenLockfileCommandName) + } + + backend, err := cache.NewActionsBackend(*timeout) + if err != nil { + return fmt.Errorf("%s save: %w", hiddenLockfileCommandName, err) + } + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + refresh := func(ctx context.Context, workspace string) error { + return refreshHiddenLockfile(ctx, workspace, stderr, stderr) + } + result, err := saveHiddenLockfile( + ctx, + backend, + *workspace, + *lockfile, + *key, + *publish, + *publishIfChanged, + refresh, + ) + if err != nil { + return fmt.Errorf("%s save: %w", hiddenLockfileCommandName, err) + } + return json.NewEncoder(stdout).Encode(result) +} + +func hiddenLockfilePlatform() (string, error) { + platform := os.Getenv("RUNNER_OS") + "-" + os.Getenv("RUNNER_ARCH") + if os.Getenv("RUNNER_OS") == "" || os.Getenv("RUNNER_ARCH") == "" { + return "", errors.New("RUNNER_OS and RUNNER_ARCH are required") + } + for _, char := range platform { + if (char >= 'A' && char <= 'Z') || + (char >= 'a' && char <= 'z') || + (char >= '0' && char <= '9') || + char == '.' || char == '_' || char == '-' { + continue + } + return "", fmt.Errorf("runner platform %q contains an unsafe character", platform) + } + return platform, nil +} + +func restoreHiddenLockfile( + ctx context.Context, + backend hiddenLockfileBackend, + workspace string, + keyFiles []string, + platform string, + outputBase func(context.Context, string) (string, error), +) (hiddenLockfileRestoreResult, error) { + workspace, err := filepath.Abs(workspace) + if err != nil { + return hiddenLockfileRestoreResult{}, fmt.Errorf("resolve workspace: %w", err) + } + module, err := readWorkspaceFile(workspace, "MODULE.bazel") + if err != nil { + return hiddenLockfileRestoreResult{}, err + } + trackedLock, err := readWorkspaceFile(workspace, "MODULE.bazel.lock") + if err != nil { + return hiddenLockfileRestoreResult{}, err + } + bazelVersion, err := readWorkspaceFile(workspace, ".bazelversion") + if err != nil { + return hiddenLockfileRestoreResult{}, err + } + extraContents := make([][]byte, 0, len(keyFiles)) + for _, keyFile := range keyFiles { + content, readErr := readWorkspaceFile(workspace, keyFile) + if readErr != nil { + return hiddenLockfileRestoreResult{}, readErr + } + extraContents = append(extraContents, content) + } + base, err := outputBase(ctx, workspace) + if err != nil { + return hiddenLockfileRestoreResult{}, err + } + base = strings.TrimSpace(base) + if !filepath.IsAbs(base) { + return hiddenLockfileRestoreResult{}, fmt.Errorf("bazel output base is not absolute: %q", base) + } + primary, restorePrefixes := deriveHiddenLockfileKeys(platform, module, trackedLock, bazelVersion, extraContents) + lockfile := filepath.Join(base, "MODULE.bazel.lock") + result := hiddenLockfileRestoreResult{ + Lockfile: lockfile, + PrimaryKey: primary, + } + + matchedKey, err := restoreHiddenLockfileKey( + ctx, + backend, + append([]string{primary}, restorePrefixes...), + lockfile, + ) + if err != nil { + result.Warnings = append(result.Warnings, fmt.Sprintf("failed to restore the hidden lockfile: %v", err)) + return result, nil + } + if matchedKey != "" { + result.MatchedKey = matchedKey + result.CacheHit = matchedKey == primary + } + return result, nil +} + +func deriveHiddenLockfileKeys(platform string, module, trackedLock, bazelVersion []byte, extras [][]byte) (string, []string) { + graphDigest := hiddenLockfileDigest( + []byte(hex.EncodeToString(hiddenLockfileDigest(module))), + []byte(hex.EncodeToString(hiddenLockfileDigest(trackedLock))), + []byte(hex.EncodeToString(hiddenLockfileDigest(bazelVersion))), + ) + extraParts := make([][]byte, 0, len(extras)) + for _, extra := range extras { + extraParts = append(extraParts, hiddenLockfileDigest(extra)) + } + extraDigest := "" + switch len(extraParts) { + case 0: + extraDigest = hex.EncodeToString(hiddenLockfileDigest(nil)) + case 1: + extraDigest = hex.EncodeToString(extraParts[0]) + default: + extraDigest = hex.EncodeToString(hiddenLockfileDigest(extraParts...)) + } + platformRoot := hiddenLockfileKeyRoot + "-" + platform + "-" + graphRoot := platformRoot + hex.EncodeToString(graphDigest) + return graphRoot + "-" + extraDigest, []string{graphRoot + "-", platformRoot} +} + +func hiddenLockfileDigest(parts ...[]byte) []byte { + hash := sha256.New() + for _, part := range parts { + _, _ = hash.Write(part) + } + return hash.Sum(nil) +} + +func readWorkspaceFile(workspace, name string) ([]byte, error) { + if name == "" { + return nil, errors.New("key file path cannot be empty") + } + if filepath.IsAbs(name) { + return nil, fmt.Errorf("key file %q must be relative to the workspace", name) + } + cleaned := filepath.Clean(name) + if cleaned == ".." || strings.HasPrefix(cleaned, ".."+string(filepath.Separator)) { + return nil, fmt.Errorf("key file %q leaves the workspace", name) + } + path := filepath.Join(workspace, cleaned) + content, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("read key file %q: %w", name, err) + } + return content, nil +} + +func restoreHiddenLockfileKey( + ctx context.Context, + backend hiddenLockfileBackend, + keys []string, + lockfile string, +) (string, error) { + if err := os.MkdirAll(filepath.Dir(lockfile), 0o700); err != nil { + return "", fmt.Errorf("prepare output base: %w", err) + } + temp, err := os.CreateTemp(filepath.Dir(lockfile), ".MODULE.bazel.lock-*") + if err != nil { + return "", fmt.Errorf("create restore file: %w", err) + } + tempName := temp.Name() + keep := false + defer func() { + _ = temp.Close() + if !keep { + _ = os.Remove(tempName) + } + }() + matchedKey, err := backend.Restore(ctx, keys, temp) + if err != nil { + return "", err + } + if matchedKey == "" { + return "", nil + } + if err := temp.Chmod(0o600); err != nil { + return "", fmt.Errorf("set restored lockfile permissions: %w", err) + } + if err := temp.Close(); err != nil { + return "", fmt.Errorf("close restored lockfile: %w", err) + } + if err := os.Rename(tempName, lockfile); err != nil { + // Windows cannot replace an existing destination with Rename. + if removeErr := os.Remove(lockfile); removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) { + return "", fmt.Errorf("replace hidden lockfile: %w", err) + } + if err := os.Rename(tempName, lockfile); err != nil { + return "", fmt.Errorf("replace hidden lockfile: %w", err) + } + } + keep = true + return matchedKey, nil +} + +func saveHiddenLockfile( + ctx context.Context, + backend hiddenLockfileBackend, + workspace string, + lockfile string, + key string, + publish bool, + publishIfChanged bool, + refresh func(context.Context, string) error, +) (hiddenLockfileSaveResult, error) { + before, previouslyExisted, err := hiddenLockfileFileDigest(lockfile) + if err != nil { + return hiddenLockfileSaveResult{}, err + } + if err := refresh(ctx, workspace); err != nil { + return hiddenLockfileSaveResult{}, fmt.Errorf("refresh hidden lockfile: %w", err) + } + file, err := os.Open(lockfile) + if err != nil { + return hiddenLockfileSaveResult{}, fmt.Errorf("open hidden lockfile: %w", err) + } + defer file.Close() + info, err := file.Stat() + if err != nil { + return hiddenLockfileSaveResult{}, fmt.Errorf("stat hidden lockfile: %w", err) + } + if !info.Mode().IsRegular() { + return hiddenLockfileSaveResult{}, errors.New("hidden lockfile is not a regular file") + } + afterHash := sha256.New() + if _, err := io.Copy(io.Discard, io.TeeReader(file, afterHash)); err != nil { + return hiddenLockfileSaveResult{}, fmt.Errorf("read refreshed hidden lockfile: %w", err) + } + changed := !previouslyExisted || !bytes.Equal(before, afterHash.Sum(nil)) + if _, err := file.Seek(0, io.SeekStart); err != nil { + return hiddenLockfileSaveResult{}, fmt.Errorf("rewind hidden lockfile: %w", err) + } + shouldPublish := publish && (publishIfChanged || !changed || !previouslyExisted) + if shouldPublish { + if err := backend.Save(ctx, key, file, info.Size()); err != nil { + return hiddenLockfileSaveResult{}, err + } + } + return hiddenLockfileSaveResult{ + Changed: changed, + PreviouslyExisted: previouslyExisted, + Saved: shouldPublish, + Key: key, + }, nil +} + +func hiddenLockfileFileDigest(path string) ([]byte, bool, error) { + file, err := os.Open(path) + if errors.Is(err, os.ErrNotExist) { + return nil, false, nil + } + if err != nil { + return nil, false, fmt.Errorf("open hidden lockfile before refresh: %w", err) + } + defer file.Close() + info, err := file.Stat() + if err != nil { + return nil, false, fmt.Errorf("stat hidden lockfile before refresh: %w", err) + } + if !info.Mode().IsRegular() { + return nil, false, errors.New("hidden lockfile before refresh is not a regular file") + } + hash := sha256.New() + if _, err := io.Copy(hash, file); err != nil { + return nil, false, fmt.Errorf("read hidden lockfile before refresh: %w", err) + } + return hash.Sum(nil), true, nil +} + +func bazelOutputBase(ctx context.Context, workspace string) (string, error) { + command := exec.CommandContext(ctx, "bazel", "info", "output_base") + command.Dir = workspace + output, err := command.Output() + if err != nil { + return "", fmt.Errorf("run bazel info output_base: %w", err) + } + return string(output), nil +} + +func refreshHiddenLockfile(ctx context.Context, workspace string, stdout, stderr io.Writer) error { + command := exec.CommandContext(ctx, "bazel", "mod", "deps", "--lockfile_mode=update") + command.Dir = workspace + command.Stdout = stdout + command.Stderr = stderr + return command.Run() +} diff --git a/cmd/cache-server/hidden_lockfile_test.go b/cmd/cache-server/hidden_lockfile_test.go new file mode 100644 index 0000000..66ddef9 --- /dev/null +++ b/cmd/cache-server/hidden_lockfile_test.go @@ -0,0 +1,307 @@ +package main + +import ( + "bytes" + "context" + "io" + "os" + "path/filepath" + "strings" + "testing" +) + +type memoryHiddenLockfileBackend struct { + entries map[string][]byte + saved map[string][]byte +} + +func (b *memoryHiddenLockfileBackend) Restore(_ context.Context, keys []string, dst io.Writer) (string, error) { + for _, key := range keys { + content, ok := b.entries[key] + if ok { + _, err := dst.Write(content) + return key, err + } + for candidate, fallback := range b.entries { + if strings.HasPrefix(candidate, key) { + _, err := dst.Write(fallback) + return candidate, err + } + } + } + return "", nil +} + +func (b *memoryHiddenLockfileBackend) Save(_ context.Context, key string, src *os.File, size int64) error { + if b.saved == nil { + b.saved = make(map[string][]byte) + } + content, err := io.ReadAll(io.LimitReader(src, size)) + if err == nil { + b.saved[key] = content + } + return err +} + +func TestDeriveHiddenLockfileKeysUsesReferenceDigests(t *testing.T) { + primary, restore := deriveHiddenLockfileKeys( + "Linux-X64", + []byte("module"), + []byte("tracked"), + []byte("version"), + [][]byte{[]byte("pnpm")}, + ) + const expected = "bazel-gha-cache-hidden-lockfile-v1-Linux-X64-cc2c17ff540c180bee987fb8843248dfdbc1df84d29fdbedbe6510b0a370d47c-2e5aa0361aaffd9121d965204bff293f4a12be1e71208fea0cb44739a4356999" + if primary != expected { + t.Fatalf("primary = %q, want %q", primary, expected) + } + if len(restore) != 2 || + !strings.HasPrefix(primary, restore[0]) || + !strings.HasPrefix(primary, restore[1]) { + t.Fatalf("restore prefixes = %v for %q", restore, primary) + } +} + +func TestRestoreHiddenLockfileUsesGraphFallback(t *testing.T) { + workspace := t.TempDir() + for name, content := range map[string]string{ + "MODULE.bazel": "module", + "MODULE.bazel.lock": "tracked", + ".bazelversion": "version", + "pnpm-lock.yaml": "pnpm", + } { + if err := os.WriteFile(filepath.Join(workspace, name), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + outputBase := filepath.Join(t.TempDir(), "output-base") + primary, restore := deriveHiddenLockfileKeys( + "Linux-X64", + []byte("module"), + []byte("tracked"), + []byte("version"), + [][]byte{[]byte("pnpm")}, + ) + fallback := restore[0] + "older-extra" + backend := &memoryHiddenLockfileBackend{entries: map[string][]byte{ + fallback: []byte("hidden lock"), + }} + result, err := restoreHiddenLockfile( + context.Background(), + backend, + workspace, + []string{"pnpm-lock.yaml"}, + "Linux-X64", + func(context.Context, string) (string, error) { return outputBase, nil }, + ) + if err != nil { + t.Fatal(err) + } + if result.PrimaryKey != primary || result.MatchedKey != fallback || result.CacheHit { + t.Fatalf("result = %+v", result) + } + content, err := os.ReadFile(result.Lockfile) + if err != nil { + t.Fatal(err) + } + if string(content) != "hidden lock" { + t.Fatalf("lockfile = %q", content) + } +} + +func TestRestoreHiddenLockfileReportsPrimaryHit(t *testing.T) { + workspace := t.TempDir() + for name, content := range map[string]string{ + "MODULE.bazel": "module", + "MODULE.bazel.lock": "tracked", + ".bazelversion": "version", + } { + if err := os.WriteFile(filepath.Join(workspace, name), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + primary, _ := deriveHiddenLockfileKeys( + "Linux-X64", + []byte("module"), + []byte("tracked"), + []byte("version"), + nil, + ) + backend := &memoryHiddenLockfileBackend{entries: map[string][]byte{primary: []byte("hidden")}} + result, err := restoreHiddenLockfile( + context.Background(), + backend, + workspace, + nil, + "Linux-X64", + func(context.Context, string) (string, error) { return t.TempDir(), nil }, + ) + if err != nil { + t.Fatal(err) + } + if result.MatchedKey != primary || !result.CacheHit { + t.Fatalf("result = %+v", result) + } +} + +func TestRestoreHiddenLockfileRejectsKeyOutsideWorkspace(t *testing.T) { + workspace := t.TempDir() + for name, content := range map[string]string{ + "MODULE.bazel": "module", + "MODULE.bazel.lock": "tracked", + ".bazelversion": "version", + } { + if err := os.WriteFile(filepath.Join(workspace, name), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + _, err := restoreHiddenLockfile( + context.Background(), + &memoryHiddenLockfileBackend{}, + workspace, + []string{"../secret"}, + "Linux-X64", + func(context.Context, string) (string, error) { return t.TempDir(), nil }, + ) + if err == nil || !strings.Contains(err.Error(), "leaves the workspace") { + t.Fatalf("error = %v", err) + } +} + +func TestSaveHiddenLockfileRefreshesBeforePublishing(t *testing.T) { + workspace := t.TempDir() + lockfile := filepath.Join(t.TempDir(), "MODULE.bazel.lock") + backend := &memoryHiddenLockfileBackend{} + refreshed := false + result, err := saveHiddenLockfile( + context.Background(), + backend, + workspace, + lockfile, + "primary", + true, + true, + func(_ context.Context, gotWorkspace string) error { + refreshed = true + if gotWorkspace != workspace { + t.Fatalf("workspace = %q", gotWorkspace) + } + return os.WriteFile(lockfile, []byte("refreshed"), 0o600) + }, + ) + if err != nil { + t.Fatal(err) + } + if !refreshed || !bytes.Equal(backend.saved["primary"], []byte("refreshed")) { + t.Fatalf("refreshed=%t saved=%q", refreshed, backend.saved["primary"]) + } + if !result.Changed || result.PreviouslyExisted { + t.Fatalf("result = %+v", result) + } +} + +func TestSaveHiddenLockfileReportsRefreshChange(t *testing.T) { + workspace := t.TempDir() + lockfile := filepath.Join(t.TempDir(), "MODULE.bazel.lock") + if err := os.WriteFile(lockfile, []byte("restored"), 0o600); err != nil { + t.Fatal(err) + } + backend := &memoryHiddenLockfileBackend{} + result, err := saveHiddenLockfile( + context.Background(), + backend, + workspace, + lockfile, + "primary", + true, + true, + func(_ context.Context, _ string) error { + return os.WriteFile(lockfile, []byte("refreshed"), 0o600) + }, + ) + if err != nil { + t.Fatal(err) + } + if !result.Changed || !result.PreviouslyExisted { + t.Fatalf("result = %+v", result) + } +} + +func TestSaveHiddenLockfileReportsUnchangedRefresh(t *testing.T) { + workspace := t.TempDir() + lockfile := filepath.Join(t.TempDir(), "MODULE.bazel.lock") + if err := os.WriteFile(lockfile, []byte("restored"), 0o600); err != nil { + t.Fatal(err) + } + backend := &memoryHiddenLockfileBackend{} + result, err := saveHiddenLockfile( + context.Background(), + backend, + workspace, + lockfile, + "primary", + true, + true, + func(context.Context, string) error { return nil }, + ) + if err != nil { + t.Fatal(err) + } + if result.Changed || !result.PreviouslyExisted { + t.Fatalf("result = %+v", result) + } +} + +func TestSaveHiddenLockfileCanAuditWithoutPublishing(t *testing.T) { + workspace := t.TempDir() + lockfile := filepath.Join(t.TempDir(), "MODULE.bazel.lock") + if err := os.WriteFile(lockfile, []byte("restored"), 0o600); err != nil { + t.Fatal(err) + } + backend := &memoryHiddenLockfileBackend{} + result, err := saveHiddenLockfile( + context.Background(), + backend, + workspace, + lockfile, + "primary", + false, + true, + func(_ context.Context, _ string) error { + return os.WriteFile(lockfile, []byte("refreshed"), 0o600) + }, + ) + if err != nil { + t.Fatal(err) + } + if !result.Changed || result.Saved || backend.saved != nil { + t.Fatalf("result=%+v saved=%v", result, backend.saved) + } +} + +func TestSaveHiddenLockfileCanSkipChangedPublication(t *testing.T) { + workspace := t.TempDir() + lockfile := filepath.Join(t.TempDir(), "MODULE.bazel.lock") + if err := os.WriteFile(lockfile, []byte("restored"), 0o600); err != nil { + t.Fatal(err) + } + backend := &memoryHiddenLockfileBackend{} + result, err := saveHiddenLockfile( + context.Background(), + backend, + workspace, + lockfile, + "primary", + true, + false, + func(_ context.Context, _ string) error { + return os.WriteFile(lockfile, []byte("refreshed"), 0o600) + }, + ) + if err != nil { + t.Fatal(err) + } + if !result.Changed || result.Saved || backend.saved != nil { + t.Fatalf("result=%+v saved=%v", result, backend.saved) + } +} diff --git a/cmd/cache-server/main.go b/cmd/cache-server/main.go index daedc43..a268b19 100644 --- a/cmd/cache-server/main.go +++ b/cmd/cache-server/main.go @@ -15,6 +15,9 @@ import ( "syscall" "time" + "google.golang.org/grpc" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/artifact" "github.com/cre4ture/bazel-github-actions-cache-v2/internal/cache" cacheserver "github.com/cre4ture/bazel-github-actions-cache-v2/internal/server" ) @@ -23,12 +26,27 @@ var version = "dev" type readyInfo struct { URL string `json:"url"` + GRPCURL string `json:"grpc_url"` StatsURL string `json:"stats_url"` PID int `json:"pid"` Version string `json:"version"` } func main() { + if len(os.Args) > 1 && os.Args[1] == uploadArtifactCommandName { + if err := uploadArtifactCommand(os.Args[2:], newArtifactUploader, os.Stdout); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + return + } + if len(os.Args) > 1 && os.Args[1] == hiddenLockfileCommandName { + if err := hiddenLockfileCommand(os.Args[2:], os.Stdout, os.Stderr); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + return + } if err := run(); err != nil { log.Printf("fatal: %v", err) os.Exit(1) @@ -38,12 +56,15 @@ func main() { func run() error { var ( port = flag.Int("port", 0, "loopback TCP port; zero selects a dynamic port") + grpcPort = flag.Int("grpc-port", 0, "loopback TCP port for the gRPC remote-cache API; zero selects a dynamic port") cacheDir = flag.String("cache-dir", "", "local spool directory") keyPrefix = flag.String("key-prefix", "bazel-http-v1", "GitHub cache key prefix") - storageMode = flag.String("storage-mode", "objects", "storage mode: objects or packs") packSize = flag.Int64("pack-size", 8*1024*1024, "target CARv2 pack size in bytes") packFlush = flag.Duration("pack-flush-interval", 30*time.Second, "maximum delay before flushing pending CARv2 data") - maxManifests = flag.Int("max-manifests", 2048, "maximum manifest cache entries to discover") + packRenew = flag.Duration("pack-renew-interval", 15*time.Second, "delay before renewing retention for packs that only presence checks touched") + packCompression = flag.Bool("pack-compression", true, "compress individual pack blocks that shrink meaningfully") + packLevel = flag.Int64("pack-compression-level", 3, "zstd level used for pack blocks (1-19)") + maxManifests = flag.Int("max-manifests", 2048, "maximum manifests to read during discovery; any beyond this are ignored") writeEnabled = flag.Bool("write-enabled", false, "publish validated uploads") failOpen = flag.Bool("fail-open", true, "degrade backend errors to misses/success") maxBlobSize = flag.Int64("max-blob-size", 512*1024*1024, "maximum object size in bytes") @@ -52,6 +73,8 @@ func run() error { backendTimeout = flag.Duration("backend-timeout", 5*time.Minute, "timeout per backend operation") readyFile = flag.String("ready-file", "", "write startup metadata to this file") statsFile = flag.String("stats-file", "", "write final statistics to this file") + usageArtifact = flag.String("usage-artifact", "", "publish the usage record as a job artifact with this name; empty disables it") + assetRoutes = flag.String("asset-header-routes", "", "newline-separated https URI patterns whose credentials may be forwarded to an origin") showVersion = flag.Bool("version", false, "print version and exit") ) flag.Parse() @@ -81,6 +104,14 @@ func run() error { address := listener.Addr().(*net.TCPAddr) baseURL := "http://127.0.0.1:" + strconv.Itoa(address.Port) + grpcListener, err := net.Listen("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(*grpcPort))) + if err != nil { + return fmt.Errorf("listen on loopback for gRPC: %w", err) + } + defer grpcListener.Close() + grpcAddress := grpcListener.Addr().(*net.TCPAddr) + grpcURL := "grpc://127.0.0.1:" + strconv.Itoa(grpcAddress.Port) + shutdownRequested := make(chan struct{}, 1) requestShutdown := func() { select { @@ -89,31 +120,31 @@ func run() error { } } logger := log.New(os.Stderr, "bazel-gha-cache: ", log.LstdFlags|log.LUTC) - var catalog cache.Catalog - if *storageMode == "packs" { - catalog, err = cache.NewActionsCatalog(*backendTimeout) - if err != nil { - return err - } + catalog, err := cache.NewActionsCatalog(*backendTimeout, logger) + if err != nil { + return err } srv, err := cacheserver.New(cacheserver.Config{ - Backend: backend, - Catalog: catalog, - CacheDir: dir, - KeyPrefix: *keyPrefix, - StorageMode: *storageMode, - PackSize: *packSize, - PackFlushInterval: *packFlush, - MaxManifests: *maxManifests, - WriteEnabled: *writeEnabled, - FailOpen: *failOpen, - MaxBlobSize: *maxBlobSize, - MaxConcurrent: *maxConcurrent, - UploadsPerMinute: *uploadsPerMinute, - BackendTimeout: *backendTimeout, - ShutdownToken: os.Getenv("BAZEL_GHA_CACHE_SHUTDOWN_TOKEN"), - Shutdown: requestShutdown, - Logger: logger, + Backend: backend, + Catalog: catalog, + CacheDir: dir, + KeyPrefix: *keyPrefix, + PackSize: *packSize, + PackFlushInterval: *packFlush, + PackRenewInterval: *packRenew, + PackCompression: *packCompression, + PackCompressionLevel: *packLevel, + MaxManifests: *maxManifests, + WriteEnabled: *writeEnabled, + FailOpen: *failOpen, + MaxBlobSize: *maxBlobSize, + MaxConcurrent: *maxConcurrent, + UploadsPerMinute: *uploadsPerMinute, + BackendTimeout: *backendTimeout, + ShutdownToken: os.Getenv("BAZEL_GHA_CACHE_SHUTDOWN_TOKEN"), + AssetHeaderRoutes: []string{*assetRoutes}, + Shutdown: requestShutdown, + Logger: logger, }) if err != nil { return err @@ -128,17 +159,22 @@ func run() error { IdleTimeout: 90 * time.Second, MaxHeaderBytes: 16 * 1024, } - serveErr := make(chan error, 1) + serveErr := make(chan error, 2) go func() { - err := httpServer.Serve(listener) - if err != nil && err != http.ErrServerClosed { - serveErr <- err + if err := httpServer.Serve(listener); err != nil && err != http.ErrServerClosed { + serveErr <- fmt.Errorf("serve http: %w", err) + } + }() + grpcServer := srv.GRPCHandler() + go func() { + if err := grpcServer.Serve(grpcListener); err != nil && err != grpc.ErrServerStopped { + serveErr <- fmt.Errorf("serve grpc: %w", err) } - close(serveErr) }() ready := readyInfo{ URL: baseURL, + GRPCURL: grpcURL, StatsURL: baseURL + "/stats", PID: os.Getpid(), Version: version, @@ -150,7 +186,7 @@ func run() error { if err := os.WriteFile(*readyFile, append(data, '\n'), 0o600); err != nil { return fmt.Errorf("write ready file: %w", err) } - logger.Printf("ready on %s (write=%t, fail_open=%t)", baseURL, *writeEnabled, *failOpen) + logger.Printf("ready on %s and %s (write=%t, fail_open=%t)", baseURL, grpcURL, *writeEnabled, *failOpen) signals := make(chan os.Signal, 1) signal.Notify(signals, os.Interrupt, syscall.SIGTERM) @@ -161,9 +197,7 @@ func run() error { case <-shutdownRequested: logger.Printf("shutdown requested") case err := <-serveErr: - if err != nil { - return fmt.Errorf("serve: %w", err) - } + return err } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) @@ -172,6 +206,7 @@ func run() error { logger.Printf("graceful shutdown failed: %v", err) _ = httpServer.Close() } + stopGRPC(grpcServer) flushContext, flushCancel := context.WithTimeout(context.Background(), *backendTimeout) if err := srv.Close(flushContext); err != nil { logger.Printf("flush packed cache: %v", err) @@ -181,6 +216,42 @@ func run() error { if err := cacheserver.WriteStatsFile(*statsFile, stats); err != nil { logger.Printf("write stats: %v", err) } + // Published here rather than by a workflow step because post steps run last; + // nothing else gets a chance to collect it. + publishUsage(*usageArtifact, srv, *backendTimeout, logger) logger.Printf("stopped: %s", strings.TrimSpace(string(stats.JSON()))) return nil } + +func publishUsage(name string, srv *cacheserver.Server, timeout time.Duration, logger *log.Logger) { + if name == "" { + return + } + uploader, err := artifact.New(timeout) + if err != nil { + logger.Printf("not publishing the usage record: %v", err) + return + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + if err := uploader.Upload(ctx, name, "cache-usage.json", srv.Usage().JSON()); err != nil { + logger.Printf("publishing the usage record failed: %v", err) + return + } + logger.Printf("published the usage record as artifact %q", name) +} + +// stopGRPC drains in-flight RPCs, but does not let a stuck stream hold up the +// post step that has to flush the cache before the job ends. +func stopGRPC(server *grpc.Server) { + stopped := make(chan struct{}) + go func() { + server.GracefulStop() + close(stopped) + }() + select { + case <-stopped: + case <-time.After(10 * time.Second): + server.Stop() + } +} diff --git a/cmd/cache-server/upload_artifact.go b/cmd/cache-server/upload_artifact.go new file mode 100644 index 0000000..6455a93 --- /dev/null +++ b/cmd/cache-server/upload_artifact.go @@ -0,0 +1,130 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "os" + "path/filepath" + "regexp" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/artifact" +) + +const uploadArtifactCommandName = "upload-artifact" + +// defaultMaxArtifactBytes bounds what one upload holds in memory. A runtime +// crash dump lists every goroutine, so a burst of tens of thousands of +// requests can produce a log of hundreds of MiB. +const defaultMaxArtifactBytes = 256 * 1024 * 1024 + +var artifactNamePattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,180}$`) + +type artifactUploader interface { + Upload(ctx context.Context, name, fileName string, content []byte) error +} + +func newArtifactUploader(timeout time.Duration) (artifactUploader, error) { + return artifact.New(timeout) +} + +// uploadArtifactCommand publishes one file as a job artifact. The post step +// runs it to keep the server log, which the server cannot publish itself when +// it has crashed. +func uploadArtifactCommand( + args []string, + newUploader func(time.Duration) (artifactUploader, error), + stdout io.Writer, +) error { + flags := flag.NewFlagSet(uploadArtifactCommandName, flag.ContinueOnError) + flags.SetOutput(io.Discard) + var ( + name = flags.String("name", "", "artifact name") + file = flags.String("file", "", "file to publish") + entryName = flags.String("entry-name", "", "file name inside the artifact; defaults to the file's base name") + timeout = flags.Duration("timeout", 2*time.Minute, "timeout for the whole upload") + maxBytes = flags.Int64("max-bytes", defaultMaxArtifactBytes, "larger files keep their head and tail") + ) + if err := flags.Parse(args); err != nil { + return fmt.Errorf("%s: %w", uploadArtifactCommandName, err) + } + if flags.NArg() != 0 { + return fmt.Errorf("%s: unexpected arguments %q", uploadArtifactCommandName, flags.Args()) + } + if !artifactNamePattern.MatchString(*name) { + return fmt.Errorf("%s: --name must match %s", uploadArtifactCommandName, artifactNamePattern) + } + if *file == "" { + return fmt.Errorf("%s: --file is required", uploadArtifactCommandName) + } + if *timeout <= 0 || *maxBytes <= 0 { + return fmt.Errorf("%s: --timeout and --max-bytes must be positive", uploadArtifactCommandName) + } + if *entryName == "" { + *entryName = filepath.Base(*file) + } + + content, omitted, err := readBounded(*file, *maxBytes) + if err != nil { + return fmt.Errorf("%s: %w", uploadArtifactCommandName, err) + } + uploader, err := newUploader(*timeout) + if err != nil { + return fmt.Errorf("%s: %w", uploadArtifactCommandName, err) + } + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + if err := uploader.Upload(ctx, *name, *entryName, content); err != nil { + return fmt.Errorf("%s: %w", uploadArtifactCommandName, err) + } + if omitted > 0 { + fmt.Fprintf(stdout, "published %s as artifact %q with %d bytes omitted from the middle\n", *entryName, *name, omitted) + } else { + fmt.Fprintf(stdout, "published %s as artifact %q\n", *entryName, *name) + } + return nil +} + +// readBounded returns the whole file, or its head and tail around a marker when +// it exceeds limit. Both ends matter for a crash: the head holds the fatal +// error and the tail holds the last goroutines. +func readBounded(path string, limit int64) ([]byte, int64, error) { + file, err := os.Open(path) + if err != nil { + return nil, 0, err + } + defer file.Close() + info, err := file.Stat() + if err != nil { + return nil, 0, err + } + if !info.Mode().IsRegular() { + return nil, 0, errors.New("--file must name a regular file") + } + size := info.Size() + if size <= limit { + content, err := io.ReadAll(io.LimitReader(file, limit)) + return content, 0, err + } + + headSize := limit / 2 + tailSize := limit - headSize + omitted := size - headSize - tailSize + marker := fmt.Sprintf("\n\n[... %d bytes omitted ...]\n\n", omitted) + content := make([]byte, 0, limit+int64(len(marker))) + head := make([]byte, headSize) + if _, err := io.ReadFull(file, head); err != nil { + return nil, 0, err + } + tail := make([]byte, tailSize) + if _, err := file.ReadAt(tail, size-tailSize); err != nil { + return nil, 0, err + } + content = append(content, head...) + content = append(content, marker...) + content = append(content, tail...) + return content, omitted, nil +} diff --git a/cmd/cache-server/upload_artifact_test.go b/cmd/cache-server/upload_artifact_test.go new file mode 100644 index 0000000..2f52c74 --- /dev/null +++ b/cmd/cache-server/upload_artifact_test.go @@ -0,0 +1,139 @@ +package main + +import ( + "bytes" + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +type recordedUpload struct { + name, fileName string + content []byte + timeout time.Duration +} + +func fakeUploader(record *recordedUpload, err error) func(time.Duration) (artifactUploader, error) { + return func(timeout time.Duration) (artifactUploader, error) { + record.timeout = timeout + return uploaderFunc(func(_ context.Context, name, fileName string, content []byte) error { + record.name, record.fileName, record.content = name, fileName, content + return err + }), nil + } +} + +type uploaderFunc func(ctx context.Context, name, fileName string, content []byte) error + +func (f uploaderFunc) Upload(ctx context.Context, name, fileName string, content []byte) error { + return f(ctx, name, fileName, content) +} + +func writeLog(t *testing.T, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "server.log") + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + return path +} + +func TestUploadArtifactPublishesTheWholeFile(t *testing.T) { + path := writeLog(t, "ready\nfatal error: thread exhaustion\n") + var record recordedUpload + var stdout bytes.Buffer + err := uploadArtifactCommand( + []string{"--name", "bazel-cache-server-log", "--file", path, "--entry-name", "cache-server.log", "--timeout", "30s"}, + fakeUploader(&record, nil), + &stdout, + ) + if err != nil { + t.Fatal(err) + } + if record.name != "bazel-cache-server-log" || record.fileName != "cache-server.log" || record.timeout != 30*time.Second { + t.Fatalf("upload = %+v", record) + } + if string(record.content) != "ready\nfatal error: thread exhaustion\n" { + t.Fatalf("content = %q", record.content) + } + if !strings.Contains(stdout.String(), `artifact "bazel-cache-server-log"`) { + t.Fatalf("stdout = %q", stdout.String()) + } +} + +func TestUploadArtifactDefaultsTheEntryNameToTheFileName(t *testing.T) { + path := writeLog(t, "ready\n") + var record recordedUpload + err := uploadArtifactCommand([]string{"--name", "log", "--file", path}, fakeUploader(&record, nil), &bytes.Buffer{}) + if err != nil { + t.Fatal(err) + } + if record.fileName != "server.log" { + t.Fatalf("entry name = %q", record.fileName) + } +} + +// A crash dump can be far larger than the useful part of it, and the fatal +// error sits at its head while the tail holds the last goroutines. +func TestUploadArtifactKeepsHeadAndTailOfOversizedFiles(t *testing.T) { + path := writeLog(t, "HEAD-"+strings.Repeat("x", 1000)+"-TAIL") + var record recordedUpload + var stdout bytes.Buffer + err := uploadArtifactCommand( + []string{"--name", "log", "--file", path, "--max-bytes", "100"}, + fakeUploader(&record, nil), + &stdout, + ) + if err != nil { + t.Fatal(err) + } + content := string(record.content) + if !strings.HasPrefix(content, "HEAD-") || !strings.HasSuffix(content, "-TAIL") { + t.Fatalf("content lost an end: %q", content) + } + if !strings.Contains(content, "[... 910 bytes omitted ...]") { + t.Fatalf("content has no omission marker: %q", content) + } + if !strings.Contains(stdout.String(), "910 bytes omitted") { + t.Fatalf("stdout = %q", stdout.String()) + } +} + +func TestUploadArtifactRejectsInvalidArguments(t *testing.T) { + path := writeLog(t, "ready\n") + for _, args := range [][]string{ + {"--file", path}, + {"--name", "bad name", "--file", path}, + {"--name", "log"}, + {"--name", "log", "--file", path, "extra"}, + {"--name", "log", "--file", path, "--timeout", "0s"}, + {"--name", "log", "--file", path, "--max-bytes", "0"}, + {"--name", "log", "--file", filepath.Dir(path)}, + {"--name", "log", "--file", filepath.Join(t.TempDir(), "missing.log")}, + } { + var record recordedUpload + if err := uploadArtifactCommand(args, fakeUploader(&record, nil), &bytes.Buffer{}); err == nil { + t.Errorf("args %q were accepted", args) + } + if record.name != "" { + t.Errorf("args %q uploaded anyway", args) + } + } +} + +func TestUploadArtifactReportsUploadFailures(t *testing.T) { + path := writeLog(t, "ready\n") + var record recordedUpload + err := uploadArtifactCommand( + []string{"--name", "log", "--file", path}, + fakeUploader(&record, errors.New("FinalizeArtifact returned HTTP 409")), + &bytes.Buffer{}, + ) + if err == nil || !strings.Contains(err.Error(), "HTTP 409") { + t.Fatalf("err = %v", err) + } +} diff --git a/dist/SHA256SUMS b/dist/SHA256SUMS deleted file mode 100644 index 187e7e5..0000000 --- a/dist/SHA256SUMS +++ /dev/null @@ -1,2 +0,0 @@ -f78d1caf02f9211eaf6e680e9dd5692b1a03355365505f617a5ad3fd254af0f0 cache-server-linux-amd64 -f6881c1ecefc1aa070bfe62ee567c45508e187da5af09fb1529bb00709a7ba30 cache-server-linux-arm64 diff --git a/dist/cache-server-linux-amd64 b/dist/cache-server-linux-amd64 deleted file mode 100755 index bbbdec4..0000000 Binary files a/dist/cache-server-linux-amd64 and /dev/null differ diff --git a/dist/cache-server-linux-arm64 b/dist/cache-server-linux-arm64 deleted file mode 100755 index 943adc1..0000000 Binary files a/dist/cache-server-linux-arm64 and /dev/null differ diff --git a/docs/carv2-manifest-dag-concept.md b/docs/carv2-manifest-dag-concept.md index 7944d15..ace9267 100644 --- a/docs/carv2-manifest-dag-concept.md +++ b/docs/carv2-manifest-dag-concept.md @@ -1,7 +1,8 @@ # Concept: CARv2 packs and a manifest DAG -Status: implemented in v0.3 as the opt-in `storage-mode: packs` format. It does -not change the v0.2 object-per-entry format or its wire compatibility. +Status: implemented as the cache's only storage format. It preserves the +existing HTTP and gRPC interfaces while replacing the earlier object-per-entry +backend. Legacy object-per-entry cache entries are not read or migrated. ## Problem @@ -33,8 +34,7 @@ hosted cache server or weakening Remote Execution API (REAPI) correctness. - Making GitHub Actions Cache a durable artifact store. - Supporting writes from untrusted pull requests or forks. - Introducing remote execution, a gRPC API, or a persistent service. -- Replacing the v0.2 key space in place. The new backend uses a new namespace - and can be rolled out or removed independently. +- Reading or migrating legacy v0.2 object-per-entry keys. ## Data model @@ -52,8 +52,15 @@ A pack is an immutable [CARv2][go-car] file produced with - A pack is identified by the SHA-256 of its complete CARv2 bytes and stored under an immutable Actions-cache key such as `-pack-v1-`. -- Packs are not additionally compressed. The GitHub cache transport already - compresses its value. +- Packs are stored uncompressed, and nothing else compresses them either. The + cache-v2 client uploads the bytes verbatim to a block blob with no content + encoding, and finalizes the entry with the raw length, which is what counts + against the repository quota. Individual blocks are therefore compressed with + zstd before they are written into the pack, and the manifest records the + encoding and the CID of the stored bytes. Per-block rather than per-pack + compression keeps the footer index useful, since serving one object + decompresses only that object, and lets a single pack mix compressed and + verbatim blocks. Packs should have a modest target size, initially 8 MiB and at most 32 MiB. Oversized output blobs receive a single-blob pack. GitHub Actions Cache restores @@ -63,8 +70,17 @@ small CAS read into excessive transfer. ### Manifest A manifest is a small immutable DAG-CBOR block encoded with -`go-ipld-prime`. Its CID is the manifest identifier and its Actions-cache key -is derived from that CID. +`go-ipld-prime`. Its CID is the manifest identifier, and its Actions-cache key +pairs that CID with the single pack the manifest commits: +`-car-manifest-v2--`. + +The pairing is what makes the two entries share a fate. Every mapping a +manifest introduces lives in that one pack, so once the pack is gone the +manifest has nothing left to offer and a reader can tell that from the key +alone. This matters because a read renews an entry's retention: a manifest that +is downloaded on every run never ages out, while the much larger pack it +describes is evicted under the repository quota. Leaving orphaned manifests +unread lets them expire on the same schedule as the data they describe. The implemented DAG-CBOR schema has this logical content: @@ -74,16 +90,25 @@ Manifest { parents: [ManifestCID] packs: [PackDescriptor { pack_cid, cache_key, byte_size }] cas_entries: [CASDigest -> PackCID] - action_entries: [ActionDigest -> ActionResultCID, closure_pack_cids] + action_entries: [ActionDigest -> ActionResultCID] } ``` +Format 2 still writes an empty `closure` list on each action entry for +compatibility with older readers. Legacy closure values are ignored; runtime +closure validation uses the Action Result itself. +Raw entries omit `block` and `encoding`, which default to the content CID and +verbatim bytes. The server's long-lived CAS index derives the content CID from +the digest and retains a block CID only for compressed entries. + Entries are deltas introduced by that manifest, not a full copy of every ancestor. A reader merges them from the roots toward the heads. The mapping -must be deterministic: the same CAS digest always denotes identical bytes. Two -different Action Result values for one Action Digest indicate a non-deterministic -build and are not silently selected; the adapter reports a cache miss and logs -the conflict. +must be deterministic: the same CAS digest always denotes identical bytes. One +Action Digest may carry several different Action Result values, because Bazel +records execution timestamps in every result and overlapping writers each +upload one. Any of them is a valid answer, so the adapter serves the copy in +the lowest pack ID, counts the key in `action_digest_conflicts`, and logs a +warning. The optimiser treats the other copies as dead, so they are reclaimed. Using [CARv2][go-car] and [IPLD][go-ipld] avoids inventing either a packed content-addressed file format or a graph serialization and traversal format. @@ -136,22 +161,27 @@ merge. ## Read protocol and eviction -1. Bootstrap an in-memory manifest view from all discoverable heads. -2. For `GET /ac/`, resolve the Action Result mapping, restore its - pack, and validate every declared closure pack and referenced CAS digest. +1. Bootstrap an in-memory manifest view from all discoverable heads. Manifests + whose pack is absent from the pack listing are skipped without being read. +2. For `GET /ac/`, resolve the Action Result mapping and restore + its pack, then confirm every closure member referenced by the Action Result + is mapped to a pack that still exists and has the declared size. Closure + packs are not restored; their retention is renewed instead. 3. For `GET /cas/`, resolve its pack, restore it on demand, look up the CID in the CARv2 index, and verify digest and size before responding. 4. If a manifest, pack, or closure member is missing or fails verification, return a cache miss. +5. A CAS presence check resolves from the manifest view without restoring the + pack, and schedules one deferred retention renewal for it. GitHub can evict any cache entry independently. The manifest must therefore not be treated as a promise that a pack still exists. This retains the v0.2 safety property that incomplete Action Results are never served. -## Rollout and validation +A checkpoint manifest that commits several packs at once does not fit the +single-pack key, and needs its own key scheme before compaction can be added. -The implementation should be a separate backend mode and namespace, initially -opt-in. Keep v0.2 available as a rollback path. +## Implementation and validation Required tests include: @@ -161,16 +191,15 @@ Required tests include: checkpoint. - Visibility ordering: a manifest cannot be resolved before its pack exists. - Missing or corrupt pack and incomplete closure behaviour, all as cache misses. -- Action Digest conflict detection. +- Deterministic resolution of Action Digest conflicts. - GitHub-cache API discovery pagination, unavailable API handling, and scoped branch/default-branch reads. - An end-to-end cold seed followed by a fresh-runner warm restore, measuring cache-entry creations, transfer volume, and hit rate. -The initial implementation uses an 8 MiB target and a 32 MiB normal-pack limit; -an individual oversized CAS output receives its own pack. It is released -opt-in so representative cold-seed and warm-read runs can tune those defaults -without altering the v0.2 rollback path. +The implementation uses an 8 MiB target and a 32 MiB normal-pack limit; an +individual oversized CAS output receives its own pack. Pack size can be +adjusted with the `pack-size-mb` action input. [go-car]: https://github.com/ipld/go-car [go-ipld]: https://github.com/ipld/go-ipld-prime diff --git a/go.mod b/go.mod index 2d3d8e5..f828cea 100644 --- a/go.mod +++ b/go.mod @@ -1,28 +1,36 @@ module github.com/cre4ture/bazel-github-actions-cache-v2 -go 1.26.0 +go 1.27.4 require ( - github.com/ipfs/go-block-format v0.2.3 - github.com/ipfs/go-cid v0.6.1 + cloud.google.com/go/longrunning v1.5.0 + github.com/ipfs/go-block-format v0.2.4 + github.com/ipfs/go-cid v0.6.2 github.com/ipld/go-car/v2 v2.17.0 github.com/ipld/go-ipld-prime v0.24.0 + github.com/klauspost/compress v1.20.4 github.com/multiformats/go-multihash v0.2.3 - github.com/tonistiigi/go-actions-cache v0.0.0-20260120203934-54bc28c26fd2 + github.com/tonistiigi/go-actions-cache v0.0.0-20260930145529-afe8013b5ac4 + golang.org/x/sync v0.25.0 + google.golang.org/genproto/googleapis/api v0.0.0-20261110000943-09e21b237f2c + google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c + google.golang.org/grpc v1.85.0 + google.golang.org/protobuf v1.36.12 + lukechampine.com/blake3 v1.4.1 ) -require google.golang.org/protobuf v1.36.11 - require ( - github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.5.0 // indirect - github.com/dimchansky/utfbom v1.1.1 // indirect - github.com/golang-jwt/jwt/v5 v5.2.2 // indirect - github.com/ipfs/boxo v0.39.0 // indirect - github.com/ipfs/go-ipld-cbor v0.2.1 // indirect - github.com/ipfs/go-ipld-format v0.6.3 // indirect - github.com/klauspost/cpuid/v2 v2.3.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.3 // indirect + github.com/Azure/azure-sdk-for-go/sdk/storage/internal v0.1.0 // indirect + github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c // indirect + github.com/dimchansky/utfbom v1.2.0 // indirect + github.com/golang-jwt/jwt/v5 v5.3.1 // indirect + github.com/ipfs/boxo v0.43.0 // indirect + github.com/ipfs/go-ipld-cbor v0.3.0 // indirect + github.com/ipfs/go-ipld-format v0.6.4 // indirect + github.com/klauspost/cpuid/v2 v2.4.2 // indirect github.com/minio/sha256-simd v1.0.1 // indirect github.com/mr-tron/base58 v1.3.0 // indirect github.com/multiformats/go-base32 v0.1.0 // indirect @@ -36,12 +44,22 @@ require ( github.com/spaolacci/murmur3 v1.1.0 // indirect github.com/whyrusleeping/cbor v0.0.0-20171005072247-63513f603b11 // indirect github.com/whyrusleeping/cbor-gen v0.3.1 // indirect - golang.org/x/crypto v0.51.0 // indirect - golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect - golang.org/x/net v0.55.0 // indirect - golang.org/x/sync v0.21.0 // indirect - golang.org/x/sys v0.45.0 // indirect - golang.org/x/text v0.39.0 // indirect + golang.org/x/crypto v0.59.0 // indirect + golang.org/x/exp v0.0.0-20261113113407-e3970619a1a4 // indirect + golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678 // indirect + golang.org/x/mod v0.42.0 // indirect + golang.org/x/net v0.62.0 // indirect + golang.org/x/sys v0.50.0 // indirect + golang.org/x/telemetry v0.0.0-20261010193011-f71dc92da45e // indirect + golang.org/x/text v0.44.0 // indirect + golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a // indirect + golang.org/x/vuln v1.9.0 // indirect golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect - lukechampine.com/blake3 v1.4.1 // indirect + honnef.co/go/tools v0.8.2 // indirect +) + +tool ( + golang.org/x/tools/cmd/deadcode + golang.org/x/vuln/cmd/govulncheck + honnef.co/go/tools/cmd/staticcheck ) diff --git a/go.sum b/go.sum index 1d8fe7c..015cc26 100644 --- a/go.sum +++ b/go.sum @@ -1,29 +1,64 @@ +cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= +cloud.google.com/go/longrunning v1.2.0 h1:WjYH3YHBGCxGJP9M4dWGHBfXr/cFIjMkNgWcJj7/iMM= +cloud.google.com/go/longrunning v1.2.0/go.mod h1:5KMQALFGOCtFoi2xSOA1u3H7WKlhmckgiyFw7+LGQp0= +cloud.google.com/go/longrunning v1.5.0 h1:aGonu6LHQl38DyozLs2jxGieI4Ixk+7GTnmHVcHt8zA= +cloud.google.com/go/longrunning v1.5.0/go.mod h1:vjM1U85ZQuTv8lJoUBSA44HLWvM6BBFeaSJYGFF1Q00= github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0 h1:JZg6HRh6W6U4OLl6lk7BZ7BLisIzM9dG1R50zUk9C/M= github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0/go.mod h1:YL1xnZ6QejvQHWJrX/AvhFl4WW4rqHVoKspWNVwFk0M= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0 h1:5H6YRLGMoC8z5aXpxqcD6FfswI8mwoVNHSecvIoazt4= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0/go.mod h1:Sk63W6X/TElfcE2BknMYg0Q9JuCpebgjnHcbs5md4NM= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0 h1:B/dfvscEQtew9dVuoxqxrUKKv8Ih2f55PydknDamU+g= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0/go.mod h1:fiPSssYvltE08HJchL04dOy+RD4hgrjph0cwGGMntdI= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0 h1:CU4+EJeJi3TKYWEcYuSdWsjzw0nVsK/H0MSQOiPcymU= github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 h1:ywEEhmNahHBihViHepv3xPBn1663uRv2t2q/ESv9seY= github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0/go.mod h1:iZDifYGJTIgIIkYRNWPENUnqx6bJ2xnSDFI2tjwZNuY= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0 h1:Terj1CMW4+NY5CpWjSRkqLoxh2DkYDdv/FH2z0897Uc= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0/go.mod h1:7Ut2Qw9vcwpLW5Q4MBy43uSxXS7tK2yjs94OJ6j5thE= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.6.0 h1:PiSrjRPpkQNjrM8H0WwKMnZUdu1RGMtd/LdGKUrOo+c= github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.6.0/go.mod h1:oDrbWx4ewMylP7xHivfgixbfGBT6APAwsSoHRKotnIc= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1 h1:/Zt+cDPnpC3OVDm/JKLOs7M2DKmLRIIp3XIx9pHHiig= github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.5.0 h1:mlmW46Q0B79I+Aj4azKC6xDMFN9a9SyZWESlGWYXbFs= github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.5.0/go.mod h1:PXe2h+LKcWTX9afWdZoHyODqR4fBa5boUM/8uJfZ0Jo= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.3 h1:zoPQ7KXGgzqeUmNWl+b6IwVAqsb5lROEJhqAmqXQtm0= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.3/go.mod h1:ei/sDx/dwDIUtZE3PQP1u8+qrA+CRy4q7qW+A2MbgB4= +github.com/Azure/azure-sdk-for-go/sdk/storage/internal v0.1.0 h1:X/bTwe0qpvmvPPutc+LWo7T4cKMqDP9JHP4k+Co9ZB4= +github.com/Azure/azure-sdk-for-go/sdk/storage/internal v0.1.0/go.mod h1:+kX7ahyFelQ42F3RScM2CFgHJljp0phc/FieKLYVpFI= github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 h1:XHOnouVk1mxXfQidrMEnLlPk9UMeRtyBTnEFtxkV0kU= github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +github.com/AzureAD/microsoft-authentication-library-for-go v1.8.0 h1:Nljr4q1GRA/5vCrMONS+g4u4LRHNgOXVSh3O43J2CnI= +github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c h1:pxW6RcqyfI9/kWtOwnv/G+AzdKuy2ZrqINhenH4HyNs= +github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dimchansky/utfbom v1.1.1 h1:vV6w1AhK4VMnhBno/TPVCoK9U/LP0PkLCS9tbxHdi/U= github.com/dimchansky/utfbom v1.1.1/go.mod h1:SxdoEBH5qIqFocHMyGOXVAybYJdr71b1Q/j0mACtrfE= +github.com/dimchansky/utfbom v1.2.0 h1:ikiGYT9Wa8zleQ0xrlAWC9Ar9LNInSWRodJ5MkHB3d4= +github.com/dimchansky/utfbom v1.2.0/go.mod h1:kJPs9PFVyF/LnFVVGz+XXvouv0KxympBxr0pSwv0KQU= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/gammazero/chanqueue v1.1.2 h1:dZEsxlyANZMyeTRemABqZF8QM9BnE4NBI43Oh3y5fIU= github.com/gammazero/chanqueue v1.1.2/go.mod h1:XDN1X/jjAbmSceNFOQbtKToeSkxtdVdpKu90LiEdBEE= github.com/gammazero/deque v1.2.1 h1:9fnQVFCCZ9/NOc7ccTNqzoKd1tCWOqeI05/lPqFPMGQ= github.com/gammazero/deque v1.2.1/go.mod h1:5nSFkzVm+afG9+gy0VIowlqVAW4N8zNcMne+CMQVD2g= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8= github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786 h1:rcv+Ippz6RAtvaGgKxc+8FQIpxHgsF+HBzPyYL2cyVU= +github.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786/go.mod h1:apVn/GCasLZUVpAJ6oWAuyP7Ne7CEsQbTnc0plM3m+o= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/renameio v0.1.0 h1:GOZbcHa3HfsPKPlmyPyN2KEohoMXOhdMbHrvbpl2QaA= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gopherjs/gopherjs v1.17.2 h1:fQnZVsXk8uxXIStYb0N4bGk7jeyTalG/wsZjQ25dO0g= @@ -35,28 +70,42 @@ github.com/ipfs/bbloom v0.1.0 h1:nIWwfIE3AaG7RCDQIsrUonGCOTp7qSXzxH7ab/ss964= github.com/ipfs/bbloom v0.1.0/go.mod h1:lDy3A3i6ndgEW2z1CaRFvDi5/ZTzgM1IxA/pkL7Wgts= github.com/ipfs/boxo v0.39.0 h1:u9jLf5pLx5SWROXjHtj8VMvv+iDlMbiTyZ/vVTQ4VhI= github.com/ipfs/boxo v0.39.0/go.mod h1:k9YCvMjytFguMHndEiGdCGMMj4b7CkdOT44vtgAxOdk= +github.com/ipfs/boxo v0.43.0 h1:nhIbfBBxgLoAxUi8upOIO5RATy++2WigMVWniRJFjnw= +github.com/ipfs/boxo v0.43.0/go.mod h1:n9HNLPLfAGexg2DGoQ5B4BMVlmj9g4+5dIcuo7w95iI= github.com/ipfs/go-bitfield v1.1.0 h1:fh7FIo8bSwaJEh6DdTWbCeZ1eqOaOkKFI74SCnsWbGA= github.com/ipfs/go-bitfield v1.1.0/go.mod h1:paqf1wjq/D2BBmzfTVFlJQ9IlFOZpg422HL0HqsGWHU= github.com/ipfs/go-block-format v0.2.3 h1:mpCuDaNXJ4wrBJLrtEaGFGXkferrw5eqVvzaHhtFKQk= github.com/ipfs/go-block-format v0.2.3/go.mod h1:WJaQmPAKhD3LspLixqlqNFxiZ3BZ3xgqxxoSR/76pnA= +github.com/ipfs/go-block-format v0.2.4 h1:pgsT9i8zB4YQkBIQRrBwqbQiXPogRCiQnfxd2bC4koI= +github.com/ipfs/go-block-format v0.2.4/go.mod h1:YpXrOge8ARskfuJuqjvJTYr4v6o9IZWgK2EEIMAhpcU= github.com/ipfs/go-cid v0.6.1 h1:T5TnNb08+ueovG76Z5gx1L4Y7QOaGTXHg1F6raWFxIc= github.com/ipfs/go-cid v0.6.1/go.mod h1:zrY0SwOhjrrIdfPQ/kf+k1sXyJ0QE7cMxfCployLBs0= +github.com/ipfs/go-cid v0.6.2 h1:VuGwJd+KJTaMJ4S4d5EEf9SXc17YUblS5axCbocn9YE= +github.com/ipfs/go-cid v0.6.2/go.mod h1:Xhwg8NzHeK9xPCEZkCw4idzPiuNMpX3fARuI5Iwj1Lo= github.com/ipfs/go-cidutil v0.1.1 h1:COuby6H8C2ml0alvHYX3WdbFM4F07YtbY0UlT5j+sgI= github.com/ipfs/go-cidutil v0.1.1/go.mod h1:SCoUftGEUgoXe5Hjeyw5CiLZF8cwYn/TbtpFQXJCP6k= +github.com/ipfs/go-cidutil v0.1.2 h1:Sbktesx5tEFtyj4iqFe3asn35WR5Wokt8nHp6Eq/5HM= github.com/ipfs/go-datastore v0.9.1 h1:67Po2epre/o0UxrmkzdS9ZTe2GFGODgTd2odx8Wh6Yo= github.com/ipfs/go-datastore v0.9.1/go.mod h1:zi07Nvrpq1bQwSkEnx3bfjz+SQZbdbWyCNvyxMh9pN0= +github.com/ipfs/go-datastore v0.9.2 h1:HJOgAmvWPRMHiwD8JHBzGZQNTKhuFGYfp8bNPwye28g= github.com/ipfs/go-dsqueue v0.2.0 h1:MBi9w3oSiX98Xc+Y7NuJ9G8MI6mAT4IGdO9dHEMCZzU= github.com/ipfs/go-dsqueue v0.2.0/go.mod h1:8FfNQC4DMF/KkzBXRNB9Rb3MKDW0Sh98HMtXYl1mLQE= github.com/ipfs/go-ipld-cbor v0.2.1 h1:H05yEJbK/hxg0uf2AJhyerBDbjOuHX4yi+1U/ogRa7E= github.com/ipfs/go-ipld-cbor v0.2.1/go.mod h1:x9Zbeq8CoE5R2WicYgBMcr/9mnkQ0lHddYWJP2sMV3A= +github.com/ipfs/go-ipld-cbor v0.3.0 h1:oYksX360/YPa+XfC7eciqDSLyLLrJ9MdiWiSFOE7NS8= +github.com/ipfs/go-ipld-cbor v0.3.0/go.mod h1:wQZ/Rz7ZsxboluciiI0i8OcVYEl8cawN3wmK5EQJPIA= github.com/ipfs/go-ipld-format v0.6.3 h1:9/lurLDTotJpZSuL++gh3sTdmcFhVkCwsgx2+rAh4j8= github.com/ipfs/go-ipld-format v0.6.3/go.mod h1:74ilVN12NXVMIV+SrBAyC05UJRk0jVvGqdmrcYZvCBk= +github.com/ipfs/go-ipld-format v0.6.4 h1:NikmzItTDyQO0WkJI3rC2TGv4OFKOqM/DvcOCZZXuwM= +github.com/ipfs/go-ipld-format v0.6.4/go.mod h1:1WGiDa1Nv8dXNQBknGQYe+9OF8IoNrErvN76BYvlaIA= github.com/ipfs/go-log/v2 v2.9.1 h1:3JXwHWU31dsCpvQ+7asz6/QsFJHqFr4gLgQ0FWteujk= github.com/ipfs/go-log/v2 v2.9.1/go.mod h1:evFx7sBiohUN3AG12mXlZBw5hacBQld3ZPHrowlJYoo= +github.com/ipfs/go-log/v2 v2.9.2 h1:O/5BB0elpkRILvT24rCJ5976wWd7u0nJ436T3rdYdc4= github.com/ipfs/go-metrics-interface v0.3.0 h1:YwG7/Cy4R94mYDUuwsBfeziJCVm9pBMJ6q/JR9V40TU= github.com/ipfs/go-metrics-interface v0.3.0/go.mod h1:OxxQjZDGocXVdyTPocns6cOLwHieqej/jos7H4POwoY= github.com/ipfs/go-unixfsnode v1.10.4 h1:cMmMyOrSjQkPVQbQvt8trErIn6jhayNf9pBA9oOwfxY= github.com/ipfs/go-unixfsnode v1.10.4/go.mod h1:Vu1e/s7ToALBBRo38sJ8DwUVWmSeQMTdxk5/rcHl7d0= +github.com/ipfs/go-unixfsnode v1.10.6 h1:0rnKD4azJad4cT8t6wITqNl9Q0GTjB+YRBfMQ39C7Sw= github.com/ipld/go-car/v2 v2.17.0 h1:zgjSxf/lQNYcQPX08cvb5rSdEY8sv5OOnQIsZhZMPx4= github.com/ipld/go-car/v2 v2.17.0/go.mod h1:/4HY8tFZ1q42Mw54ILLPQfjkUqMJxFKqY1yMDKHlYko= github.com/ipld/go-codec-dagpb v1.7.0 h1:hpuvQjCSVSLnTnHXn+QAMR0mLmb1gA6wl10LExo2Ts0= @@ -67,8 +116,14 @@ github.com/ipld/go-ipld-prime/storage/bsadapter v0.0.0-20250821084354-a425e60cd7 github.com/ipld/go-ipld-prime/storage/bsadapter v0.0.0-20250821084354-a425e60cd714/go.mod h1:ZEUdra3CoqRVRYgAX/jAJO9aZGz6SKtKEG628fHHktY= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/klauspost/compress v1.20.2 h1:v5tiZvm1KGLyg5d5oXdXe3lsSPrbEUiKoXGia//I7Qo= +github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI= +github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ= +github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -79,6 +134,7 @@ github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6 github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4= github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM= github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8= github.com/mr-tron/base58 v1.3.0 h1:K6Y13R2h+dku0wOqKtecgRnBUBPrZzLZy5aIj8lCcJI= @@ -115,8 +171,11 @@ github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0b github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/tonistiigi/go-actions-cache v0.0.0-20260120203934-54bc28c26fd2 h1:5p6hffZeB25G4rhBc3HU6x1aIlyDELfib+/Omq+ZfQA= github.com/tonistiigi/go-actions-cache v0.0.0-20260120203934-54bc28c26fd2/go.mod h1:cD0SB2270BYw6HYKriFn4H6NRLhGj6ytf48YTpsm8LY= +github.com/tonistiigi/go-actions-cache v0.0.0-20260930145529-afe8013b5ac4 h1:RkHGDzvazJu1TzNvesQpnN5RwNxvU3e7O2UdJqjaj2Q= +github.com/tonistiigi/go-actions-cache v0.0.0-20260930145529-afe8013b5ac4/go.mod h1:PhGlvWoWwfUaY1K5xm8HHjcinBw/rD9FLQTPTxHbxyw= github.com/warpfork/go-testmark v0.12.1 h1:rMgCpJfwy1sJ50x0M0NgyphxYYPMOODIJHhsXyEHU0s= github.com/warpfork/go-testmark v0.12.1/go.mod h1:kHwy7wfvGSPh1rQJYKayD4AbtNaeyZdcGi9tNJTaa5Y= github.com/whyrusleeping/cbor v0.0.0-20171005072247-63513f603b11 h1:5HZfQkwe0mIfyDmc1Em5GqlNRzcdtlv4HTNmdpt7XH0= @@ -125,29 +184,91 @@ github.com/whyrusleeping/cbor-gen v0.3.1 h1:82ioxmhEYut7LBVGhGq8xoRkXPLElVuh5mV6 github.com/whyrusleeping/cbor-gen v0.3.1/go.mod h1:pM99HXyEbSQHcosHc0iW7YFmwnscr+t9Te4ibko05so= github.com/whyrusleeping/chunker v0.0.0-20181014151217-fe64bd25879f h1:jQa4QT2UP9WYv2nzyawpKMOCl+Z/jW7djv2/J50lj9E= github.com/whyrusleeping/chunker v0.0.0-20181014151217-fe64bd25879f/go.mod h1:p9UJB6dDgdPgMJZs7UjUOdulKyRr9fqkS+6JKAInPy8= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= +go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= +go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58= +go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0= +go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I= +go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= +go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= +go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o= +go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= +go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= -golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI= -golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8= +go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJkhzJCK5J6kUi1NTVXfM= golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80= -golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= -golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= -golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= -golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= -golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= -golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= -golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus= -golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM= +golang.org/x/exp v0.0.0-20261113113407-e3970619a1a4 h1:lfvjMWyv5q5oJgIhGfBDf7Szvu8POtgSpMy2XbXlEFs= +golang.org/x/exp v0.0.0-20261113113407-e3970619a1a4/go.mod h1:J3U+E8RzytcGvwz+uJuAP4zULJ2TkAQBnmPZMexpdXs= +golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678 h1:1P7xPZEwZMoBoz0Yze5Nx2/4pxj6nw9ZqHWXqP0iRgQ= +golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= +golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw= +golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/telemetry v0.0.0-20261010193011-f71dc92da45e h1:P6NGsugec4oASJ+yKMNgTndeo0h2CbixZLvQIe9h5R4= +golang.org/x/telemetry v0.0.0-20261010193011-f71dc92da45e/go.mod h1:GNu+nb+E5axfGmP+Uu3ZVQu5lE/Xk42MjZOHWUD94/o= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= +golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a h1:Yqozs0FNPRoPGS4hNGlrNwRENWr5H5nVG9sN/f+5640= +golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= +golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM= +golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY= +golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM= +golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8= +golang.org/x/vuln v1.9.0 h1:12VaqnI9kJfqwRoPptxoqsUhQtdfrSbdksT7X/KY/sc= +golang.org/x/vuln v1.9.0/go.mod h1:E/Frwm0xp49fTyBW+6CQHdkvobknbwUM49yEpMGUauw= golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY= golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= -google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= -google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/genproto/googleapis/api v0.0.0-20260706201446-f0a921348800 h1:admdQBe8jR3VWhBsUrAOaF2Qw6K/+p5pSm1GN8+6Fw4= +google.golang.org/genproto/googleapis/api v0.0.0-20260706201446-f0a921348800/go.mod h1:FPk7EXUKMtImne7AmknoYjT4QXqKIzzRbeQIXzLk6fQ= +google.golang.org/genproto/googleapis/api v0.0.0-20261110000943-09e21b237f2c h1:ofk4SEqvpf6M5VWh88xRp42IYgdVOh7gffebnDj3OqU= +google.golang.org/genproto/googleapis/api v0.0.0-20261110000943-09e21b237f2c/go.mod h1:OzYcNQzaMRKcOFRMtyLzG/cfW1SmS2eh+7UmOLLFblk= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 h1:qEHAMpSaUhtD0p3NbEEI83HwNGFxEwaSJ1G9PLnCBZE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c h1:XXChExL+Tm7Ubp0x0VXUEncPLHrkXIgoVWqnxmKNbAA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= +google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= +google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= +google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.8.2 h1:+jPbCzuYxYrcoOvCecYUFDj+XJQRmzIhJmlbpps21Zk= +honnef.co/go/tools v0.8.2/go.mod h1:xG1Q4n+mg3bKZrO6RWFA9jFlkqplflmDRHGeuexiLDs= lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg= lukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo= diff --git a/internal/artifact/artifact.go b/internal/artifact/artifact.go new file mode 100644 index 0000000..02ad4e4 --- /dev/null +++ b/internal/artifact/artifact.go @@ -0,0 +1,212 @@ +package artifact + +import ( + "archive/zip" + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "strings" + "time" +) + +// Uploader publishes one workflow artifact through the runner's results +// service. That API is not publicly documented, but it is the same one +// @actions/artifact and actions/upload-artifact speak, so its wire format +// cannot move without breaking GitHub's own tooling. +type Uploader struct { + baseURL string + token string + runID string + jobID string + client *http.Client +} + +const servicePrefix = "twirp/github.actions.results.api.v1.ArtifactService/" + +// resultsScope is the token scope carrying the identifiers an upload has to +// name, in the form Actions.Results::. +const resultsScope = "Actions.Results:" + +// New builds an uploader from the runner environment, or reports that the +// environment cannot publish artifacts. +func New(timeout time.Duration) (*Uploader, error) { + baseURL := os.Getenv("ACTIONS_RESULTS_URL") + token := os.Getenv("ACTIONS_RUNTIME_TOKEN") + if baseURL == "" || token == "" { + return nil, errors.New("the runner artifact service is unavailable in this step") + } + runID, jobID, err := backendIDs(token) + if err != nil { + return nil, err + } + return &Uploader{ + baseURL: strings.TrimRight(baseURL, "/") + "/", + token: token, + runID: runID, + jobID: jobID, + client: &http.Client{Timeout: timeout}, + }, nil +} + +// backendIDs reads the run and job identifiers out of the runtime token. The +// token is only decoded, never verified: it is this process's own credential +// and the service checks it. +func backendIDs(token string) (string, string, error) { + segments := strings.Split(token, ".") + if len(segments) != 3 { + return "", "", errors.New("the runtime token is not a JWT") + } + payload, err := base64.RawURLEncoding.DecodeString(segments[1]) + if err != nil { + return "", "", errors.New("the runtime token payload is not base64url") + } + var claims struct { + Scope string `json:"scp"` + } + if err := json.Unmarshal(payload, &claims); err != nil { + return "", "", errors.New("the runtime token payload is not JSON") + } + for _, scope := range strings.Fields(claims.Scope) { + if !strings.HasPrefix(scope, resultsScope) { + continue + } + parts := strings.Split(strings.TrimPrefix(scope, resultsScope), ":") + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + break + } + return parts[0], parts[1], nil + } + return "", "", errors.New("the runtime token carries no artifact scope") +} + +// Upload publishes content as a single-file artifact. Artifact names must be +// unique within a job. +func (u *Uploader) Upload(ctx context.Context, name, fileName string, content []byte) error { + archive, err := zipOne(fileName, content) + if err != nil { + return err + } + uploadURL, err := u.createArtifact(ctx, name) + if err != nil { + return err + } + if err := u.putBlock(ctx, uploadURL, archive); err != nil { + return err + } + return u.finalizeArtifact(ctx, name, archive) +} + +func zipOne(fileName string, content []byte) ([]byte, error) { + var buffer bytes.Buffer + archive := zip.NewWriter(&buffer) + entry, err := archive.Create(fileName) + if err != nil { + return nil, fmt.Errorf("create artifact entry: %w", err) + } + if _, err := entry.Write(content); err != nil { + return nil, fmt.Errorf("write artifact entry: %w", err) + } + if err := archive.Close(); err != nil { + return nil, fmt.Errorf("close artifact archive: %w", err) + } + return buffer.Bytes(), nil +} + +func (u *Uploader) createArtifact(ctx context.Context, name string) (string, error) { + var response struct { + OK bool `json:"ok"` + SignedUploadURL string `json:"signed_upload_url"` + } + request := map[string]any{ + "workflow_run_backend_id": u.runID, + "workflow_job_run_backend_id": u.jobID, + "name": name, + "version": 4, + } + if err := u.call(ctx, "CreateArtifact", request, &response); err != nil { + return "", err + } + if !response.OK || response.SignedUploadURL == "" { + return "", errors.New("the artifact service declined to create the artifact") + } + return response.SignedUploadURL, nil +} + +func (u *Uploader) finalizeArtifact(ctx context.Context, name string, archive []byte) error { + sum := sha256.Sum256(archive) + request := map[string]any{ + "workflow_run_backend_id": u.runID, + "workflow_job_run_backend_id": u.jobID, + "name": name, + "size": len(archive), + "hash": "sha256:" + hex.EncodeToString(sum[:]), + } + var response struct { + OK bool `json:"ok"` + } + if err := u.call(ctx, "FinalizeArtifact", request, &response); err != nil { + return err + } + if !response.OK { + return errors.New("the artifact service declined to finalize the artifact") + } + return nil +} + +func (u *Uploader) call(ctx context.Context, method string, body, out any) error { + encoded, err := json.Marshal(body) + if err != nil { + return err + } + request, err := http.NewRequestWithContext( + ctx, + http.MethodPost, + u.baseURL+servicePrefix+method, + bytes.NewReader(encoded), + ) + if err != nil { + return err + } + request.Header.Set("Content-Type", "application/json") + request.Header.Set("Authorization", "Bearer "+u.token) + response, err := u.client.Do(request) + if err != nil { + return fmt.Errorf("%s failed", method) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return fmt.Errorf("%s returned HTTP %d", method, response.StatusCode) + } + return json.NewDecoder(response.Body).Decode(out) +} + +func (u *Uploader) putBlock(ctx context.Context, uploadURL string, archive []byte) error { + request, err := http.NewRequestWithContext( + ctx, + http.MethodPut, + uploadURL, + bytes.NewReader(archive), + ) + if err != nil { + return err + } + request.Header.Set("x-ms-blob-type", "BlockBlob") + request.Header.Set("Content-Type", "application/zip") + request.ContentLength = int64(len(archive)) + response, err := u.client.Do(request) + if err != nil { + return errors.New("uploading the artifact failed") + } + defer response.Body.Close() + if response.StatusCode != http.StatusCreated && response.StatusCode != http.StatusOK { + return fmt.Errorf("uploading the artifact returned HTTP %d", response.StatusCode) + } + return nil +} diff --git a/internal/artifact/artifact_test.go b/internal/artifact/artifact_test.go new file mode 100644 index 0000000..906ff89 --- /dev/null +++ b/internal/artifact/artifact_test.go @@ -0,0 +1,166 @@ +package artifact + +import ( + "archive/zip" + "bytes" + "context" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func testToken(t *testing.T, scope string) string { + t.Helper() + payload, err := json.Marshal(map[string]string{"scp": scope}) + if err != nil { + t.Fatal(err) + } + return "header." + base64.RawURLEncoding.EncodeToString(payload) + ".signature" +} + +func TestBackendIDsComeFromTheRuntimeToken(t *testing.T) { + token := testToken(t, "Actions.Something:x Actions.Results:run-42:job-7") + runID, jobID, err := backendIDs(token) + if err != nil { + t.Fatal(err) + } + if runID != "run-42" || jobID != "job-7" { + t.Fatalf("ids = %q/%q", runID, jobID) + } + + for _, invalid := range []string{ + "not-a-jwt", + "header.!!!.signature", + testToken(t, "Actions.Results:onlyone"), + testToken(t, "Actions.Other:run:job"), + } { + if _, _, err := backendIDs(invalid); err == nil { + t.Fatalf("accepted %q", invalid) + } + } +} + +func TestUploadCreatesPutsAndFinalizes(t *testing.T) { + var calls []string + var uploaded []byte + var finalize map[string]any + + blobs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls = append(calls, "put") + if got := r.Header.Get("x-ms-blob-type"); got != "BlockBlob" { + t.Errorf("blob type = %q", got) + } + body, _ := io.ReadAll(r.Body) + uploaded = body + w.WriteHeader(http.StatusCreated) + })) + defer blobs.Close() + + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + method := strings.TrimPrefix(r.URL.Path, "/"+servicePrefix) + calls = append(calls, method) + if got := r.Header.Get("Authorization"); !strings.HasPrefix(got, "Bearer ") { + t.Errorf("authorization = %q", got) + } + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + if body["workflow_run_backend_id"] != "run-42" || body["workflow_job_run_backend_id"] != "job-7" { + t.Errorf("backend ids = %v", body) + } + switch method { + case "CreateArtifact": + _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "signed_upload_url": blobs.URL + "/blob"}) + case "FinalizeArtifact": + finalize = body + _ = json.NewEncoder(w).Encode(map[string]any{"ok": true}) + default: + t.Errorf("unexpected method %q", method) + } + })) + defer service.Close() + + uploader := &Uploader{ + baseURL: service.URL + "/", + token: testToken(t, "Actions.Results:run-42:job-7"), + runID: "run-42", + jobID: "job-7", + client: &http.Client{Timeout: 5 * time.Second}, + } + content := []byte(`{"entries":[]}`) + if err := uploader.Upload(context.Background(), "cache-usage", "usage.json", content); err != nil { + t.Fatal(err) + } + + // Ordering matters: the blob has to exist before it is finalized. + want := []string{"CreateArtifact", "put", "FinalizeArtifact"} + if strings.Join(calls, ",") != strings.Join(want, ",") { + t.Fatalf("calls = %v, want %v", calls, want) + } + if finalize["size"].(float64) != float64(len(uploaded)) { + t.Fatalf("finalized size %v against %d uploaded bytes", finalize["size"], len(uploaded)) + } + if hash, _ := finalize["hash"].(string); !strings.HasPrefix(hash, "sha256:") { + t.Fatalf("hash = %q", hash) + } + + archive, err := zip.NewReader(bytes.NewReader(uploaded), int64(len(uploaded))) + if err != nil { + t.Fatal(err) + } + if len(archive.File) != 1 || archive.File[0].Name != "usage.json" { + t.Fatalf("archive = %+v", archive.File) + } + entry, err := archive.File[0].Open() + if err != nil { + t.Fatal(err) + } + defer entry.Close() + stored, _ := io.ReadAll(entry) + if string(stored) != string(content) { + t.Fatalf("stored = %q", stored) + } +} + +func TestUploadReportsServiceRefusal(t *testing.T) { + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{"ok": false}) + })) + defer service.Close() + + uploader := &Uploader{ + baseURL: service.URL + "/", + token: testToken(t, "Actions.Results:run:job"), + runID: "run", + jobID: "job", + client: &http.Client{Timeout: 5 * time.Second}, + } + err := uploader.Upload(context.Background(), "cache-usage", "usage.json", []byte("{}")) + if err == nil || !strings.Contains(err.Error(), "declined") { + t.Fatalf("error = %v", err) + } +} + +func TestNewRequiresTheRunnerEnvironment(t *testing.T) { + t.Setenv("ACTIONS_RESULTS_URL", "") + t.Setenv("ACTIONS_RUNTIME_TOKEN", "") + if _, err := New(time.Second); err == nil { + t.Fatal("accepted an environment with no artifact service") + } + + t.Setenv("ACTIONS_RESULTS_URL", "https://results.example.invalid/") + t.Setenv("ACTIONS_RUNTIME_TOKEN", testToken(t, "Actions.Results:run:job")) + uploader, err := New(time.Second) + if err != nil { + t.Fatal(err) + } + if uploader.baseURL != "https://results.example.invalid/" { + t.Fatalf("base url = %q", uploader.baseURL) + } +} diff --git a/internal/cache/backend.go b/internal/cache/backend.go index 05cbb02..afc7643 100644 --- a/internal/cache/backend.go +++ b/internal/cache/backend.go @@ -57,17 +57,24 @@ func NewActionsBackend(timeout time.Duration) (*ActionsBackend, error) { } func (b *ActionsBackend) Load(ctx context.Context, key string, dst io.Writer) (bool, error) { - entry, err := b.cache.Load(ctx, key) + matched, err := b.Restore(ctx, []string{key}, dst) + return matched != "", err +} + +// Restore asks the runner cache service to use the first exact or prefix match +// in keys and writes that entry to dst. +func (b *ActionsBackend) Restore(ctx context.Context, keys []string, dst io.Writer) (string, error) { + entry, err := b.cache.Load(ctx, keys...) if err != nil { - return false, fmt.Errorf("load cache entry: %w", err) + return "", fmt.Errorf("load cache entry: %w", err) } if entry == nil { - return false, nil + return "", nil } if err := entry.WriteTo(ctx, dst); err != nil { - return false, fmt.Errorf("download cache entry: %w", err) + return "", fmt.Errorf("download cache entry: %w", err) } - return true, nil + return entry.Key, nil } func (b *ActionsBackend) Exists(ctx context.Context, key string) (bool, error) { diff --git a/internal/cache/catalog.go b/internal/cache/catalog.go index 2cb711f..86a0500 100644 --- a/internal/cache/catalog.go +++ b/internal/cache/catalog.go @@ -5,19 +5,22 @@ import ( "encoding/json" "errors" "fmt" + "log" "net/http" "net/url" "os" - "strconv" + "regexp" "strings" "time" ) // Catalog lists immutable GitHub Actions cache keys. The packed backend uses -// it solely to discover manifest heads; cache bytes are still restored through -// the runner cache-v2 service. +// it to discover manifest heads and to learn which packs still exist; cache +// bytes are still restored through the runner cache-v2 service. Listing reads +// metadata only, so it does not extend an entry's lifetime. type Catalog interface { - List(ctx context.Context, keyPrefix string, limit int) ([]string, error) + // List returns every cache key starting with keyPrefix, newest first. + List(ctx context.Context, keyPrefix string) ([]string, error) } // ActionsCatalog lists cache metadata through the public GitHub REST API. @@ -27,12 +30,37 @@ type ActionsCatalog struct { baseURL *url.URL repository string token string - client *http.Client + // ref restricts listings to one Git reference. Empty lists every reference, + // which is what a cache server needs: a job restores its own branch's + // entries and the default branch's. + ref string + client *http.Client + logger *log.Logger +} + +// refPattern admits the full references GitHub documents for this parameter. +var refPattern = regexp.MustCompile(`^refs/[A-Za-z0-9._/-]{1,200}$`) + +// validRef applies the parts of git's own refname rules that keep a reference +// from naming something other than itself. +func validRef(ref string) bool { + return refPattern.MatchString(ref) && + !strings.Contains(ref, "..") && + !strings.Contains(ref, "//") && + !strings.HasSuffix(ref, "/") && + !strings.HasSuffix(ref, ".lock") } // NewActionsCatalog creates a manifest-discovery client from GitHub Actions // runner environment variables. -func NewActionsCatalog(timeout time.Duration) (*ActionsCatalog, error) { +func NewActionsCatalog(timeout time.Duration, logger *log.Logger) (*ActionsCatalog, error) { + return NewScopedActionsCatalog(timeout, logger, "") +} + +// NewScopedActionsCatalog restricts every listing to one Git reference, so that +// entries another reference owns never appear. A caller that deletes wants this: +// it can restore exactly what it lists. +func NewScopedActionsCatalog(timeout time.Duration, logger *log.Logger, ref string) (*ActionsCatalog, error) { repository := os.Getenv("GITHUB_REPOSITORY") if len(strings.Split(repository, "/")) != 2 || strings.HasPrefix(repository, "/") || strings.HasSuffix(repository, "/") { return nil, errors.New("GITHUB_REPOSITORY must be owner/repository for packed-cache manifest discovery") @@ -49,39 +77,72 @@ func NewActionsCatalog(timeout time.Duration) (*ActionsCatalog, error) { if err != nil || baseURL.Scheme == "" || baseURL.Host == "" { return nil, fmt.Errorf("invalid GITHUB_API_URL: %w", err) } + if ref != "" && !validRef(ref) { + return nil, fmt.Errorf("a cache scope must be a full Git reference such as refs/heads/main, got %q", ref) + } return &ActionsCatalog{ baseURL: baseURL, repository: repository, token: token, + ref: ref, client: &http.Client{Timeout: timeout}, + logger: logger, }, nil } type actionsCacheListResponse struct { ActionsCaches []struct { - Key string `json:"key"` + Key string `json:"key"` + CreatedAt time.Time `json:"created_at"` } `json:"actions_caches"` } -// List returns at most limit cache keys whose immutable key starts with -// keyPrefix. GitHub's API pagination is followed explicitly so a later writer -// does not silently hide older DAG parents. -func (c *ActionsCatalog) List(ctx context.Context, keyPrefix string, limit int) ([]string, error) { - if limit <= 0 { - return nil, errors.New("catalog list limit must be positive") +// CatalogEntry is a listed cache entry with the metadata a deletion decision +// needs. Age is the only thing distinguishing a pack whose manifest was lost +// from one a running job has not committed a manifest for yet. +type CatalogEntry struct { + Key string + CreatedAt time.Time +} + +// List returns every cache key whose immutable key starts with keyPrefix, +// newest first. +func (c *ActionsCatalog) List(ctx context.Context, keyPrefix string) ([]string, error) { + entries, err := c.ListEntries(ctx, keyPrefix) + if err != nil { + return nil, err } - page := 1 - keys := make([]string, 0) - for { - endpoint := *c.baseURL - endpoint.Path = strings.TrimRight(endpoint.Path, "/") + "/repos/" + c.repository + "/actions/caches" - query := endpoint.Query() - query.Set("key", keyPrefix) - query.Set("per_page", "100") - query.Set("page", strconv.Itoa(page)) - endpoint.RawQuery = query.Encode() + keys := make([]string, 0, len(entries)) + for _, entry := range entries { + keys = append(keys, entry.Key) + } + return keys, nil +} + +// List returns every cache key whose immutable key starts with keyPrefix, +// newest first. Pagination follows the Link header rather than page sizes, so +// a short page cannot end the listing early and silently hide older DAG +// parents. +func (c *ActionsCatalog) ListEntries(ctx context.Context, keyPrefix string) ([]CatalogEntry, error) { + endpoint := *c.baseURL + endpoint.Path = strings.TrimRight(endpoint.Path, "/") + "/repos/" + c.repository + "/actions/caches" + query := endpoint.Query() + query.Set("key", keyPrefix) + // Newest first, so a caller that reads only part of the listing keeps the + // most recent entries rather than an arbitrary subset. + query.Set("sort", "created_at") + query.Set("direction", "desc") + query.Set("per_page", "100") + if c.ref != "" { + query.Set("ref", c.ref) + } + endpoint.RawQuery = query.Encode() - request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil) + next := endpoint.String() + keys := make([]CatalogEntry, 0) + unexpected := 0 + for next != "" { + request, err := http.NewRequestWithContext(ctx, http.MethodGet, next, nil) if err != nil { return nil, fmt.Errorf("create cache catalog request: %w", err) } @@ -94,6 +155,7 @@ func (c *ActionsCatalog) List(ctx context.Context, keyPrefix string, limit int) } var result actionsCacheListResponse decodeErr := json.NewDecoder(response.Body).Decode(&result) + link := response.Header.Get("Link") _ = response.Body.Close() if response.StatusCode != http.StatusOK { return nil, fmt.Errorf("list GitHub Actions caches: HTTP %d", response.StatusCode) @@ -102,16 +164,70 @@ func (c *ActionsCatalog) List(ctx context.Context, keyPrefix string, limit int) return nil, fmt.Errorf("decode GitHub Actions cache list: %w", decodeErr) } for _, entry := range result.ActionsCaches { - if strings.HasPrefix(entry.Key, keyPrefix) { - keys = append(keys, entry.Key) - if len(keys) > limit { - return nil, fmt.Errorf("manifest catalog exceeds configured limit of %d entries", limit) + if !strings.HasPrefix(entry.Key, keyPrefix) { + // GitHub documents key as an explicit key or prefix, so a + // non-matching entry means the filter no longer behaves as this + // catalog assumes. + if unexpected == 0 { + c.logf("GitHub cache listing for prefix %q returned unrelated key %q", keyPrefix, entry.Key) } + unexpected++ + continue } + keys = append(keys, CatalogEntry{Key: entry.Key, CreatedAt: entry.CreatedAt}) } - if len(result.ActionsCaches) < 100 { - return keys, nil + if next, err = c.nextPageURL(link); err != nil { + return nil, err } - page++ } + c.reportUnexpected(keyPrefix, unexpected) + return keys, nil +} + +// nextPageURL returns the rel="next" target of a Link header, or an empty +// string on the final page. +func (c *ActionsCatalog) nextPageURL(header string) (string, error) { + for _, section := range strings.Split(header, ",") { + parts := strings.Split(strings.TrimSpace(section), ";") + if len(parts) < 2 { + continue + } + target := strings.TrimSpace(parts[0]) + if !strings.HasPrefix(target, "<") || !strings.HasSuffix(target, ">") { + continue + } + isNext := false + for _, parameter := range parts[1:] { + switch strings.TrimSpace(parameter) { + case `rel="next"`, "rel=next": + isNext = true + } + } + if !isNext { + continue + } + parsed, err := url.Parse(target[1 : len(target)-1]) + if err != nil { + return "", fmt.Errorf("parse cache listing pagination link: %w", err) + } + // Pagination must never leave the configured API host. + if parsed.Scheme != c.baseURL.Scheme || parsed.Host != c.baseURL.Host { + return "", fmt.Errorf("cache listing pagination link leaves %s", c.baseURL.Host) + } + return parsed.String(), nil + } + return "", nil +} + +func (c *ActionsCatalog) reportUnexpected(keyPrefix string, unexpected int) { + if unexpected > 1 { + c.logf("GitHub cache listing for prefix %q returned %d unrelated keys", keyPrefix, unexpected) + } +} + +func (c *ActionsCatalog) logf(format string, args ...any) { + if c.logger == nil { + return + } + c.logger.Printf(format, args...) } diff --git a/internal/cache/catalog_test.go b/internal/cache/catalog_test.go index d6715f9..7bde7dd 100644 --- a/internal/cache/catalog_test.go +++ b/internal/cache/catalog_test.go @@ -1,7 +1,9 @@ package cache import ( + "bytes" "context" + "log" "net/http" "net/http/httptest" "net/url" @@ -9,21 +11,33 @@ import ( "testing" ) -func TestActionsCatalogListsAllPagesWithinPrefix(t *testing.T) { +func TestActionsCatalogFollowsShortPagesToTheFinalLink(t *testing.T) { requests := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requests++ if got := r.Header.Get("Authorization"); got != "Bearer token" { - t.Fatalf("authorization = %q", got) + t.Errorf("authorization = %q", got) } - if got := r.URL.Query().Get("key"); got != "prefix-manifest-" { - t.Fatalf("key = %q", got) + query := r.URL.Query() + if got := query.Get("key"); got != "prefix-manifest-" { + t.Errorf("key = %q", got) } - if r.URL.Query().Get("page") == "1" { - _, _ = w.Write([]byte(`{"actions_caches":[{"key":"prefix-manifest-one"}]}`)) + if got := query.Get("sort"); got != "created_at" { + t.Errorf("sort = %q", got) + } + if got := query.Get("direction"); got != "desc" { + t.Errorf("direction = %q", got) + } + // A page far shorter than per_page must not end the listing while the + // server still advertises a next page. + if query.Get("page") != "2" { + query.Set("page", "2") + next := "http://" + r.Host + "/repos/owner/repository/actions/caches?" + query.Encode() + w.Header().Set("Link", `<`+next+`>; rel="next", <`+next+`>; rel="last"`) + _, _ = w.Write([]byte(`{"total_count":2,"actions_caches":[{"key":"prefix-manifest-one"}]}`)) return } - _, _ = w.Write([]byte(`{"actions_caches":[]}`)) + _, _ = w.Write([]byte(`{"total_count":2,"actions_caches":[{"key":"prefix-manifest-two"}]}`)) })) defer server.Close() baseURL, err := url.Parse(server.URL) @@ -31,18 +45,19 @@ func TestActionsCatalogListsAllPagesWithinPrefix(t *testing.T) { t.Fatal(err) } catalog := &ActionsCatalog{baseURL: baseURL, repository: "owner/repository", token: "token", client: server.Client()} - keys, err := catalog.List(context.Background(), "prefix-manifest-", 10) + keys, err := catalog.List(context.Background(), "prefix-manifest-") if err != nil { t.Fatal(err) } - if strings.Join(keys, ",") != "prefix-manifest-one" || requests != 1 { + if strings.Join(keys, ",") != "prefix-manifest-one,prefix-manifest-two" || requests != 2 { t.Fatalf("keys/requests = %v/%d", keys, requests) } } -func TestActionsCatalogRejectsLimitOverflow(t *testing.T) { +func TestActionsCatalogRejectsPaginationLinkToAnotherHost(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, _ = w.Write([]byte(`{"actions_caches":[{"key":"prefix-one"},{"key":"prefix-two"}]}`)) + w.Header().Set("Link", `; rel="next"`) + _, _ = w.Write([]byte(`{"total_count":1,"actions_caches":[{"key":"prefix-one"}]}`)) })) defer server.Close() baseURL, err := url.Parse(server.URL) @@ -50,7 +65,37 @@ func TestActionsCatalogRejectsLimitOverflow(t *testing.T) { t.Fatal(err) } catalog := &ActionsCatalog{baseURL: baseURL, repository: "owner/repository", token: "token", client: server.Client()} - if _, err := catalog.List(context.Background(), "prefix-", 1); err == nil { - t.Fatal("overflow was accepted") + if _, err := catalog.List(context.Background(), "prefix-"); err == nil { + t.Fatal("pagination followed a link to another host") + } +} + +func TestActionsCatalogLogsKeysOutsideTheRequestedPrefix(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{"actions_caches":[{"key":"prefix-one"},{"key":"unrelated"},{"key":"another"}]}`)) + })) + defer server.Close() + baseURL, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + var logged bytes.Buffer + catalog := &ActionsCatalog{ + baseURL: baseURL, + repository: "owner/repository", + token: "token", + client: server.Client(), + logger: log.New(&logged, "", 0), + } + keys, err := catalog.List(context.Background(), "prefix-") + if err != nil { + t.Fatal(err) + } + if strings.Join(keys, ",") != "prefix-one" { + t.Fatalf("keys = %v", keys) + } + if !strings.Contains(logged.String(), `unrelated key "unrelated"`) || + !strings.Contains(logged.String(), "returned 2 unrelated keys") { + t.Fatalf("prefix filter violation was not reported: %q", logged.String()) } } diff --git a/internal/cache/pruner.go b/internal/cache/pruner.go new file mode 100644 index 0000000..73f06d5 --- /dev/null +++ b/internal/cache/pruner.go @@ -0,0 +1,90 @@ +package cache + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "os" + "strings" + "time" +) + +// ActionsPruner deletes GitHub Actions cache entries. It is deliberately a +// separate type from ActionsCatalog: deleting needs actions: write, and the +// cache server must never be handed a client that can. +type ActionsPruner struct { + baseURL *url.URL + repository string + token string + ref string + client *http.Client +} + +// NewActionsPruner deletes only within one Git reference. Without a ref the API +// removes every reference's copy of a key, which would take entries this caller +// never listed and cannot replace. +func NewActionsPruner(timeout time.Duration, ref string) (*ActionsPruner, error) { + repository := os.Getenv("GITHUB_REPOSITORY") + if len(strings.Split(repository, "/")) != 2 || strings.HasPrefix(repository, "/") || strings.HasSuffix(repository, "/") { + return nil, errors.New("GITHUB_REPOSITORY must be owner/repository") + } + token := os.Getenv("GITHUB_TOKEN") + if token == "" { + return nil, errors.New("GITHUB_TOKEN is required to delete cache entries") + } + baseURLText := os.Getenv("GITHUB_API_URL") + if baseURLText == "" { + baseURLText = "https://api.github.com" + } + baseURL, err := url.Parse(baseURLText) + if err != nil || baseURL.Scheme == "" || baseURL.Host == "" { + return nil, fmt.Errorf("invalid GITHUB_API_URL: %w", err) + } + if ref == "" || !validRef(ref) { + return nil, fmt.Errorf("deleting needs a full Git reference such as refs/heads/main, got %q", ref) + } + return &ActionsPruner{ + baseURL: baseURL, + repository: repository, + token: token, + ref: ref, + client: &http.Client{Timeout: timeout}, + }, nil +} + +// Delete removes the cache entry with exactly this key. An entry that is +// already gone is not an error: the goal is its absence. +func (p *ActionsPruner) Delete(ctx context.Context, key string) error { + if key == "" { + return errors.New("refusing to delete without a key") + } + endpoint := *p.baseURL + endpoint.Path = strings.TrimRight(endpoint.Path, "/") + "/repos/" + p.repository + "/actions/caches" + // Both are exact matches. Without the ref the API would delete every + // reference's copy of this key. + query := url.Values{} + query.Set("key", key) + query.Set("ref", p.ref) + endpoint.RawQuery = query.Encode() + + request, err := http.NewRequestWithContext(ctx, http.MethodDelete, endpoint.String(), nil) + if err != nil { + return err + } + request.Header.Set("Accept", "application/vnd.github+json") + request.Header.Set("Authorization", "Bearer "+p.token) + request.Header.Set("X-GitHub-Api-Version", "2022-11-28") + response, err := p.client.Do(request) + if err != nil { + return errors.New("deleting the cache entry failed") + } + defer response.Body.Close() + switch response.StatusCode { + case http.StatusOK, http.StatusNoContent, http.StatusNotFound: + return nil + default: + return fmt.Errorf("deleting the cache entry returned HTTP %d", response.StatusCode) + } +} diff --git a/internal/cache/scope_test.go b/internal/cache/scope_test.go new file mode 100644 index 0000000..a5abc6c --- /dev/null +++ b/internal/cache/scope_test.go @@ -0,0 +1,123 @@ +package cache + +import ( + "context" + "log" + "net/http" + "net/http/httptest" + "net/url" + "testing" + "time" +) + +func testBaseURL(t *testing.T, raw string) *url.URL { + t.Helper() + parsed, err := url.Parse(raw) + if err != nil { + t.Fatal(err) + } + return parsed +} + +// A pass that deletes wants to see only what it can also restore, so entries +// another reference owns must not appear at all. +func TestScopedCatalogAsksForOneReference(t *testing.T) { + var scope string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + scope = r.URL.Query().Get("ref") + _, _ = w.Write([]byte(`{"actions_caches":[{"key":"prefix-one"}]}`)) + })) + defer server.Close() + + catalog := &ActionsCatalog{ + baseURL: testBaseURL(t, server.URL), + repository: "owner/repository", + token: "token", + ref: "refs/heads/main", + client: server.Client(), + logger: log.New(discard{}, "", 0), + } + if _, err := catalog.List(context.Background(), "prefix-"); err != nil { + t.Fatal(err) + } + if scope != "refs/heads/main" { + t.Fatalf("ref = %q", scope) + } +} + +// A cache server must keep listing every reference: a job restores its own +// branch's entries and the default branch's. +func TestUnscopedCatalogAsksForEveryReference(t *testing.T) { + var present bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, present = r.URL.Query()["ref"] + _, _ = w.Write([]byte(`{"actions_caches":[]}`)) + })) + defer server.Close() + + catalog := &ActionsCatalog{ + baseURL: testBaseURL(t, server.URL), + repository: "owner/repository", + token: "token", + client: server.Client(), + logger: log.New(discard{}, "", 0), + } + if _, err := catalog.List(context.Background(), "prefix-"); err != nil { + t.Fatal(err) + } + if present { + t.Fatal("an unscoped catalog narrowed the listing to one reference") + } +} + +// Without a ref the API deletes every reference's copy of a key, which would +// take entries this caller never listed and cannot replace. +func TestPrunerDeletesWithinOneReference(t *testing.T) { + var query url.Values + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodDelete { + t.Errorf("method = %s", r.Method) + } + query = r.URL.Query() + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + pruner := &ActionsPruner{ + baseURL: testBaseURL(t, server.URL), + repository: "owner/repository", + token: "token", + ref: "refs/heads/main", + client: server.Client(), + } + if err := pruner.Delete(context.Background(), "prefix-car-pack-v1-abc"); err != nil { + t.Fatal(err) + } + if got := query.Get("ref"); got != "refs/heads/main" { + t.Fatalf("ref = %q", got) + } + if got := query.Get("key"); got != "prefix-car-pack-v1-abc" { + t.Fatalf("key = %q", got) + } +} + +func TestScopeMustBeAFullReference(t *testing.T) { + t.Setenv("GITHUB_REPOSITORY", "owner/repository") + t.Setenv("GITHUB_TOKEN", "token") + for _, ref := range []string{"main", "../../etc", "refs/heads/../..", "refs/heads/", "refs//heads/x", "refs/heads/x.lock", ""} { + if _, err := NewActionsPruner(time.Second, ref); err == nil { + t.Fatalf("pruner accepted %q", ref) + } + if ref == "" { + // An unscoped catalog is legitimate; an unscoped pruner is not. + continue + } + if _, err := NewScopedActionsCatalog(time.Second, nil, ref); err == nil { + t.Fatalf("catalog accepted %q", ref) + } + } +} + +type discard struct{} + +func (discard) Write(p []byte) (int, error) { return len(p), nil } diff --git a/internal/optimiser/demand.go b/internal/optimiser/demand.go new file mode 100644 index 0000000..7183504 --- /dev/null +++ b/internal/optimiser/demand.go @@ -0,0 +1,196 @@ +package optimiser + +import ( + "sort" + "strings" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/server" +) + +// Demand is what a window of recent jobs did with each cache entry. It is the +// only thing the manifests cannot say: pack composition can be read back from +// them, but only a job knows which entries it needed. +type Demand struct { + downloads map[string]map[string]struct{} + presence map[string]uint64 + runs map[string]struct{} + + // Built lazily from the above, and dropped by Observe. + order []string + position map[string]int + sets map[string]runSet +} + +func NewDemand() *Demand { + return &Demand{ + downloads: make(map[string]map[string]struct{}), + presence: make(map[string]uint64), + runs: make(map[string]struct{}), + } +} + +func demandKey(kind, digest string) string { return kind + "/" + digest } + +// Observe folds one job's usage record into the demand. Keying downloads by run +// is what lets the planner tell entries that are wanted together from entries +// that merely happen to be popular. +func (d *Demand) Observe(runID string, report server.UsageReport) { + if runID == "" { + return + } + d.order, d.position, d.sets = nil, nil, nil + d.runs[runID] = struct{}{} + for _, entry := range report.Entries { + key := demandKey(entry.Kind, entry.Digest) + d.presence[key] += entry.PresenceChecks + if entry.Downloads == 0 { + continue + } + runs, found := d.downloads[key] + if !found { + runs = make(map[string]struct{}) + d.downloads[key] = runs + } + runs[runID] = struct{}{} + } +} + +// Runs counts the jobs that contributed a record. A plan built from too few is +// a plan built from noise. +func (d *Demand) Runs() int { return len(d.runs) } + +// minHoldoutRuns is the smallest window split into fitting and checking runs; +// below it every run does both. +const minHoldoutRuns = 4 + +// split sets aside every fourth run, so that a regrouping fitted to the rest +// can be judged on jobs it never saw. Judged on its own runs, any regrouping +// looks like an improvement, and a pass would chase each window's noise. +func (d *Demand) split() (fit, check *Demand) { + if len(d.runs) < minHoldoutRuns { + return d, d + } + ids := make([]string, 0, len(d.runs)) + for id := range d.runs { + ids = append(ids, id) + } + sort.Strings(ids) + held := make(map[string]bool, len(ids)/4) + for at, id := range ids { + if at%4 == 3 { + held[id] = true + } + } + return d.filter(func(id string) bool { return !held[id] }), d.filter(func(id string) bool { return held[id] }) +} + +func (d *Demand) filter(keep func(string) bool) *Demand { + filtered := NewDemand() + for id := range d.runs { + if keep(id) { + filtered.runs[id] = struct{}{} + } + } + for key, runs := range d.downloads { + for id := range runs { + if !keep(id) { + continue + } + if filtered.downloads[key] == nil { + filtered.downloads[key] = make(map[string]struct{}) + } + filtered.downloads[key][id] = struct{}{} + } + } + return filtered +} + +// Downloaded reports whether any observed job needed the entry's bytes. A +// presence-only entry is answered from the manifest without restoring its pack, +// so it costs a reader nothing and is not worth separating out. +func (d *Demand) Downloaded(kind, digest string) bool { + return len(d.downloads[demandKey(kind, digest)]) > 0 +} + +// index numbers the runs, busiest first, so that ordering run sets by their +// lowest bits clusters entries by the jobs that restore the most. +func (d *Demand) index() { + if d.position != nil { + return + } + busy := make(map[string]int, len(d.runs)) + for _, runs := range d.downloads { + for run := range runs { + busy[run]++ + } + } + d.order = make([]string, 0, len(d.runs)) + for run := range d.runs { + d.order = append(d.order, run) + } + sort.Slice(d.order, func(i, j int) bool { + if busy[d.order[i]] != busy[d.order[j]] { + return busy[d.order[i]] > busy[d.order[j]] + } + return d.order[i] < d.order[j] + }) + d.position = make(map[string]int, len(d.order)) + for at, run := range d.order { + d.position[run] = at + } + d.sets = make(map[string]runSet) +} + +// Used reports whether any observed job downloaded the entry or checked that it +// exists. Either keeps it: a presence check is how a job, or a reader validating +// an action result, depends on an entry it does not need the bytes of. +func (d *Demand) Used(kind, digest string) bool { + key := demandKey(kind, digest) + return len(d.downloads[key]) > 0 || d.presence[key] > 0 +} + +// runSet is the jobs that downloaded an entry, as a bitset over index order. +// The result is shared and must not be modified. +func (d *Demand) runSet(kind, digest string) runSet { + d.index() + key := demandKey(kind, digest) + if set, found := d.sets[key]; found { + return set + } + set := newRunSet(len(d.order)) + for run := range d.downloads[key] { + set.add(d.position[run]) + } + d.sets[key] = set + return set +} + +// names lists the runs in a set, sorted, in the form Signature uses. +func (d *Demand) names(set runSet) string { + d.index() + ids := make([]string, 0, set.count()) + for at, run := range d.order { + if set.has(at) { + ids = append(ids, run) + } + } + sort.Strings(ids) + return strings.Join(ids, " ") +} + +// Signature names the set of runs that downloaded an entry, and is empty when +// none did. Two entries sharing a signature were wanted by exactly the same +// jobs, so placing them in one pack costs a later job nothing it did not +// already have to fetch. +func (d *Demand) Signature(kind, digest string) string { + runs := d.downloads[demandKey(kind, digest)] + if len(runs) == 0 { + return "" + } + ids := make([]string, 0, len(runs)) + for id := range runs { + ids = append(ids, id) + } + sort.Strings(ids) + return strings.Join(ids, " ") +} diff --git a/internal/optimiser/format.go b/internal/optimiser/format.go new file mode 100644 index 0000000..1534a19 --- /dev/null +++ b/internal/optimiser/format.go @@ -0,0 +1,71 @@ +package optimiser + +import ( + "strconv" + "strings" +) + +var byteUnits = []struct { + name string + size int64 +}{ + {"TiB", 1 << 40}, + {"GiB", 1 << 30}, + {"MiB", 1 << 20}, + {"KiB", 1 << 10}, + {"B", 1}, +} + +// HumanBytes renders a size in the largest unit that fits, as "2.32GiB". +// Trailing zeros are dropped so a round number stays short. +func HumanBytes(value int64) string { + if value < 0 { + return "-" + HumanBytes(-value) + } + for _, unit := range byteUnits { + // Bytes are the floor, so anything under a kibibyte lands there. + if value < unit.size && unit.size > 1 { + continue + } + scaled := strconv.FormatFloat(float64(value)/float64(unit.size), 'f', 3, 64) + return groupInteger(trimTrailingZeros(scaled)) + unit.name + } + return "0B" +} + +func trimTrailingZeros(text string) string { + if !strings.Contains(text, ".") { + return text + } + return strings.TrimRight(strings.TrimRight(text, "0"), ".") +} + +func groupInteger(text string) string { + integer, fraction, hasFraction := strings.Cut(text, ".") + value, err := strconv.ParseInt(integer, 10, 64) + if err != nil { + return text + } + if hasFraction { + return HumanCount(value) + "." + fraction + } + return HumanCount(value) +} + +// HumanCount groups digits so a long number can be read at a glance. +func HumanCount(value int64) string { + text := strconv.FormatInt(value, 10) + sign := "" + if text[0] == '-' { + sign, text = "-", text[1:] + } + lead := len(text) % 3 + if lead == 0 { + lead = 3 + } + grouped := text[:lead] + for index := lead; index < len(text); index += 3 { + grouped += "," + text[index:index+3] + } + return sign + grouped +} diff --git a/internal/optimiser/format_test.go b/internal/optimiser/format_test.go new file mode 100644 index 0000000..b212ca4 --- /dev/null +++ b/internal/optimiser/format_test.go @@ -0,0 +1,40 @@ +package optimiser + +import "testing" + +func TestHumanBytesUsesTheLargestUnitThatFits(t *testing.T) { + cases := map[int64]string{ + 0: "0B", + 12: "12B", + 1023: "1,023B", + 1024: "1KiB", + 2491416576: "2.32GiB", + 241432494: "230.248MiB", + 1 << 40 * 3: "3TiB", + 1<<30 + 1<<29: "1.5GiB", + // Trailing zeros go, so a round size stays short. + 2 << 20: "2MiB", + -1024: "-1KiB", + } + for value, want := range cases { + if got := HumanBytes(value); got != want { + t.Errorf("HumanBytes(%d) = %q, want %q", value, got, want) + } + } +} + +func TestHumanCountGroupsDigits(t *testing.T) { + cases := map[int64]string{ + 0: "0", + 999: "999", + 1000: "1,000", + 999999: "999,999", + 1000000: "1,000,000", + -12345: "-12,345", + } + for value, want := range cases { + if got := HumanCount(value); got != want { + t.Errorf("HumanCount(%d) = %q, want %q", value, got, want) + } + } +} diff --git a/internal/optimiser/plan.go b/internal/optimiser/plan.go new file mode 100644 index 0000000..d51a1cd --- /dev/null +++ b/internal/optimiser/plan.go @@ -0,0 +1,716 @@ +package optimiser + +import ( + "errors" + "fmt" + "sort" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/server" +) + +// The planner works on the merged manifest view directly, so that the entries +// it groups carry the block identity the repacker needs to copy them. +type ( + Entry = server.LayoutEntry + Pack = server.LayoutPack + Layout = server.Layout +) + +type Options struct { + // TargetPackSize bounds a rebuilt pack, in bytes of object content. + TargetPackSize int64 + // MinWasteFraction is how much of a pack must be bytes a restore pays for + // but does not want before rebuilding it is worth the upload. A download's + // fixed cost counts as such bytes, which is what makes a small pack worth + // merging even when every job restoring it wants all of it. + MinWasteFraction float64 + // MinImprovement is how much of a pack's restore cost its rebuild must + // remove. Without it, a pack no grouping can improve is rebuilt on every + // pass. + MinImprovement float64 + // DownloadOverhead is the fixed cost of restoring one pack, in the bytes + // it is worth: a request and a manifest to read before any content flows. + // It is what lets fewer, larger packs win over many small ones. + DownloadOverhead int64 + // MinRuns refuses to plan from a window too small to mean anything. + MinRuns int +} + +func DefaultOptions() Options { + return Options{ + TargetPackSize: 8 * 1024 * 1024, + MinWasteFraction: 0.25, + MinImprovement: 0.25, + DownloadOverhead: 8 * 1024 * 1024, + MinRuns: 3, + } +} + +// Timing gates the two kinds of rewrite by pack age. Eviction rewrites one +// pack at a time to drop entries nothing has used for EvictAfter. Reshaping +// regroups packs whose shape is at least ReshapeAfter old. +type Timing struct { + Now time.Time + // Ages is when each pack's contents took their current shape. A pack + // missing from it is treated as brand new. Nil turns the age gates off. + Ages map[string]time.Time + EvictAfter time.Duration + ReshapeAfter time.Duration + // Recent holds every usage record since Now-EvictAfter. Nil, because those + // records are incomplete, turns eviction off. + Recent *Demand +} + +// Group is one pack the optimiser will build. A reshaped group never mixes +// kinds: Bazel reads action results before it fetches any output, so a pack of +// pure action results answers many lookups for one small restore. +type Group struct { + Kind string + // Signature names the runs that would have restored this pack, and is + // empty for a pack no observed run wanted anything from. + Signature string + Entries []Entry + Bytes int64 + // Since is the age a pack rewritten only to evict stale entries inherits + // from its source. Zero for a reshaped pack, whose age starts afresh. + Since time.Time + // Evicts names the pack this group rewrites without its stale entries. + Evicts string + runs runSet +} + +type Plan struct { + Groups []Group + // Rewrite packs have live entries that all reappear in Groups, apart from + // any evicted as stale. + Rewrite []string + // Dead packs have no live entries left; every digest they hold is served + // from a lower pack ID. + Dead []string + Keep []string + // ReclaimedBytes counts object bytes that stop being stored at all. + ReclaimedBytes int64 + // WastedBytes counts what an average restore of the reshaped packs paid + // for and did not want. + WastedBytes int64 + // OverfetchBefore is what an average observed job downloaded from the + // reshaped packs and did not want; OverfetchAfter is the same for their + // replacements. Downloads count the packs it restored to get it. + OverfetchBefore int64 + OverfetchAfter int64 + DownloadsBefore float64 + DownloadsAfter float64 + // Unimproved counts packs over the waste threshold that were left alone + // because no regrouping found would cut their restore cost enough. + Unimproved int + // Evicted counts packs rewritten on their own to drop EvictedEntries stale + // entries holding EvictedBytes. + Evicted int + EvictedEntries int + EvictedBytes int64 + // Abandoned counts packs every entry of which is stale. Nothing restores + // them, so GitHub expires them; rewriting would only renew them. + Abandoned int + // ReshapeEligible counts packs old enough to reshape, and ReshapeSkipped + // says why reshaping did not run, when it did not. + ReshapeEligible int + ReshapeSkipped string +} + +func (p Plan) Empty() bool { return len(p.Rewrite) == 0 && len(p.Dead) == 0 } + +var errTooFewRuns = errors.New("too few usage records to plan from") + +// maxRefinements bounds how often the planner drops packs a regrouping does +// not improve and regroups what is left. +const maxRefinements = 8 + +// maxGroupEntries keeps a rebuilt pack's manifest well inside the entry limit +// readers enforce, however small its entries. +const maxGroupEntries = 50_000 + +type packState struct { + pack Pack + entries []Entry + liveBytes int64 + // Stale entries have been taken out of entries, and their bytes count as + // dead from here on. + staleEntries int + staleBytes int64 +} + +func (s *packState) deadBytes() int64 { return max(s.pack.DeclaredBytes-s.liveBytes, 0) } + +func (s *packState) restorers(demand *Demand) runSet { + restorers := newRunSet(demand.Runs()) + for _, entry := range s.entries { + restorers.union(demand.runSet(entry.Kind, entry.Digest)) + } + return restorers +} + +// waste estimates the bytes an average restore of this pack pays for and does +// not want. Measuring it per restoring run is what catches a pack whose entries +// are all wanted, but by different jobs, so every one of them overfetches. +func (s *packState) waste(demand *Demand) int64 { + restorers := s.restorers(demand) + // A pack no observed run restored costs only the storage its dead copies + // take; nothing ever downloads it to overfetch from. + if restorers.empty() { + return s.deadBytes() + } + var total int64 + for at := range demand.Runs() { + if !restorers.has(at) { + continue + } + var wanted int64 + for _, entry := range s.entries { + if demand.runSet(entry.Kind, entry.Digest).has(at) { + wanted += entry.Size + } + } + total += s.pack.DeclaredBytes - wanted + } + return total / int64(restorers.count()) +} + +// wasteful reports whether a pack is worth considering for a rebuild at all. +func (s *packState) wasteful(demand *Demand, options Options) bool { + if s.pack.DeclaredBytes <= 0 { + return false + } + waste, size := s.waste(demand), s.pack.DeclaredBytes + if !s.restorers(demand).empty() { + waste += options.DownloadOverhead + size += options.DownloadOverhead + } + return float64(waste)/float64(size) >= options.MinWasteFraction +} + +// cost is what restoring packs costs every observed run together: the bytes +// downloaded and not wanted, and the downloads it took. +type cost struct { + overfetch int64 + downloads float64 +} + +func (c cost) total(overhead int64) float64 { + return float64(c.overfetch) + c.downloads*float64(overhead) +} + +// placement is where a regrouping puts an entry: how many runs restore its new +// pack, and its share of that pack's downloads. +type placement struct { + restorers int + share float64 +} + +// costs measures the pack now, and once its entries sit where placed says. +// Every run that wants one entry of a pack downloads all of it, so each entry +// costs its size once for every restoring run that did not want it. +func (s *packState) costs(demand *Demand, placed map[string]placement) (before, after cost) { + current := s.restorers(demand).count() + before.overfetch = s.deadBytes() * int64(current) + before.downloads = float64(current) + for _, entry := range s.entries { + wanted := int64(demand.runSet(entry.Kind, entry.Digest).count()) + at := placed[demandKey(entry.Kind, entry.Digest)] + before.overfetch += entry.Size * (int64(current) - wanted) + after.overfetch += entry.Size * (int64(at.restorers) - wanted) + after.downloads += float64(at.restorers) * at.share + } + return before, after +} + +// worthRebuilding reports whether the regrouping pays for the upload, either +// by cutting what restoring the pack costs or by dropping enough dead copies +// to be worth it for the storage alone. +func (s *packState) worthRebuilding(before, after cost, options Options) bool { + was, now := before.total(options.DownloadOverhead), after.total(options.DownloadOverhead) + if gain := was - now; gain > 0 && gain >= options.MinImprovement*was { + return true + } + dead := s.deadBytes() + return dead > 0 && float64(dead) >= options.MinWasteFraction*float64(s.pack.DeclaredBytes) +} + +// NewPlan decides which packs to rebuild and how to regroup their contents, +// treating every pack as old enough to reshape and evicting nothing. +func NewPlan(layout Layout, demand *Demand, options Options) (Plan, error) { + return NewTimedPlan(layout, demand, options, Timing{}) +} + +// NewTimedPlan plans both kinds of rewrite. +// +// Eviction drops entries no job has used for EvictAfter from packs at least +// that old, one pack at a time and keeping each pack's age, so a pack holding a +// little dead weight is cleaned without disturbing anything else. Packs whose +// every entry is stale are left for GitHub to expire. +// +// Reshaping regroups packs whose shape is at least ReshapeAfter old, and only +// when there are at least two: one pack can only have its contents shuffled. +// A reshaped pack starts a new age, which is what keeps reshaping from +// revisiting the same packs on every pass. +// +// Nothing but disuse drops a live entry. A manifest records an action's +// closure as pack IDs rather than digests, so no entry can be proven +// unreferenced; but a reader validates an action's closure before serving it, +// so evicting something still referenced costs a cache miss rather than a +// broken build. +func NewTimedPlan(layout Layout, demand *Demand, options Options, timing Timing) (Plan, error) { + if demand.Runs() < options.MinRuns { + return Plan{}, fmt.Errorf("%w: have %d, want %d", errTooFewRuns, demand.Runs(), options.MinRuns) + } + if options.TargetPackSize <= 0 { + return Plan{}, errors.New("target pack size must be positive") + } + + states := make(map[string]*packState, len(layout.Packs)) + for _, pack := range layout.Packs { + states[pack.ID] = &packState{pack: pack} + } + for _, entry := range layout.Entries { + state, known := states[entry.Pack] + if !known { + return Plan{}, fmt.Errorf("entry %s/%s names unknown pack %s", entry.Kind, entry.Digest, entry.Pack) + } + state.entries = append(state.entries, entry) + state.liveBytes += entry.Size + } + + oldEnough := func(pack string, age time.Duration) bool { + if timing.Ages == nil { + return true + } + at, known := timing.Ages[pack] + return known && !at.IsZero() && !at.After(timing.Now.Add(-age)) + } + evicting := timing.Recent != nil && timing.EvictAfter > 0 + + plan := Plan{} + eligible := make([]*packState, 0) + evictOnly := make([]*packState, 0) + settle := func(state *packState) { + if state.staleEntries > 0 { + evictOnly = append(evictOnly, state) + } else { + plan.Keep = append(plan.Keep, state.pack.ID) + } + } + for _, pack := range sortedPackIDs(layout.Packs) { + state := states[pack] + if len(state.entries) == 0 { + plan.Dead = append(plan.Dead, pack) + plan.ReclaimedBytes += state.pack.DeclaredBytes + continue + } + if evicting && oldEnough(pack, timing.EvictAfter) { + fresh := state.entries[:0:0] + for _, entry := range state.entries { + if timing.Recent.Used(entry.Kind, entry.Digest) { + fresh = append(fresh, entry) + continue + } + state.staleEntries++ + state.staleBytes += entry.Size + } + if len(fresh) == 0 { + plan.Abandoned++ + plan.Keep = append(plan.Keep, pack) + continue + } + state.entries = fresh + state.liveBytes -= state.staleBytes + } + if oldEnough(pack, timing.ReshapeAfter) { + eligible = append(eligible, state) + } else { + settle(state) + } + } + plan.ReshapeEligible = len(eligible) + + reshaped := make([]*packState, 0) + if len(eligible) < 2 { + plan.ReshapeSkipped = fmt.Sprintf("%d packs are old enough to reshape, and reshaping needs at least 2", len(eligible)) + for _, state := range eligible { + settle(state) + } + } else { + candidates := make([]*packState, 0, len(eligible)) + for _, state := range eligible { + if state.wasteful(demand, options) { + candidates = append(candidates, state) + } else { + settle(state) + } + } + // A pack can be wasteful and still be the best grouping its entries + // allow, so each candidate has to earn its rebuild against the + // regrouping actually on offer, judged on runs that regrouping was not + // fitted to. Dropping one changes what the rest are grouped with, hence + // the loop. + fit, check := demand.split() + for iteration := 0; len(candidates) > 0 && iteration < maxRefinements; iteration++ { + trial := group(movingEntries(candidates), fit, options) + before, after := assess(candidates, trial, check) + kept := make([]*packState, 0, len(candidates)) + for _, state := range candidates { + if state.worthRebuilding(before[state], after[state], options) { + kept = append(kept, state) + continue + } + plan.Unimproved++ + settle(state) + } + if len(kept) == len(candidates) { + break + } + candidates = kept + } + reshaped = candidates + } + + sort.Slice(evictOnly, func(i, j int) bool { return evictOnly[i].pack.ID < evictOnly[j].pack.ID }) + for _, state := range evictOnly { + plan.Groups = append(plan.Groups, evictionGroup(state, demand, timing.Ages)) + plan.Rewrite = append(plan.Rewrite, state.pack.ID) + plan.ReclaimedBytes += state.deadBytes() + plan.Evicted++ + } + + // The packs actually built use every run, now that the choice of which to + // rebuild no longer rests on them. + groups := group(movingEntries(reshaped), demand, options) + before, after := assess(reshaped, groups, demand) + var was, now cost + for _, state := range reshaped { + plan.Rewrite = append(plan.Rewrite, state.pack.ID) + plan.ReclaimedBytes += state.deadBytes() + plan.WastedBytes += state.waste(demand) + was.overfetch += before[state].overfetch + was.downloads += before[state].downloads + now.overfetch += after[state].overfetch + now.downloads += after[state].downloads + } + for _, state := range append(append([]*packState(nil), evictOnly...), reshaped...) { + plan.EvictedEntries += state.staleEntries + plan.EvictedBytes += state.staleBytes + } + if runs := demand.Runs(); runs > 0 { + plan.OverfetchBefore = was.overfetch / int64(runs) + plan.OverfetchAfter = now.overfetch / int64(runs) + plan.DownloadsBefore = was.downloads / float64(runs) + plan.DownloadsAfter = now.downloads / float64(runs) + } + plan.Groups = append(plan.Groups, groups...) + plan.Groups = scheduleGroups(plan.Groups, layout.Packs) + sort.Strings(plan.Keep) + if err := plan.verify(movingEntries(append(evictOnly, reshaped...))); err != nil { + return Plan{}, err + } + return plan, nil +} + +// evictionGroup rewrites one pack without its stale entries, in the same order +// and with the same age, so that nothing but the stale entries changes. +func evictionGroup(state *packState, demand *Demand, ages map[string]time.Time) Group { + evicted := Group{ + Kind: state.entries[0].Kind, + Entries: append([]Entry(nil), state.entries...), + Since: ages[state.pack.ID], + Evicts: state.pack.ID, + runs: state.restorers(demand), + } + for _, entry := range state.entries { + evicted.Bytes += entry.Size + if entry.Kind != evicted.Kind { + evicted.Kind = "mixed" + } + } + evicted.Signature = demand.names(evicted.runs) + return evicted +} + +func movingEntries(states []*packState) []Entry { + moving := make([]Entry, 0) + for _, state := range states { + moving = append(moving, state.entries...) + } + return moving +} + +// assess measures each pack's restore cost now and once regrouped, under the +// given demand. That demand need not be what the groups were built from. +func assess(states []*packState, groups []Group, demand *Demand) (before, after map[*packState]cost) { + placed := make(map[string]placement) + for _, group := range groups { + restorers := newRunSet(demand.Runs()) + for _, entry := range group.Entries { + restorers.union(demand.runSet(entry.Kind, entry.Digest)) + } + count := restorers.count() + for _, entry := range group.Entries { + // A pack's downloads are shared out by bytes, or evenly among + // entries when it holds none. + share := 1 / float64(len(group.Entries)) + if group.Bytes > 0 { + share = float64(entry.Size) / float64(group.Bytes) + } + placed[demandKey(entry.Kind, entry.Digest)] = placement{restorers: count, share: share} + } + } + before = make(map[*packState]cost, len(states)) + after = make(map[*packState]cost, len(states)) + for _, state := range states { + before[state], after[state] = state.costs(demand, placed) + } + return before, after +} + +// candidateWindow bounds how far ahead a filling pack looks for its next chunk. +// The ordering already puts similar run sets close together, so a short look +// ahead finds nearly everything a full search would, at linear cost. +const candidateWindow = 64 + +// chunk is entries wanted by exactly the same runs, cut to fit a pack. +type chunk struct { + runs runSet + bytes int64 + entries []Entry +} + +// group fills packs so that the jobs restoring each one want as much of it as +// possible. Cold entries, which no observed job downloaded, get packs of their +// own: mixing them in is the waste this whole pass exists to remove. +func group(entries []Entry, demand *Demand, options Options) []Group { + byKind := make(map[string][]Entry) + for _, entry := range entries { + byKind[entry.Kind] = append(byKind[entry.Kind], entry) + } + kinds := make([]string, 0, len(byKind)) + for kind := range byKind { + kinds = append(kinds, kind) + } + sort.Strings(kinds) + + groups := make([]Group, 0) + for _, kind := range kinds { + var hot, cold []Entry + for _, entry := range byKind[kind] { + if demand.runSet(entry.Kind, entry.Digest).empty() { + cold = append(cold, entry) + } else { + hot = append(hot, entry) + } + } + groups = append(groups, groupHot(kind, hot, demand, options)...) + groups = append(groups, groupCold(kind, cold, demand, options.TargetPackSize)...) + } + return groups +} + +// scheduleGroups prioritizes groups that carry the largest share of the source +// packs they help retire. This lets completed source packs be released earlier +// during a partial optimization pass. +func scheduleGroups(groups []Group, packs []Pack) []Group { + type scheduledGroup struct { + group Group + score float64 + } + + sourceSizes := make(map[string]int64, len(packs)) + for _, pack := range packs { + size := pack.StoredSize + if size <= 0 { + size = pack.DeclaredBytes + } + if size <= 0 { + size = 1 + } + sourceSizes[pack.ID] = size + } + + groupSources := make([]map[string]struct{}, len(groups)) + sourceGroupCounts := make(map[string]int) + for index, group := range groups { + groupSources[index] = make(map[string]struct{}) + for _, entry := range group.Entries { + groupSources[index][entry.Pack] = struct{}{} + } + for source := range groupSources[index] { + sourceGroupCounts[source]++ + } + } + + scheduled := make([]scheduledGroup, len(groups)) + for index, group := range groups { + score := float64(0) + sources := make([]string, 0, len(groupSources[index])) + for source := range groupSources[index] { + sources = append(sources, source) + } + sort.Strings(sources) + for _, source := range sources { + if groups := sourceGroupCounts[source]; groups > 0 { + score += float64(sourceSizes[source]) / float64(groups) + } + } + scheduled[index] = scheduledGroup{group: group, score: score} + } + sort.SliceStable(scheduled, func(i, j int) bool { + return scheduled[i].score > scheduled[j].score + }) + ordered := make([]Group, len(scheduled)) + for index, item := range scheduled { + ordered[index] = item.group + } + return ordered +} + +// groupCold keeps entries that came from the same pack together, since they +// were written by the same job and are the likeliest to be wanted together. +func groupCold(kind string, entries []Entry, demand *Demand, targetSize int64) []Group { + sort.Slice(entries, func(i, j int) bool { + if entries[i].Pack != entries[j].Pack { + return entries[i].Pack < entries[j].Pack + } + return entries[i].Digest < entries[j].Digest + }) + groups := make([]Group, 0) + var current *Group + for _, entry := range entries { + if current == nil || current.Bytes+entry.Size > targetSize || len(current.Entries) >= maxGroupEntries { + groups = append(groups, Group{Kind: kind, runs: newRunSet(demand.Runs())}) + current = &groups[len(groups)-1] + } + current.Entries = append(current.Entries, entry) + current.Bytes += entry.Size + } + return groups +} + +func groupHot(kind string, entries []Entry, demand *Demand, options Options) []Group { + targetSize := options.TargetPackSize + sort.Slice(entries, func(i, j int) bool { return entries[i].Digest < entries[j].Digest }) + classes := make(map[string][]Entry) + sets := make(map[string]runSet) + for _, entry := range entries { + set := demand.runSet(entry.Kind, entry.Digest) + key := set.key() + classes[key] = append(classes[key], entry) + sets[key] = set + } + chunks := make([]chunk, 0, len(classes)) + for key, members := range classes { + var current *chunk + for _, entry := range members { + if current == nil || current.bytes+entry.Size > targetSize || len(current.entries) >= maxGroupEntries { + chunks = append(chunks, chunk{runs: sets[key]}) + current = &chunks[len(chunks)-1] + } + current.entries = append(current.entries, entry) + current.bytes += entry.Size + } + } + sort.Slice(chunks, func(i, j int) bool { + if chunks[i].runs.before(chunks[j].runs) { + return true + } + if chunks[j].runs.before(chunks[i].runs) { + return false + } + return chunks[i].entries[0].Digest < chunks[j].entries[0].Digest + }) + + overhead := options.DownloadOverhead + + // next links the chunks still to be placed, in order; len(chunks) ends it. + next := make([]int, len(chunks)) + for at := range next { + next[at] = at + 1 + } + head := 0 + groups := make([]Group, 0) + for head < len(chunks) { + seed := chunks[head] + head = next[head] + current := Group{ + Kind: kind, + Entries: append([]Entry(nil), seed.entries...), + Bytes: seed.bytes, + runs: seed.runs.clone(), + } + for current.Bytes < targetSize { + best, bestPrevious := -1, -1 + var bestBenefit int64 + previous, scanned := -1, 0 + for at := head; at < len(chunks) && scanned < candidateWindow; previous, at = at, next[at] { + scanned++ + candidate := &chunks[at] + if current.Bytes+candidate.bytes > targetSize || + len(current.Entries)+len(candidate.entries) > maxGroupEntries { + continue + } + // Every run restoring either part restores the merged pack. Merging + // saves those wanting both a download, and costs the others the + // part they do not want. + restoring := int64(current.runs.count()) + wanting := int64(candidate.runs.count()) + merged := restoring + int64(candidate.runs.without(current.runs)) + benefit := restoring*(current.Bytes+overhead) + wanting*(candidate.bytes+overhead) - + merged*(current.Bytes+candidate.bytes+overhead) + if best < 0 || benefit > bestBenefit { + best, bestPrevious, bestBenefit = at, previous, benefit + } + } + if best < 0 || bestBenefit < 0 { + break + } + candidate := &chunks[best] + if bestPrevious < 0 { + head = next[best] + } else { + next[bestPrevious] = next[best] + } + current.Entries = append(current.Entries, candidate.entries...) + current.Bytes += candidate.bytes + current.runs.union(candidate.runs) + } + current.Signature = demand.names(current.runs) + groups = append(groups, current) + } + return groups +} + +// verify is the safety net for the one invariant that matters: a pack is only +// ever deleted once every entry it served has somewhere else to come from. +func (p Plan) verify(moving []Entry) error { + placed := make(map[string]struct{}) + for _, group := range p.Groups { + for _, entry := range group.Entries { + key := demandKey(entry.Kind, entry.Digest) + if _, duplicate := placed[key]; duplicate { + return fmt.Errorf("plan places %s/%s into two packs", entry.Kind, entry.Digest) + } + placed[key] = struct{}{} + } + } + for _, entry := range moving { + if _, found := placed[demandKey(entry.Kind, entry.Digest)]; !found { + return fmt.Errorf("plan drops %s/%s", entry.Kind, entry.Digest) + } + } + return nil +} + +func sortedPackIDs(packs []Pack) []string { + ids := make([]string, 0, len(packs)) + for _, pack := range packs { + ids = append(ids, pack.ID) + } + sort.Strings(ids) + return ids +} diff --git a/internal/optimiser/plan_test.go b/internal/optimiser/plan_test.go new file mode 100644 index 0000000..1ce7bb4 --- /dev/null +++ b/internal/optimiser/plan_test.go @@ -0,0 +1,487 @@ +package optimiser + +import ( + "strconv" + "strings" + "testing" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/server" +) + +func demandFrom(t *testing.T, runs map[string][]server.UsageEntry) *Demand { + t.Helper() + demand := NewDemand() + for run, entries := range runs { + demand.Observe(run, server.UsageReport{Entries: entries}) + } + return demand +} + +func downloaded(kind, digest string) server.UsageEntry { + return server.UsageEntry{Kind: kind, Digest: digest, Downloads: 1} +} + +func checked(kind, digest string) server.UsageEntry { + return server.UsageEntry{Kind: kind, Digest: digest, PresenceChecks: 1} +} + +func entriesFor(pack string, kind string, count int, each int64) []Entry { + entries := make([]Entry, 0, count) + for index := range count { + entries = append(entries, Entry{ + Kind: kind, + Digest: kind + "-" + pack + "-" + strconv.Itoa(index), + Pack: pack, + Size: each, + }) + } + return entries +} + +func declare(id string, entries []Entry, extraDead int64) Pack { + var bytes int64 + for _, entry := range entries { + bytes += entry.Size + } + return Pack{ + ID: id, + StoredSize: bytes + extraDead, + DeclaredBytes: bytes + extraDead, + DeclaredCount: len(entries), + } +} + +// withBystander adds an old pack nothing downloads. Reshaping needs at least +// two packs old enough, and the bystander is never worth rebuilding, so the +// pack under test is what the plan is about. +func withBystander(layout Layout) Layout { + bystander := []Entry{{Kind: "cas", Digest: "bystander", Pack: "pack-zz", Size: 1}} + layout.Packs = append(append([]Pack(nil), layout.Packs...), declare("pack-zz", bystander, 0)) + layout.Entries = append(append([]Entry(nil), layout.Entries...), bystander...) + return layout +} + +func testOptions() Options { + options := DefaultOptions() + options.TargetPackSize = 1000 + options.MinRuns = 1 + options.DownloadOverhead = 0 + return options +} + +// The whole pass exists to stop a restore paying for bytes nothing wanted. +func TestPlanSeparatesHotEntriesFromColdOnes(t *testing.T) { + entries := entriesFor("pack-a", "cas", 4, 100) + layout := withBystander(Layout{Packs: []Pack{declare("pack-a", entries, 0)}, Entries: entries}) + demand := demandFrom(t, map[string][]server.UsageEntry{ + "run-1": {downloaded("cas", entries[0].Digest), downloaded("cas", entries[1].Digest)}, + }) + + plan, err := NewPlan(layout, demand, testOptions()) + if err != nil { + t.Fatal(err) + } + if len(plan.Rewrite) != 1 || plan.Rewrite[0] != "pack-a" { + t.Fatalf("rewrite = %v", plan.Rewrite) + } + if len(plan.Groups) != 2 { + t.Fatalf("groups = %+v, want a hot one and a cold one", plan.Groups) + } + for _, group := range plan.Groups { + wantHot := group.Signature != "" + for _, entry := range group.Entries { + if demand.Downloaded(entry.Kind, entry.Digest) != wantHot { + t.Fatalf("group %+v mixes hot and cold entries", group) + } + } + } + if plan.WastedBytes != 200 { + t.Fatalf("wasted = %d, want 200", plan.WastedBytes) + } +} + +func TestScheduleGroupsPrioritizesSourcePackProgress(t *testing.T) { + groups := []Group{ + {Entries: []Entry{{Kind: "cas", Digest: "a-1", Pack: "pack-a", Size: 1}}}, + {Entries: []Entry{ + {Kind: "cas", Digest: "a-2", Pack: "pack-a", Size: 1}, + {Kind: "cas", Digest: "b-1", Pack: "pack-b", Size: 1}, + }}, + {Entries: []Entry{{Kind: "cas", Digest: "b-2", Pack: "pack-b", Size: 1}}}, + } + packs := []Pack{ + {ID: "pack-a", StoredSize: 1000}, + {ID: "pack-b", StoredSize: 500}, + } + + ordered := scheduleGroups(groups, packs) + if got, want := ordered[0].Entries[0].Digest, "a-2"; got != want { + t.Fatalf("first group starts with %q, want %q", got, want) + } + if got, want := ordered[1].Entries[0].Digest, "a-1"; got != want { + t.Fatalf("second group starts with %q, want %q", got, want) + } + if got, want := ordered[2].Entries[0].Digest, "b-2"; got != want { + t.Fatalf("third group starts with %q, want %q", got, want) + } + + repeated := scheduleGroups(groups, packs) + for index := range ordered { + if ordered[index].Entries[0].Digest != repeated[index].Entries[0].Digest { + t.Fatalf("ordering is not deterministic: %q != %q", + ordered[index].Entries[0].Digest, repeated[index].Entries[0].Digest) + } + } +} + +// A pack that is entirely hot, or entirely cold, is already segregated. Paying +// to rebuild it would be pure churn. +func TestPlanLeavesUnmixedPacksAlone(t *testing.T) { + hot := entriesFor("pack-hot", "cas", 3, 100) + cold := entriesFor("pack-cold", "cas", 3, 100) + layout := Layout{ + Packs: []Pack{declare("pack-hot", hot, 0), declare("pack-cold", cold, 0)}, + Entries: append(append([]Entry{}, hot...), cold...), + } + demand := demandFrom(t, map[string][]server.UsageEntry{ + "run-1": {downloaded("cas", hot[0].Digest), downloaded("cas", hot[1].Digest), downloaded("cas", hot[2].Digest)}, + }) + + plan, err := NewPlan(layout, demand, testOptions()) + if err != nil { + t.Fatal(err) + } + if !plan.Empty() { + t.Fatalf("plan = %+v, want no work", plan) + } + if len(plan.Keep) != 2 { + t.Fatalf("keep = %v", plan.Keep) + } +} + +// A presence check is answered from the manifest without restoring the pack, so +// it costs a reader nothing and must not be treated as demand for the bytes. +func TestPlanTreatsPresenceOnlyEntriesAsCold(t *testing.T) { + entries := entriesFor("pack-a", "cas", 4, 100) + layout := withBystander(Layout{Packs: []Pack{declare("pack-a", entries, 0)}, Entries: entries}) + demand := demandFrom(t, map[string][]server.UsageEntry{ + "run-1": {checked("cas", entries[0].Digest), checked("cas", entries[1].Digest)}, + }) + + plan, err := NewPlan(layout, demand, testOptions()) + if err != nil { + t.Fatal(err) + } + if !plan.Empty() { + t.Fatalf("plan = %+v, want a wholly cold pack left alone", plan) + } +} + +// Entries wanted by the same jobs belong together; a later job then restores +// one pack instead of several. +func TestPlanGroupsEntriesWantedByTheSameRuns(t *testing.T) { + entries := entriesFor("pack-a", "cas", 4, 100) + layout := withBystander(Layout{Packs: []Pack{declare("pack-a", entries, 0)}, Entries: entries}) + demand := demandFrom(t, map[string][]server.UsageEntry{ + "run-1": {downloaded("cas", entries[0].Digest), downloaded("cas", entries[2].Digest)}, + "run-2": {downloaded("cas", entries[1].Digest), downloaded("cas", entries[3].Digest)}, + }) + + options := testOptions() + options.TargetPackSize = 200 + plan, err := NewPlan(layout, demand, options) + if err != nil { + t.Fatal(err) + } + if len(plan.Groups) != 2 { + t.Fatalf("groups = %+v", plan.Groups) + } + for _, group := range plan.Groups { + signatures := make(map[string]struct{}) + for _, entry := range group.Entries { + signatures[demand.Signature(entry.Kind, entry.Digest)] = struct{}{} + } + if len(signatures) != 1 { + t.Fatalf("group %+v mixes runs: %v", group.Entries, signatures) + } + } +} + +// Bazel reads action results before fetching any output, so a pack of pure +// action results answers many lookups for one small restore. +func TestPlanNeverMixesKindsInOnePack(t *testing.T) { + blobs := entriesFor("pack-a", "cas", 2, 100) + actions := entriesFor("pack-a", "ac", 2, 10) + all := append(append([]Entry{}, blobs...), actions...) + layout := withBystander(Layout{Packs: []Pack{declare("pack-a", all, 0)}, Entries: all}) + demand := demandFrom(t, map[string][]server.UsageEntry{ + "run-1": {downloaded("cas", blobs[0].Digest), downloaded("ac", actions[0].Digest)}, + }) + + plan, err := NewPlan(layout, demand, testOptions()) + if err != nil { + t.Fatal(err) + } + for _, group := range plan.Groups { + for _, entry := range group.Entries { + if entry.Kind != group.Kind { + t.Fatalf("group of kind %q holds %+v", group.Kind, entry) + } + } + } +} + +// A digest can end up in several packs, but only the lowest pack ID is ever +// served. A pack left holding nothing live is pure storage cost. +func TestPlanDeletesPacksWithNoLiveEntries(t *testing.T) { + live := entriesFor("pack-a", "cas", 2, 100) + shadowed := entriesFor("pack-b", "cas", 2, 100) + layout := Layout{ + Packs: []Pack{declare("pack-a", live, 0), declare("pack-b", shadowed, 0)}, + Entries: live, + } + demand := demandFrom(t, map[string][]server.UsageEntry{ + "run-1": {downloaded("cas", live[0].Digest), downloaded("cas", live[1].Digest)}, + }) + + plan, err := NewPlan(layout, demand, testOptions()) + if err != nil { + t.Fatal(err) + } + if len(plan.Dead) != 1 || plan.Dead[0] != "pack-b" { + t.Fatalf("dead = %v", plan.Dead) + } + if len(plan.Groups) != 0 { + t.Fatalf("a dead pack has nothing to rebuild, got %+v", plan.Groups) + } + if plan.ReclaimedBytes != 200 { + t.Fatalf("reclaimed = %d, want 200", plan.ReclaimedBytes) + } +} + +// Deleting a pack is only safe once every entry it served has somewhere else to +// come from, so a plan that would drop one must not be returned at all. +func TestPlanRefusesToDropAnEntry(t *testing.T) { + entries := entriesFor("pack-a", "cas", 2, 100) + plan := Plan{Groups: []Group{{Kind: "cas", Entries: entries[:1]}}} + if err := plan.verify(entries); err == nil { + t.Fatal("verify accepted a plan that drops an entry") + } + + duplicated := Plan{Groups: []Group{ + {Kind: "cas", Entries: entries[:1]}, + {Kind: "cas", Entries: entries[:1]}, + }} + if err := duplicated.verify(entries[:1]); err == nil { + t.Fatal("verify accepted a plan that stores an entry twice") + } +} + +func TestPlanRewritesEveryEntryOfARewrittenPack(t *testing.T) { + entries := entriesFor("pack-a", "cas", 40, 100) + layout := withBystander(Layout{Packs: []Pack{declare("pack-a", entries, 0)}, Entries: entries}) + observed := make([]server.UsageEntry, 0) + for index := 0; index < 10; index++ { + observed = append(observed, downloaded("cas", entries[index].Digest)) + } + demand := demandFrom(t, map[string][]server.UsageEntry{"run-1": observed}) + + plan, err := NewPlan(layout, demand, testOptions()) + if err != nil { + t.Fatal(err) + } + placed := 0 + for _, group := range plan.Groups { + if group.Bytes > testOptions().TargetPackSize { + t.Fatalf("group of %d bytes exceeds the target", group.Bytes) + } + placed += len(group.Entries) + } + if placed != len(entries) { + t.Fatalf("placed %d of %d entries", placed, len(entries)) + } +} + +// One entry larger than the target still has to go somewhere. +func TestPlanPlacesAnOversizedEntry(t *testing.T) { + entries := []Entry{ + {Kind: "cas", Digest: "big", Pack: "pack-a", Size: 5000}, + {Kind: "cas", Digest: "small", Pack: "pack-a", Size: 10}, + } + layout := withBystander(Layout{Packs: []Pack{declare("pack-a", entries, 0)}, Entries: entries}) + demand := demandFrom(t, map[string][]server.UsageEntry{ + "run-1": {downloaded("cas", "big")}, + }) + + options := testOptions() + options.MinWasteFraction = 0 + plan, err := NewPlan(layout, demand, options) + if err != nil { + t.Fatal(err) + } + if len(plan.Rewrite) != 1 { + t.Fatalf("rewrite = %v", plan.Rewrite) + } + if err := plan.verify(entries); err != nil { + t.Fatal(err) + } +} + +// Planning from one job's record would chase that job's particular shape. +func TestPlanRefusesTooSmallAWindow(t *testing.T) { + entries := entriesFor("pack-a", "cas", 2, 100) + layout := withBystander(Layout{Packs: []Pack{declare("pack-a", entries, 0)}, Entries: entries}) + demand := demandFrom(t, map[string][]server.UsageEntry{"run-1": nil}) + + options := testOptions() + options.MinRuns = 3 + if _, err := NewPlan(layout, demand, options); err == nil { + t.Fatal("planned from a single run") + } +} + +func TestPlanRejectsAnEntryNamingAnUnknownPack(t *testing.T) { + entries := entriesFor("pack-a", "cas", 1, 100) + layout := Layout{Packs: nil, Entries: entries} + demand := demandFrom(t, map[string][]server.UsageEntry{"run-1": nil}) + + _, err := NewPlan(layout, demand, testOptions()) + if err == nil || !strings.Contains(err.Error(), "unknown pack") { + t.Fatalf("error = %v", err) + } +} + +func TestDemandSignatureNamesTheRunsThatDownloaded(t *testing.T) { + demand := demandFrom(t, map[string][]server.UsageEntry{ + "run-2": {downloaded("cas", "a"), checked("cas", "b")}, + "run-1": {downloaded("cas", "a")}, + }) + if got := demand.Signature("cas", "a"); got != "run-1 run-2" { + t.Fatalf("signature = %q", got) + } + if got := demand.Signature("cas", "b"); got != "" { + t.Fatalf("a presence check is not demand for bytes, got %q", got) + } + if demand.Runs() != 2 { + t.Fatalf("runs = %d", demand.Runs()) + } + +} + +// A pack can be over the waste threshold and still be the best grouping its +// entries allow. Rebuilding it anyway is what made every pass redo the last. +func TestPlanLeavesAPackNoRegroupingImproves(t *testing.T) { + entries := entriesFor("pack-a", "cas", 2, 100) + layout := withBystander(Layout{Packs: []Pack{declare("pack-a", entries, 0)}, Entries: entries}) + demand := demandFrom(t, map[string][]server.UsageEntry{ + "run-1": {downloaded("cas", entries[0].Digest), downloaded("cas", entries[1].Digest)}, + "run-2": {downloaded("cas", entries[0].Digest)}, + }) + + // Splitting would spare run-2 the 100 bytes it does not want, at the cost + // of a second download for run-1 worth exactly as much. + options := testOptions() + options.DownloadOverhead = 100 + plan, err := NewPlan(layout, demand, options) + if err != nil { + t.Fatal(err) + } + if !plan.Empty() || plan.Unimproved != 1 { + t.Fatalf("plan = %+v, want the pack left alone as unimproved", plan) + } +} + +// Judged on the runs it was fitted to, any regrouping looks better. Only runs +// held out of the fit say whether a later job would gain anything. +func TestPlanJudgesARegroupingOnRunsItWasNotFittedTo(t *testing.T) { + entries := entriesFor("pack-a", "cas", 4, 100) + layout := withBystander(Layout{Packs: []Pack{declare("pack-a", entries, 0)}, Entries: entries}) + all := make([]server.UsageEntry, 0, len(entries)) + for _, entry := range entries { + all = append(all, downloaded("cas", entry.Digest)) + } + // run-4 is held out, and wants the whole pack. + demand := demandFrom(t, map[string][]server.UsageEntry{ + "run-1": {downloaded("cas", entries[0].Digest)}, + "run-2": {downloaded("cas", entries[1].Digest)}, + "run-3": {downloaded("cas", entries[2].Digest)}, + "run-4": all, + }) + + plan, err := NewPlan(layout, demand, testOptions()) + if err != nil { + t.Fatal(err) + } + if !plan.Empty() { + t.Fatalf("plan = %+v, want no rebuild the held-out run would not gain from", plan) + } +} + +func TestPlanRebuildsWhatHeldOutRunsWouldGainFrom(t *testing.T) { + first := entriesFor("pack-a", "cas", 2, 300) + second := entriesFor("pack-a", "ac", 2, 300) + for index := range second { + second[index].Kind = "cas" + } + all := append(append([]Entry{}, first...), second...) + layout := withBystander(Layout{Packs: []Pack{declare("pack-a", all, 0)}, Entries: all}) + // Two kinds of job alternate; the held-out run-4 and run-8 are both the second. + runs := make(map[string][]server.UsageEntry) + for run := 1; run <= 8; run++ { + wanted := first + if run%2 == 0 { + wanted = second + } + for _, entry := range wanted { + runs["run-"+strconv.Itoa(run)] = append(runs["run-"+strconv.Itoa(run)], downloaded("cas", entry.Digest)) + } + } + demand := demandFrom(t, runs) + + plan, err := NewPlan(layout, demand, testOptions()) + if err != nil { + t.Fatal(err) + } + if len(plan.Rewrite) != 1 || len(plan.Groups) != 2 { + t.Fatalf("plan = %+v, want the two jobs' entries split apart", plan) + } + if plan.OverfetchBefore != 600 || plan.OverfetchAfter != 0 { + t.Fatalf("overfetch per job %d -> %d, want 600 -> 0", plan.OverfetchBefore, plan.OverfetchAfter) + } +} + +// A small remainder wanted by fewer jobs joins the pack rather than costing +// the jobs that want it one more download. +func TestPlanFillsPacksWithEntriesTheSameJobsWant(t *testing.T) { + entries := entriesFor("pack-a", "cas", 6, 100) + cold := entriesFor("pack-a", "ac", 4, 100) + for index := range cold { + cold[index].Kind = "cas" + } + all := append(append([]Entry{}, entries...), cold...) + layout := withBystander(Layout{Packs: []Pack{declare("pack-a", all, 0)}, Entries: all}) + demand := demandFrom(t, map[string][]server.UsageEntry{ + "run-1": {downloaded("cas", entries[0].Digest), downloaded("cas", entries[1].Digest), downloaded("cas", entries[2].Digest), + downloaded("cas", entries[3].Digest), downloaded("cas", entries[4].Digest)}, + "run-2": {downloaded("cas", entries[0].Digest), downloaded("cas", entries[1].Digest), downloaded("cas", entries[2].Digest), + downloaded("cas", entries[3].Digest), downloaded("cas", entries[4].Digest), downloaded("cas", entries[5].Digest)}, + }) + + // Merging the remainder saves run-2 a download worth more than the 100 + // bytes it costs run-1. + options := testOptions() + options.DownloadOverhead = 200 + plan, err := NewPlan(layout, demand, options) + if err != nil { + t.Fatal(err) + } + var hot []Group + for _, group := range plan.Groups { + if group.Signature != "" { + hot = append(hot, group) + } + } + if len(hot) != 1 || len(hot[0].Entries) != 6 { + t.Fatalf("hot groups = %+v, want the remainder folded into one pack", hot) + } +} diff --git a/internal/optimiser/plan_timing_test.go b/internal/optimiser/plan_timing_test.go new file mode 100644 index 0000000..3814b19 --- /dev/null +++ b/internal/optimiser/plan_timing_test.go @@ -0,0 +1,220 @@ +package optimiser + +import ( + "testing" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/server" +) + +const day = 24 * time.Hour + +type timedFixture struct { + now time.Time + layout Layout + ages map[string]time.Time +} + +func newTimedFixture() *timedFixture { + return &timedFixture{now: time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC), ages: make(map[string]time.Time)} +} + +// pack adds a pack of count entries aged the given number of days. +func (f *timedFixture) pack(id string, count int, age time.Duration) []Entry { + entries := entriesFor(id, "cas", count, 100) + f.layout.Packs = append(f.layout.Packs, declare(id, entries, 0)) + f.layout.Entries = append(f.layout.Entries, entries...) + f.ages[id] = f.now.Add(-age) + return entries +} + +func (f *timedFixture) timing(recent *Demand) Timing { + return Timing{Now: f.now, Ages: f.ages, EvictAfter: 7 * day, ReshapeAfter: 14 * day, Recent: recent} +} + +func usedBy(entries ...Entry) []server.UsageEntry { + used := make([]server.UsageEntry, 0, len(entries)) + for _, entry := range entries { + used = append(used, downloaded(entry.Kind, entry.Digest)) + } + return used +} + +// A pack holding a little dead weight is cleaned on its own: nothing else +// moves, and it keeps its age so that reshaping still reaches it in time. +func TestTimedPlanEvictsStaleEntriesFromOnePackAlone(t *testing.T) { + fixture := newTimedFixture() + mixed := fixture.pack("pack-a", 3, 10*day) + clean := fixture.pack("pack-b", 2, 10*day) + recent := demandFrom(t, map[string][]server.UsageEntry{"run-1": usedBy(mixed[0], mixed[1], clean[0], clean[1])}) + + plan, err := NewTimedPlan(fixture.layout, recent, testOptions(), fixture.timing(recent)) + if err != nil { + t.Fatal(err) + } + if len(plan.Rewrite) != 1 || plan.Rewrite[0] != "pack-a" || len(plan.Keep) != 1 || plan.Keep[0] != "pack-b" { + t.Fatalf("rewrite %v, keep %v; want only the pack with stale entries rewritten", plan.Rewrite, plan.Keep) + } + if len(plan.Groups) != 1 { + t.Fatalf("groups = %+v", plan.Groups) + } + evicted := plan.Groups[0] + if evicted.Evicts != "pack-a" || len(evicted.Entries) != 2 || !evicted.Since.Equal(fixture.ages["pack-a"]) { + t.Fatalf("group = %+v, want pack-a's two used entries at its original age", evicted) + } + if plan.Evicted != 1 || plan.EvictedEntries != 1 || plan.EvictedBytes != 100 || plan.ReclaimedBytes != 100 { + t.Fatalf("evicted %d packs, %d entries, %d bytes; reclaimed %d", + plan.Evicted, plan.EvictedEntries, plan.EvictedBytes, plan.ReclaimedBytes) + } +} + +// Presence checks are how a job, or a reader validating an action result, +// depends on an entry without downloading it. +func TestTimedPlanKeepsEntriesOnlyCheckedForPresence(t *testing.T) { + fixture := newTimedFixture() + entries := fixture.pack("pack-a", 2, 10*day) + recent := demandFrom(t, map[string][]server.UsageEntry{ + "run-1": {downloaded("cas", entries[0].Digest), checked("cas", entries[1].Digest)}, + }) + + plan, err := NewTimedPlan(fixture.layout, recent, testOptions(), fixture.timing(recent)) + if err != nil { + t.Fatal(err) + } + if !plan.Empty() { + t.Fatalf("plan = %+v, want nothing evicted", plan) + } +} + +// Entries written less than the eviction threshold ago may simply not have +// been needed yet. +func TestTimedPlanLeavesYoungPacksAlone(t *testing.T) { + fixture := newTimedFixture() + entries := fixture.pack("pack-a", 3, 3*day) + recent := demandFrom(t, map[string][]server.UsageEntry{"run-1": usedBy(entries[0])}) + + plan, err := NewTimedPlan(fixture.layout, recent, testOptions(), fixture.timing(recent)) + if err != nil { + t.Fatal(err) + } + if !plan.Empty() { + t.Fatalf("plan = %+v, want a young pack left alone", plan) + } +} + +// Nothing restores a pack every entry of which is stale, so GitHub expires it. +// Rewriting it would only renew it. +func TestTimedPlanLeavesWhollyStalePacksToExpire(t *testing.T) { + fixture := newTimedFixture() + fixture.pack("pack-a", 3, 10*day) + used := fixture.pack("pack-b", 1, 10*day) + recent := demandFrom(t, map[string][]server.UsageEntry{"run-1": usedBy(used...)}) + + plan, err := NewTimedPlan(fixture.layout, recent, testOptions(), fixture.timing(recent)) + if err != nil { + t.Fatal(err) + } + if !plan.Empty() || plan.Abandoned != 1 { + t.Fatalf("plan = %+v, want the stale pack abandoned untouched", plan) + } +} + +// Without every record in the window, an entry that looks unused may have been +// used by a record that could not be read. +func TestTimedPlanEvictsNothingWithoutCompleteRecords(t *testing.T) { + fixture := newTimedFixture() + entries := fixture.pack("pack-a", 3, 10*day) + demand := demandFrom(t, map[string][]server.UsageEntry{"run-1": usedBy(entries[0])}) + + plan, err := NewTimedPlan(fixture.layout, demand, testOptions(), fixture.timing(nil)) + if err != nil { + t.Fatal(err) + } + if !plan.Empty() { + t.Fatalf("plan = %+v, want no eviction", plan) + } +} + +// One pack old enough to reshape can only have its contents shuffled, so it is +// not reshaped, though its stale entries still go. +func TestTimedPlanDoesNotReshapeASinglePack(t *testing.T) { + fixture := newTimedFixture() + old := fixture.pack("pack-a", 4, 20*day) + young := fixture.pack("pack-b", 2, 2*day) + // Run-1 and run-2 want different halves of the old pack, which reshaping + // would split, and nothing wants its last entry. + recent := demandFrom(t, map[string][]server.UsageEntry{ + "run-1": usedBy(old[0], young[0], young[1]), + "run-2": usedBy(old[1], old[2]), + }) + + plan, err := NewTimedPlan(fixture.layout, recent, testOptions(), fixture.timing(recent)) + if err != nil { + t.Fatal(err) + } + if plan.ReshapeEligible != 1 || plan.ReshapeSkipped == "" { + t.Fatalf("eligible %d, skipped %q", plan.ReshapeEligible, plan.ReshapeSkipped) + } + if len(plan.Groups) != 1 || plan.Groups[0].Evicts != "pack-a" || len(plan.Groups[0].Entries) != 3 { + t.Fatalf("groups = %+v, want pack-a evicted in place", plan.Groups) + } +} + +// Reshaping regroups only packs old enough, merges small packs restored by the +// same jobs to save their downloads, and starts the result's age afresh. +func TestTimedPlanReshapesOldPacksIntoFewerDownloads(t *testing.T) { + fixture := newTimedFixture() + first := fixture.pack("pack-a", 2, 20*day) + second := fixture.pack("pack-b", 2, 20*day) + young := fixture.pack("pack-c", 2, 2*day) + runs := make(map[string][]server.UsageEntry) + for _, run := range []string{"run-1", "run-2", "run-3", "run-4"} { + runs[run] = usedBy(append(append(append([]Entry(nil), first...), second...), young...)...) + } + recent := demandFrom(t, runs) + + options := testOptions() + options.DownloadOverhead = 1000 + plan, err := NewTimedPlan(fixture.layout, recent, options, fixture.timing(recent)) + if err != nil { + t.Fatal(err) + } + if len(plan.Rewrite) != 2 || len(plan.Groups) != 1 || len(plan.Groups[0].Entries) != 4 { + t.Fatalf("rewrite %v into %+v, want the two old packs merged", plan.Rewrite, plan.Groups) + } + if !plan.Groups[0].Since.IsZero() || plan.Groups[0].Evicts != "" { + t.Fatalf("group = %+v, want a reshaped pack with a fresh age", plan.Groups[0]) + } + if plan.DownloadsBefore != 2 || plan.DownloadsAfter != 1 { + t.Fatalf("downloads per job %v -> %v, want 2 -> 1", plan.DownloadsBefore, plan.DownloadsAfter) + } + for _, kept := range plan.Keep { + if kept == "pack-c" { + return + } + } + t.Fatalf("keep = %v, want the young pack untouched", plan.Keep) +} + +// However tiny the entries, a pack's manifest has to stay within what readers +// accept. +func TestPlanCapsEntriesPerPack(t *testing.T) { + entries := entriesFor("pack-a", "cas", maxGroupEntries+10, 1) + layout := withBystander(Layout{Packs: []Pack{declare("pack-a", entries, 0)}, Entries: entries}) + demand := demandFrom(t, map[string][]server.UsageEntry{"run-1": usedBy(entries[:5]...)}) + + options := testOptions() + options.TargetPackSize = 1 << 30 + plan, err := NewPlan(layout, demand, options) + if err != nil { + t.Fatal(err) + } + if len(plan.Groups) == 0 { + t.Fatal("nothing was regrouped") + } + for _, group := range plan.Groups { + if len(group.Entries) > maxGroupEntries { + t.Fatalf("a group holds %d entries", len(group.Entries)) + } + } +} diff --git a/internal/optimiser/reap.go b/internal/optimiser/reap.go new file mode 100644 index 0000000..ff9b4c2 --- /dev/null +++ b/internal/optimiser/reap.go @@ -0,0 +1,94 @@ +package optimiser + +import ( + "context" + "fmt" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/cache" + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/server" +) + +// EntryLister reports listed cache entries with their creation time. +type EntryLister interface { + ListEntries(ctx context.Context, keyPrefix string) ([]cache.CatalogEntry, error) +} + +// reap deletes packs that no manifest names. Such a pack is unreachable: a +// reader only ever finds a pack through a manifest, so nothing can serve it. +// It reports how many packs passed the age filter and how many were deleted, +// which differ on a dry run. +// +// Two things make this safe enough to offer at all. Packs whose manifest merely +// failed to load are excluded by ReadLayout, because another ref may still be +// reading them. And an age threshold well beyond any job's lifetime separates a +// pack whose manifest was lost from one a running job has published but not yet +// committed a manifest for. +func reap(ctx context.Context, options RunOptions, layout server.Layout) (int, int, error) { + keys := make([]string, 0, len(layout.UnmanifestedPacks)) + for _, pack := range layout.UnmanifestedPacks { + keys = append(keys, pack.Key) + } + return reapKeys(ctx, options, server.PackKeyPrefix(options.KeyPrefix), "unmanifested packs", keys) +} + +// reapManifests deletes manifests whose pack is gone. Readers already skip +// them, and they would expire unread within a week, but until then they take +// quota from a cache whose packs are being evicted for want of it. The age +// threshold covers a listing taken between a job publishing a pack and that +// pack appearing in the listing. +func reapManifests(ctx context.Context, options RunOptions, layout server.Layout) (int, int, error) { + keys := make([]string, 0, len(layout.PacklessManifests)) + for _, manifest := range layout.PacklessManifests { + keys = append(keys, manifest.Key) + } + return reapKeys(ctx, options, server.ManifestKeyPrefix(options.KeyPrefix), "manifests whose pack is gone", keys) +} + +func reapKeys(ctx context.Context, options RunOptions, listPrefix, noun string, keys []string) (int, int, error) { + if len(keys) == 0 { + return 0, 0, nil + } + if options.Lister == nil { + return 0, 0, fmt.Errorf("reaping needs a catalog that reports creation times") + } + if options.ReapOlderThan <= 0 { + return 0, 0, fmt.Errorf("reaping needs a positive age threshold") + } + + entries, err := options.Lister.ListEntries(ctx, listPrefix) + if err != nil { + return 0, 0, fmt.Errorf("list %s for reaping: %w", noun, err) + } + created := make(map[string]time.Time, len(entries)) + for _, entry := range entries { + created[entry.Key] = entry.CreatedAt + } + + cutoff := time.Now().Add(-options.ReapOlderThan) + reapable := 0 + deleted := 0 + tooYoung := 0 + for _, key := range keys { + at, known := created[key] + // An entry with no creation time is left alone: without it there is no + // way to tell it apart from one being written right now. + if !known || at.IsZero() || at.After(cutoff) { + tooYoung++ + continue + } + reapable++ + if options.DryRun { + continue + } + if err := options.Pruner.Delete(ctx, key); err != nil { + return reapable, deleted, fmt.Errorf("reap %s: %w", key, err) + } + deleted++ + } + if tooYoung > 0 { + options.Log("left %d %s alone: newer than %s, or with no known creation time", + tooYoung, noun, options.ReapOlderThan) + } + return reapable, deleted, nil +} diff --git a/internal/optimiser/reap_test.go b/internal/optimiser/reap_test.go new file mode 100644 index 0000000..a0b722c --- /dev/null +++ b/internal/optimiser/reap_test.go @@ -0,0 +1,215 @@ +package optimiser + +import ( + "context" + "testing" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/cache" + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/server" +) + +type fakeLister struct { + entries []cache.CatalogEntry +} + +func (l fakeLister) ListEntries(context.Context, string) ([]cache.CatalogEntry, error) { + return l.entries, nil +} + +func reapOptions(pruner Pruner, entries []cache.CatalogEntry) RunOptions { + return RunOptions{ + Pruner: pruner, + Lister: fakeLister{entries: entries}, + KeyPrefix: "prefix", + ReapOlderThan: 24 * time.Hour, + Log: func(string, ...any) {}, + } +} + +func TestReapRemovesOldPacksNoManifestNames(t *testing.T) { + pruner := &recordingPruner{} + layout := server.Layout{UnmanifestedPacks: []server.LayoutPack{ + {ID: "old", Key: "prefix-car-pack-v1-old"}, + }} + options := reapOptions(pruner, []cache.CatalogEntry{ + {Key: "prefix-car-pack-v1-old", CreatedAt: time.Now().Add(-72 * time.Hour)}, + }) + + reapable, reaped, err := reap(context.Background(), options, layout) + if err != nil { + t.Fatal(err) + } + if reapable != 1 || reaped != 1 || len(pruner.deleted) != 1 { + t.Fatalf("reapable %d, reaped %d, deleted %v", reapable, reaped, pruner.deleted) + } +} + +// A pack a running job has published but not yet committed a manifest for looks +// exactly like one whose manifest was lost. Only age tells them apart. +func TestReapLeavesRecentPacksAlone(t *testing.T) { + pruner := &recordingPruner{} + layout := server.Layout{UnmanifestedPacks: []server.LayoutPack{ + {ID: "fresh", Key: "prefix-car-pack-v1-fresh"}, + }} + options := reapOptions(pruner, []cache.CatalogEntry{ + {Key: "prefix-car-pack-v1-fresh", CreatedAt: time.Now().Add(-time.Minute)}, + }) + + reapable, reaped, err := reap(context.Background(), options, layout) + if err != nil { + t.Fatal(err) + } + if reapable != 0 || reaped != 0 || len(pruner.deleted) != 0 { + t.Fatalf("reapable %d, reaped %d, deleted %v", reapable, reaped, pruner.deleted) + } +} + +// Without a creation time there is no way to tell a lost pack from one being +// written right now. +func TestReapLeavesPacksWithNoKnownAge(t *testing.T) { + pruner := &recordingPruner{} + layout := server.Layout{UnmanifestedPacks: []server.LayoutPack{ + {ID: "unknown", Key: "prefix-car-pack-v1-unknown"}, + }} + + for _, entries := range [][]cache.CatalogEntry{ + nil, + {{Key: "prefix-car-pack-v1-unknown"}}, + } { + reapable, reaped, err := reap(context.Background(), reapOptions(pruner, entries), layout) + if err != nil { + t.Fatal(err) + } + if reapable != 0 || reaped != 0 || len(pruner.deleted) != 0 { + t.Fatalf("reapable %d, reaped %d, deleted %v", reapable, reaped, pruner.deleted) + } + } +} + +// A pack whose manifest exists but could not be read is not unmanifested: +// another ref may still be reading it, so it never reaches the reaper. +func TestReapOnlyEverSeesUnmanifestedPacks(t *testing.T) { + pruner := &recordingPruner{} + layout := server.Layout{ + Packs: []server.LayoutPack{{ID: "live", Key: "prefix-car-pack-v1-live"}}, + OrphanPacks: 5, + UnreadableManifests: 5, + } + options := reapOptions(pruner, []cache.CatalogEntry{ + {Key: "prefix-car-pack-v1-live", CreatedAt: time.Now().Add(-72 * time.Hour)}, + }) + + reapable, reaped, err := reap(context.Background(), options, layout) + if err != nil { + t.Fatal(err) + } + if reapable != 0 || reaped != 0 || len(pruner.deleted) != 0 { + t.Fatalf("reapable %d, reaped %d, deleted %v", reapable, reaped, pruner.deleted) + } +} + +// A dry run has to apply the age filter, or its count says nothing about what a +// real pass would remove. +func TestReapCountsCandidatesOnADryRunWithoutDeleting(t *testing.T) { + pruner := &recordingPruner{} + layout := server.Layout{UnmanifestedPacks: []server.LayoutPack{ + {ID: "old", Key: "prefix-car-pack-v1-old"}, + {ID: "fresh", Key: "prefix-car-pack-v1-fresh"}, + }} + options := reapOptions(pruner, []cache.CatalogEntry{ + {Key: "prefix-car-pack-v1-old", CreatedAt: time.Now().Add(-72 * time.Hour)}, + {Key: "prefix-car-pack-v1-fresh", CreatedAt: time.Now().Add(-time.Minute)}, + }) + options.DryRun = true + + reapable, reaped, err := reap(context.Background(), options, layout) + if err != nil { + t.Fatal(err) + } + if reapable != 1 { + t.Fatalf("reapable = %d, want the one old enough", reapable) + } + if reaped != 0 || len(pruner.deleted) != 0 { + t.Fatalf("a dry run deleted %d packs: %v", reaped, pruner.deleted) + } +} + +func TestReapRefusesWithoutAnAgeThreshold(t *testing.T) { + layout := server.Layout{UnmanifestedPacks: []server.LayoutPack{ + {ID: "old", Key: "prefix-car-pack-v1-old"}, + }} + options := reapOptions(&recordingPruner{}, nil) + options.ReapOlderThan = 0 + if _, _, err := reap(context.Background(), options, layout); err == nil { + t.Fatal("reaped without an age threshold") + } +} + +// A manifest whose pack is gone is skipped by every reader, so once it is old +// enough that no listing race can explain it, it is only taking quota. +func TestReapManifestsRemovesOldManifestsWhosePackIsGone(t *testing.T) { + pruner := &recordingPruner{} + layout := server.Layout{PacklessManifests: []server.LayoutManifest{ + {ID: "old", Key: "prefix-car-manifest-v2-gone-old", Pack: "gone"}, + {ID: "fresh", Key: "prefix-car-manifest-v2-new-fresh", Pack: "new"}, + }} + options := reapOptions(pruner, []cache.CatalogEntry{ + {Key: "prefix-car-manifest-v2-gone-old", CreatedAt: time.Now().Add(-72 * time.Hour)}, + {Key: "prefix-car-manifest-v2-new-fresh", CreatedAt: time.Now().Add(-time.Minute)}, + }) + + reapable, reaped, err := reapManifests(context.Background(), options, layout) + if err != nil { + t.Fatal(err) + } + if reapable != 1 || reaped != 1 || len(pruner.deleted) != 1 || pruner.deleted[0] != "prefix-car-manifest-v2-gone-old" { + t.Fatalf("reapable %d, reaped %d, deleted %v", reapable, reaped, pruner.deleted) + } +} + +func TestReapManifestsDeletesNothingOnADryRun(t *testing.T) { + pruner := &recordingPruner{} + layout := server.Layout{PacklessManifests: []server.LayoutManifest{ + {ID: "old", Key: "prefix-car-manifest-v2-gone-old", Pack: "gone"}, + }} + options := reapOptions(pruner, []cache.CatalogEntry{ + {Key: "prefix-car-manifest-v2-gone-old", CreatedAt: time.Now().Add(-72 * time.Hour)}, + }) + options.DryRun = true + + reapable, reaped, err := reapManifests(context.Background(), options, layout) + if err != nil { + t.Fatal(err) + } + if reapable != 1 || reaped != 0 || len(pruner.deleted) != 0 { + t.Fatalf("reapable %d, reaped %d, deleted %v", reapable, reaped, pruner.deleted) + } +} + +// A pack rewritten only to evict stale entries records its age in its manifest, +// which must win over its own, newer, creation time. +func TestPackAgesPreferWhatTheManifestRecords(t *testing.T) { + recorded := time.Now().Add(-30 * 24 * time.Hour).UTC().Truncate(time.Second) + created := time.Now().Add(-time.Hour).UTC().Truncate(time.Second) + layout := server.Layout{Packs: []server.LayoutPack{ + {ID: "evicted", Key: "prefix-car-pack-v1-evicted", Since: recorded}, + {ID: "written", Key: "prefix-car-pack-v1-written"}, + {ID: "unlisted", Key: "prefix-car-pack-v1-unlisted"}, + }} + options := reapOptions(&recordingPruner{}, []cache.CatalogEntry{ + {Key: "prefix-car-pack-v1-evicted", CreatedAt: created}, + {Key: "prefix-car-pack-v1-written", CreatedAt: created}, + }) + + ages, err := packAges(context.Background(), options, layout) + if err != nil { + t.Fatal(err) + } + if !ages["evicted"].Equal(recorded) || !ages["written"].Equal(created) { + t.Fatalf("ages = %v", ages) + } + if _, known := ages["unlisted"]; known { + t.Fatal("a pack with no known age was given one") + } +} diff --git a/internal/optimiser/records.go b/internal/optimiser/records.go new file mode 100644 index 0000000..002d968 --- /dev/null +++ b/internal/optimiser/records.go @@ -0,0 +1,320 @@ +package optimiser + +import ( + "archive/zip" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "sort" + "strconv" + "strings" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/server" +) + +// maxRecordBytes bounds one decompressed usage record. The archive comes from +// a workflow run, so it is only as trustworthy as whoever could start one. +const maxRecordBytes = 64 * 1024 * 1024 + +// usageFileName is the entry each job's teardown writes into its artifact. +const usageFileName = "cache-usage.json" + +// RecordSource reads the usage records jobs published as workflow artifacts. +// It needs actions: read and nothing more. +type RecordSource struct { + baseURL *url.URL + repository string + token string + artifact string + client *http.Client +} + +func NewRecordSource(artifact string, timeout time.Duration) (*RecordSource, error) { + repository := os.Getenv("GITHUB_REPOSITORY") + if len(strings.Split(repository, "/")) != 2 || strings.HasPrefix(repository, "/") || strings.HasSuffix(repository, "/") { + return nil, errors.New("GITHUB_REPOSITORY must be owner/repository") + } + token := os.Getenv("GITHUB_TOKEN") + if token == "" { + return nil, errors.New("GITHUB_TOKEN is required to read usage records") + } + baseURLText := os.Getenv("GITHUB_API_URL") + if baseURLText == "" { + baseURLText = "https://api.github.com" + } + baseURL, err := url.Parse(baseURLText) + if err != nil || baseURL.Scheme == "" || baseURL.Host == "" { + return nil, fmt.Errorf("invalid GITHUB_API_URL: %w", err) + } + if artifact == "" { + return nil, errors.New("the usage artifact name is required") + } + return &RecordSource{ + baseURL: baseURL, + repository: repository, + token: token, + artifact: artifact, + client: &http.Client{Timeout: timeout}, + }, nil +} + +type artifactListResponse struct { + Artifacts []artifactSummary `json:"artifacts"` +} + +type artifactSummary struct { + ID int64 `json:"id"` + Expired bool `json:"expired"` + SizeInBytes int64 `json:"size_in_bytes"` + CreatedAt time.Time `json:"created_at"` + WorkflowRun struct { + ID int64 `json:"id"` + RepositoryID int64 `json:"repository_id"` + HeadRepositoryID int64 `json:"head_repository_id"` + } `json:"workflow_run"` +} + +const ( + artifactsPerPage = 100 + // maxArtifactPages bounds how far back a listing pages. A repository busy + // enough to exceed it within the eviction window gets no eviction rather + // than an unbounded pass. + maxArtifactPages = 50 +) + +// Window asks for every record since a point in time, on top of the newest +// ones a plan is built from. +type Window struct { + Since time.Time + Recent *Demand +} + +// Coverage says whether Recent holds every record since the window opened. +// Only then does "no record used this entry" mean nothing used it. +type Coverage struct { + Records int + Complete bool + Gap string +} + +// Collect folds the newest records into demand and reports how many it read. +// A record that cannot be read is skipped rather than fatal: the plan simply +// rests on a smaller window. +func (s *RecordSource) Collect(ctx context.Context, demand *Demand, limit int, warn func(string, ...any)) (int, error) { + collected, _, err := s.CollectWindow(ctx, demand, limit, Window{}, warn) + return collected, err +} + +// CollectWindow is Collect, and also folds every record created since +// window.Since into window.Recent. +func (s *RecordSource) CollectWindow(ctx context.Context, demand *Demand, limit int, window Window, warn func(string, ...any)) (int, Coverage, error) { + summaries, reached, err := s.list(ctx, limit, window.Since) + if err != nil { + return 0, Coverage{}, err + } + coverage := Coverage{} + gap := func(reason string) { + if coverage.Gap == "" { + coverage.Gap = reason + } + } + if !window.Since.IsZero() && !reached { + gap(fmt.Sprintf("the usage records listed do not reach back to %s", window.Since.Format(time.RFC3339))) + } + collected := 0 + for _, summary := range summaries { + run := summary.WorkflowRun.ID + inWindow := !window.Since.IsZero() && !summary.CreatedAt.Before(window.Since) + if !window.Since.IsZero() && summary.CreatedAt.IsZero() { + gap(fmt.Sprintf("the record from run %d has no creation time", run)) + } + if summary.Expired || summary.SizeInBytes > maxRecordBytes { + if inWindow { + gap(fmt.Sprintf("the record from run %d has expired or is too large", run)) + } + continue + } + forPlan := collected < limit + if !forPlan && !inWindow { + continue + } + report, err := s.download(ctx, summary) + if err != nil { + warn("skipping usage record from run %d: %v", run, err) + if inWindow { + gap(fmt.Sprintf("the record from run %d could not be read", run)) + } + continue + } + // Every job publishes its own record, often under the same name as the + // other jobs of its run, and each job restores packs for itself. + id := recordID(summary) + if forPlan { + demand.Observe(id, report) + collected++ + } + if inWindow && window.Recent != nil { + window.Recent.Observe(id, report) + coverage.Records++ + } + } + coverage.Complete = !window.Since.IsZero() && coverage.Gap == "" + return collected, coverage, nil +} + +// list returns the records worth reading, newest first: at least limit usable +// ones, and everything since since. It reports whether the listing reached a +// record older than since, which is the only proof nothing in between is +// missing. Running out of records proves nothing, since retention may have +// deleted older ones. +func (s *RecordSource) list(ctx context.Context, limit int, since time.Time) ([]artifactSummary, bool, error) { + selected := make([]artifactSummary, 0, limit) + seen := make(map[int64]struct{}) + usable := 0 + reached := false + for page := 1; page <= maxArtifactPages; page++ { + listed, err := s.listPage(ctx, page) + if err != nil { + return nil, false, err + } + for _, summary := range listed { + if !since.IsZero() && !summary.CreatedAt.IsZero() && summary.CreatedAt.Before(since) { + reached = true + } + // A run started from a fork is outside this repository's trust + // boundary and could otherwise steer the layout by publishing a + // shaped record. + if summary.WorkflowRun.HeadRepositoryID != summary.WorkflowRun.RepositoryID { + continue + } + // Pages can shift while being read, so the same record may be listed + // twice; it must not count twice. Records of other jobs in the same + // run are not duplicates: dropping them would hide what those jobs + // used, and eviction would take it. + if _, duplicate := seen[summary.ID]; duplicate { + continue + } + seen[summary.ID] = struct{}{} + selected = append(selected, summary) + if !summary.Expired && summary.SizeInBytes <= maxRecordBytes { + usable++ + } + } + if len(listed) < artifactsPerPage || usable >= limit && (since.IsZero() || reached) { + break + } + } + sort.SliceStable(selected, func(i, j int) bool { return selected[i].CreatedAt.After(selected[j].CreatedAt) }) + return selected, reached, nil +} + +// recordID names the job a record came from: its run, and the artifact the +// job published. +func recordID(summary artifactSummary) string { + return strconv.FormatInt(summary.WorkflowRun.ID, 10) + "/" + strconv.FormatInt(summary.ID, 10) +} + +func (s *RecordSource) listPage(ctx context.Context, page int) ([]artifactSummary, error) { + endpoint := *s.baseURL + endpoint.Path = strings.TrimRight(endpoint.Path, "/") + "/repos/" + s.repository + "/actions/artifacts" + query := endpoint.Query() + query.Set("name", s.artifact) + query.Set("per_page", strconv.Itoa(artifactsPerPage)) + query.Set("page", strconv.Itoa(page)) + endpoint.RawQuery = query.Encode() + + request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil) + if err != nil { + return nil, err + } + s.authorize(request) + response, err := s.client.Do(request) + if err != nil { + return nil, errors.New("listing usage artifacts failed") + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return nil, fmt.Errorf("listing usage artifacts returned HTTP %d", response.StatusCode) + } + var listed artifactListResponse + if err := json.NewDecoder(response.Body).Decode(&listed); err != nil { + return nil, fmt.Errorf("decode usage artifact list: %w", err) + } + return listed.Artifacts, nil +} + +func (s *RecordSource) download(ctx context.Context, summary artifactSummary) (server.UsageReport, error) { + endpoint := *s.baseURL + endpoint.Path = strings.TrimRight(endpoint.Path, "/") + + "/repos/" + s.repository + "/actions/artifacts/" + strconv.FormatInt(summary.ID, 10) + "/zip" + + request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil) + if err != nil { + return server.UsageReport{}, err + } + s.authorize(request) + response, err := s.client.Do(request) + if err != nil { + return server.UsageReport{}, errors.New("downloading the usage artifact failed") + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return server.UsageReport{}, fmt.Errorf("downloading the usage artifact returned HTTP %d", response.StatusCode) + } + archive, err := io.ReadAll(io.LimitReader(response.Body, maxRecordBytes+1)) + if err != nil { + return server.UsageReport{}, err + } + if int64(len(archive)) > maxRecordBytes { + return server.UsageReport{}, errors.New("the usage artifact is larger than the record limit") + } + return readUsageArchive(archive) +} + +func readUsageArchive(archive []byte) (server.UsageReport, error) { + reader, err := zip.NewReader(bytes.NewReader(archive), int64(len(archive))) + if err != nil { + return server.UsageReport{}, fmt.Errorf("open usage artifact: %w", err) + } + for _, file := range reader.File { + if file.Name != usageFileName { + continue + } + // Bounded independently of the compressed size, so a small archive + // cannot expand into an unbounded allocation. + entry, err := file.Open() + if err != nil { + return server.UsageReport{}, err + } + data, err := io.ReadAll(io.LimitReader(entry, maxRecordBytes+1)) + closeErr := entry.Close() + if err != nil { + return server.UsageReport{}, err + } + if closeErr != nil { + return server.UsageReport{}, closeErr + } + if int64(len(data)) > maxRecordBytes { + return server.UsageReport{}, errors.New("the usage record is larger than the record limit") + } + var report server.UsageReport + if err := json.Unmarshal(data, &report); err != nil { + return server.UsageReport{}, fmt.Errorf("decode usage record: %w", err) + } + return report, nil + } + return server.UsageReport{}, fmt.Errorf("the artifact holds no %s", usageFileName) +} + +func (s *RecordSource) authorize(request *http.Request) { + request.Header.Set("Accept", "application/vnd.github+json") + request.Header.Set("Authorization", "Bearer "+s.token) + request.Header.Set("X-GitHub-Api-Version", "2022-11-28") +} diff --git a/internal/optimiser/records_test.go b/internal/optimiser/records_test.go new file mode 100644 index 0000000..8603687 --- /dev/null +++ b/internal/optimiser/records_test.go @@ -0,0 +1,324 @@ +package optimiser + +import ( + "archive/zip" + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "strings" + "testing" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/server" +) + +func usageArchive(t *testing.T, report server.UsageReport) []byte { + t.Helper() + var buffer bytes.Buffer + archive := zip.NewWriter(&buffer) + entry, err := archive.Create(usageFileName) + if err != nil { + t.Fatal(err) + } + encoded, err := json.Marshal(report) + if err != nil { + t.Fatal(err) + } + if _, err := entry.Write(encoded); err != nil { + t.Fatal(err) + } + if err := archive.Close(); err != nil { + t.Fatal(err) + } + return buffer.Bytes() +} + +func testSource(t *testing.T, handler http.Handler) *RecordSource { + t.Helper() + service := httptest.NewServer(handler) + t.Cleanup(service.Close) + base, err := url.Parse(service.URL) + if err != nil { + t.Fatal(err) + } + return &RecordSource{ + baseURL: base, + repository: "owner/repo", + token: "test-token", + artifact: "bazel-cache-usage", + client: &http.Client{Timeout: 5 * time.Second}, + } +} + +func TestCollectFoldsRecordsKeyedByRun(t *testing.T) { + archive := usageArchive(t, server.UsageReport{Entries: []server.UsageEntry{ + {Kind: "cas", Digest: "a", Downloads: 1}, + }}) + source := testSource(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("Authorization"); got != "Bearer test-token" { + t.Errorf("authorization = %q", got) + } + if strings.HasSuffix(r.URL.Path, "/artifacts") { + if got := r.URL.Query().Get("name"); got != "bazel-cache-usage" { + t.Errorf("name filter = %q", got) + } + _ = json.NewEncoder(w).Encode(map[string]any{"artifacts": []any{ + sameRepoArtifact(1, 101), + sameRepoArtifact(2, 102), + }}) + return + } + _, _ = w.Write(archive) + })) + + demand := NewDemand() + collected, err := source.Collect(context.Background(), demand, 10, func(string, ...any) {}) + if err != nil { + t.Fatal(err) + } + if collected != 2 || demand.Runs() != 2 { + t.Fatalf("collected %d records over %d runs", collected, demand.Runs()) + } + if got := demand.Signature("cas", "a"); got != "101/1 102/2" { + t.Fatalf("signature = %q", got) + } +} + +// A run started from a fork is outside the repository's trust boundary, so its +// record must not steer the layout. +func TestCollectIgnoresForkRuns(t *testing.T) { + source := testSource(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.HasSuffix(r.URL.Path, "/artifacts") { + t.Errorf("downloaded a fork artifact from %s", r.URL.Path) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"artifacts": []any{ + map[string]any{ + "id": 1, "expired": false, "size_in_bytes": 100, + "workflow_run": map[string]any{"id": 101, "repository_id": 7, "head_repository_id": 9}, + }, + }}) + })) + + demand := NewDemand() + collected, err := source.Collect(context.Background(), demand, 10, func(string, ...any) {}) + if err != nil { + t.Fatal(err) + } + if collected != 0 { + t.Fatalf("collected %d fork records", collected) + } +} + +// One unreadable record must not cost the whole window. +func TestCollectSkipsUnreadableRecords(t *testing.T) { + good := usageArchive(t, server.UsageReport{Entries: []server.UsageEntry{ + {Kind: "cas", Digest: "a", Downloads: 1}, + }}) + source := testSource(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/artifacts") { + _ = json.NewEncoder(w).Encode(map[string]any{"artifacts": []any{ + sameRepoArtifact(1, 101), + sameRepoArtifact(2, 102), + }}) + return + } + if strings.Contains(r.URL.Path, "/1/") { + _, _ = w.Write([]byte("not a zip")) + return + } + _, _ = w.Write(good) + })) + + warnings := 0 + demand := NewDemand() + collected, err := source.Collect(context.Background(), demand, 10, func(string, ...any) { warnings++ }) + if err != nil { + t.Fatal(err) + } + if collected != 1 || warnings != 1 { + t.Fatalf("collected %d records with %d warnings", collected, warnings) + } +} + +func TestReadUsageArchiveRejectsAnArchiveWithoutARecord(t *testing.T) { + var buffer bytes.Buffer + archive := zip.NewWriter(&buffer) + if _, err := archive.Create("something-else.json"); err != nil { + t.Fatal(err) + } + if err := archive.Close(); err != nil { + t.Fatal(err) + } + if _, err := readUsageArchive(buffer.Bytes()); err == nil { + t.Fatal("accepted an archive with no usage record") + } +} + +func sameRepoArtifact(id, run int) map[string]any { + return map[string]any{ + "id": id, "expired": false, "size_in_bytes": 100, + "workflow_run": map[string]any{"id": run, "repository_id": 7, "head_repository_id": 7}, + } +} + +func datedArtifact(id, run int, created time.Time) map[string]any { + artifact := sameRepoArtifact(id, run) + artifact["created_at"] = created.UTC().Format(time.RFC3339) + return artifact +} + +func windowSource(t *testing.T, pages [][]any, archive []byte) (*RecordSource, *[]string) { + t.Helper() + var downloaded []string + source := testSource(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/artifacts") { + page := 1 + if text := r.URL.Query().Get("page"); text != "" { + page, _ = strconv.Atoi(text) + } + artifacts := []any{} + if page <= len(pages) { + artifacts = pages[page-1] + } + _ = json.NewEncoder(w).Encode(map[string]any{"artifacts": artifacts}) + return + } + downloaded = append(downloaded, r.URL.Path) + _, _ = w.Write(archive) + })) + return source, &downloaded +} + +// Eviction reads every record in its window, not just the newest few, and only +// trusts the window once the listing has reached past its start. +func TestCollectWindowReadsEveryRecordSinceItOpened(t *testing.T) { + now := time.Now() + archive := usageArchive(t, server.UsageReport{Entries: []server.UsageEntry{{Kind: "cas", Digest: "a", Downloads: 1}}}) + source, downloaded := windowSource(t, [][]any{{ + datedArtifact(1, 101, now.Add(-time.Hour)), + datedArtifact(2, 102, now.Add(-48*time.Hour)), + datedArtifact(3, 103, now.Add(-100*time.Hour)), + datedArtifact(4, 104, now.Add(-200*time.Hour)), + }}, archive) + + plan, recent := NewDemand(), NewDemand() + collected, coverage, err := source.CollectWindow(context.Background(), plan, 1, + Window{Since: now.Add(-168 * time.Hour), Recent: recent}, func(string, ...any) {}) + if err != nil { + t.Fatal(err) + } + if collected != 1 || plan.Runs() != 1 { + t.Fatalf("planned from %d records", collected) + } + if !coverage.Complete || coverage.Records != 3 || recent.Runs() != 3 { + t.Fatalf("coverage = %+v over %d runs", coverage, recent.Runs()) + } + if len(*downloaded) != 3 { + t.Fatalf("downloaded %v, want only the three records the window or plan needs", *downloaded) + } +} + +// Retention may have deleted older records, so running out is not proof that +// nothing in the window is missing. +func TestCollectWindowIsIncompleteUntilItReachesPastItsStart(t *testing.T) { + now := time.Now() + archive := usageArchive(t, server.UsageReport{}) + source, _ := windowSource(t, [][]any{{datedArtifact(1, 101, now.Add(-time.Hour))}}, archive) + + _, coverage, err := source.CollectWindow(context.Background(), NewDemand(), 25, + Window{Since: now.Add(-168 * time.Hour), Recent: NewDemand()}, func(string, ...any) {}) + if err != nil { + t.Fatal(err) + } + if coverage.Complete || coverage.Gap == "" { + t.Fatalf("coverage = %+v, want incomplete", coverage) + } +} + +// A record in the window that cannot be read could be the one that used an +// entry, so the window is not to be trusted. +func TestCollectWindowIsIncompleteWithAnExpiredRecordInside(t *testing.T) { + now := time.Now() + archive := usageArchive(t, server.UsageReport{}) + expired := datedArtifact(2, 102, now.Add(-48*time.Hour)) + expired["expired"] = true + source, _ := windowSource(t, [][]any{{ + datedArtifact(1, 101, now.Add(-time.Hour)), + expired, + datedArtifact(3, 103, now.Add(-200*time.Hour)), + }}, archive) + + _, coverage, err := source.CollectWindow(context.Background(), NewDemand(), 25, + Window{Since: now.Add(-168 * time.Hour), Recent: NewDemand()}, func(string, ...any) {}) + if err != nil { + t.Fatal(err) + } + if coverage.Complete || !strings.Contains(coverage.Gap, "102") { + t.Fatalf("coverage = %+v, want the expired record named", coverage) + } +} + +func TestCollectWindowPagesThroughTheListing(t *testing.T) { + now := time.Now() + archive := usageArchive(t, server.UsageReport{}) + first := make([]any, 0, artifactsPerPage) + for index := range artifactsPerPage { + first = append(first, datedArtifact(index+1, 1000+index, now.Add(-time.Duration(index+1)*time.Minute))) + } + source, _ := windowSource(t, [][]any{first, {datedArtifact(500, 5000, now.Add(-200*time.Hour))}}, archive) + + _, coverage, err := source.CollectWindow(context.Background(), NewDemand(), 25, + Window{Since: now.Add(-168 * time.Hour), Recent: NewDemand()}, func(string, ...any) {}) + if err != nil { + t.Fatal(err) + } + if !coverage.Complete || coverage.Records != artifactsPerPage { + t.Fatalf("coverage = %+v", coverage) + } +} + +// Every job of a run publishes its own record, usually under the same name. +// Keeping one per run would hide what the others used, and eviction would then +// take it. +func TestCollectKeepsEveryJobsRecordFromOneRun(t *testing.T) { + now := time.Now() + first := usageArchive(t, server.UsageReport{Entries: []server.UsageEntry{{Kind: "cas", Digest: "a", Downloads: 1}}}) + second := usageArchive(t, server.UsageReport{Entries: []server.UsageEntry{{Kind: "cas", Digest: "b", PresenceChecks: 1}}}) + source := testSource(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/artifacts") { + artifacts := []any{} + if r.URL.Query().Get("page") == "1" { + artifacts = []any{ + datedArtifact(1, 101, now.Add(-time.Hour)), + datedArtifact(2, 101, now.Add(-2*time.Hour)), + datedArtifact(3, 100, now.Add(-200*time.Hour)), + } + } + _ = json.NewEncoder(w).Encode(map[string]any{"artifacts": artifacts}) + return + } + if strings.Contains(r.URL.Path, "/2/") { + _, _ = w.Write(second) + return + } + _, _ = w.Write(first) + })) + + recent := NewDemand() + _, coverage, err := source.CollectWindow(context.Background(), NewDemand(), 25, + Window{Since: now.Add(-168 * time.Hour), Recent: recent}, func(string, ...any) {}) + if err != nil { + t.Fatal(err) + } + if !coverage.Complete || coverage.Records != 2 { + t.Fatalf("coverage = %+v, want both jobs' records", coverage) + } + if !recent.Used("cas", "a") || !recent.Used("cas", "b") { + t.Fatal("an entry one job of the run used looks unused") + } +} diff --git a/internal/optimiser/run.go b/internal/optimiser/run.go new file mode 100644 index 0000000..c88a816 --- /dev/null +++ b/internal/optimiser/run.go @@ -0,0 +1,507 @@ +package optimiser + +import ( + "context" + "errors" + "fmt" + "sync" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/cache" + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/server" +) + +// Pruner deletes immutable cache entries by exact key. +type Pruner interface { + Delete(ctx context.Context, key string) error +} + +type RunOptions struct { + Backend cache.Backend + Catalog cache.Catalog + Pruner Pruner + Records *RecordSource + CacheDir string + KeyPrefix string + // MaxRecords bounds the window of runs a plan is built from. + MaxRecords int + MaxBlobSize int64 + Timeout time.Duration + // UploadsPerMinute spaces publications, as the cache server does. + UploadsPerMinute int + // Concurrency is how many packs are rebuilt at once. + Concurrency int + // MaxNewBytes stops a pass once it has published this much. A cache near + // its quota cannot hold the old and new layouts at once, and stopping early + // leaves the remainder for the next pass. + MaxNewBytes int64 + // Reap deletes packs no manifest names at all. Opt-in, because it is the + // one thing here that removes data no replacement was published for. + Reap bool + // ReapOlderThan keeps a pack a running job has published but not yet + // committed a manifest for out of reach. + ReapOlderThan time.Duration + // EvictAfter is how long an entry may go unused before it is evicted from + // its pack. Reshaping waits for packs twice as old, so that a pack is + // cleaned in place a few times between regroupings. Zero disables both + // age gates and eviction. + EvictAfter time.Duration + // Lister reports cache entries' creation times, which stand in for a + // pack's age when its manifest does not record one. + Lister EntryLister + Plan Options + // DryRun plans and reports without publishing or deleting anything. + DryRun bool + Log func(string, ...any) +} + +type Result struct { + Records int + Packs int + Entries int + Rebuilt int + Deleted int + ReclaimedBytes int64 + WastedBytes int64 + // OverfetchBefore and OverfetchAfter are what an average observed job + // downloaded and did not want from the rebuilt packs, and would from their + // replacements. + OverfetchBefore int64 + OverfetchAfter int64 + // DownloadsBefore and DownloadsAfter are how many of those packs an average + // observed job restored, and would restore. + DownloadsBefore float64 + DownloadsAfter float64 + // Unimproved counts wasteful packs left alone because no regrouping found + // would have cut their restore cost enough to be worth the upload. + Unimproved int + // RecordsInWindow counts usage records inside the eviction window, and + // EvictionSkipped says why nothing was evicted when the records were + // incomplete. + RecordsInWindow int + EvictionSkipped string + // Evicted counts packs rewritten on their own to drop EvictedEntries stale + // entries holding EvictedBytes. Abandoned counts packs every entry of which + // is stale, left for GitHub to expire. + Evicted int + EvictedEntries int + EvictedBytes int64 + Abandoned int + // ReshapeEligible counts packs old enough to reshape; ReshapeSkipped says + // why reshaping did not run, when it did not. + ReshapeEligible int + ReshapeSkipped string + DryRun bool + // Unreadable counts manifests the listing reported but this job could not + // restore, so a plan that saw few of them can be recognised as such. + Unreadable int + // PublishedBytes is what this pass added before freeing anything. + PublishedBytes int64 + // Incomplete marks a pass that stopped at its byte budget with work left. + Incomplete bool + // Reaped counts packs removed because no manifest named them. + Reaped int + // Reapable counts packs that passed the age filter, whether or not this + // pass was allowed to delete them. + Reapable int + // Unmanifested counts packs no manifest names, whether or not they were + // reaped. + Unmanifested int + // OrphanManifests counts manifests whose pack is gone; ReapableManifests + // and ReapedManifests are those old enough to reap, and those reaped. + OrphanManifests int + ReapableManifests int + ReapedManifests int + // Skipped explains why a pass did no work. A quiet repository is not a + // failure, and a scheduled pass must not go red for having nothing to do. + Skipped string +} + +// Run collects usage records, plans a repacking, and applies it. Nothing is +// deleted until every replacement pack and manifest is published, so an +// interrupted pass leaves duplicated storage rather than a hole. +func Run(ctx context.Context, options RunOptions) (Result, error) { + if options.Log == nil { + options.Log = func(string, ...any) {} + } + if options.Pruner == nil && !options.DryRun { + return Result{}, errors.New("applying a plan needs a pruner") + } + + layout, err := server.ReadLayout(ctx, server.LayoutOptions{ + Backend: options.Backend, + Catalog: options.Catalog, + KeyPrefix: options.KeyPrefix, + MaxBlobSize: options.MaxBlobSize, + Timeout: options.Timeout, + Warn: options.Log, + }) + if err != nil { + return Result{}, fmt.Errorf("read the stored layout: %w", err) + } + options.Log("layout has %s packs, %s live entries, %s orphaned packs (%s named by no manifest), %s orphaned manifests, %s manifests this job cannot restore", + HumanCount(int64(len(layout.Packs))), HumanCount(int64(len(layout.Entries))), + HumanCount(int64(layout.OrphanPacks)), HumanCount(int64(len(layout.UnmanifestedPacks))), + HumanCount(int64(layout.OrphanManifests)), HumanCount(int64(layout.UnreadableManifests))) + + now := time.Now() + timing := Timing{Now: now} + window := Window{} + if options.EvictAfter > 0 { + timing.EvictAfter = options.EvictAfter + timing.ReshapeAfter = 2 * options.EvictAfter + timing.Ages, err = packAges(ctx, options, layout) + if err != nil { + return Result{}, err + } + window = Window{Since: now.Add(-options.EvictAfter), Recent: NewDemand()} + } + demand := NewDemand() + records, coverage, err := options.Records.CollectWindow(ctx, demand, options.MaxRecords, window, options.Log) + if err != nil { + return Result{}, fmt.Errorf("collect usage records: %w", err) + } + + result := Result{ + Records: records, + RecordsInWindow: coverage.Records, + Packs: len(layout.Packs), + Entries: len(layout.Entries), + Unreadable: layout.UnreadableManifests, + Unmanifested: len(layout.UnmanifestedPacks), + OrphanManifests: layout.OrphanManifests, + DryRun: options.DryRun, + } + // Reaping is independent of any repacking plan: an unmanifested pack is + // unreachable whether or not the rest of the layout is worth rebuilding. A + // dry run still applies the age filter, so its count means something. + if options.Reap { + reapable, reaped, err := reap(ctx, options, layout) + result.Reapable = reapable + result.Reaped = reaped + if err != nil { + return result, err + } + if options.DryRun { + options.Log("%d packs no manifest names are old enough to reap", reapable) + } else { + options.Log("reaped %d packs no manifest names", reaped) + } + + // Readers already skip these, so failing to remove one costs only the + // quota it holds until it expires; it is no reason to stop the pass. + reapable, reaped, err = reapManifests(ctx, options, layout) + result.ReapableManifests = reapable + result.ReapedManifests = reaped + switch { + case err != nil: + options.Log("could not reap every manifest whose pack is gone: %v", err) + case options.DryRun: + options.Log("%d manifests whose pack is gone are old enough to reap", reapable) + default: + options.Log("reaped %d manifests whose pack is gone", reaped) + } + } + if options.EvictAfter > 0 { + if coverage.Complete { + timing.Recent = window.Recent + } else { + result.EvictionSkipped = coverage.Gap + options.Log("evicting nothing: %s, so an entry that looks unused may not be", coverage.Gap) + } + } + plan, err := NewTimedPlan(layout, demand, options.Plan, timing) + if errors.Is(err, errTooFewRuns) { + result.Skipped = err.Error() + options.Log("%s; leaving the layout alone", err) + return result, nil + } + if err != nil { + return result, err + } + result.ReclaimedBytes = plan.ReclaimedBytes + result.WastedBytes = plan.WastedBytes + result.OverfetchBefore = plan.OverfetchBefore + result.OverfetchAfter = plan.OverfetchAfter + result.DownloadsBefore = plan.DownloadsBefore + result.DownloadsAfter = plan.DownloadsAfter + result.Unimproved = plan.Unimproved + result.Evicted = plan.Evicted + result.EvictedEntries = plan.EvictedEntries + result.EvictedBytes = plan.EvictedBytes + result.Abandoned = plan.Abandoned + result.ReshapeEligible = plan.ReshapeEligible + result.ReshapeSkipped = plan.ReshapeSkipped + if plan.Abandoned > 0 { + options.Log("left %d packs alone that nothing has used for %s; GitHub expires them unread", plan.Abandoned, options.EvictAfter) + } + if plan.ReshapeSkipped != "" { + options.Log("not reshaping: %s", plan.ReshapeSkipped) + } + if plan.Unimproved > 0 { + options.Log("left %d wasteful packs alone: no regrouping found would cut their overfetch by %.0f%% for jobs it was not fitted to", + plan.Unimproved, options.Plan.MinImprovement*100) + } + if plan.Empty() { + result.Skipped = "every pack is already grouped for how it is read" + options.Log("%s; nothing to do", result.Skipped) + return result, nil + } + options.Log("evicting %s stale entries (%s) from %d packs, each rewritten on its own", + HumanCount(int64(plan.EvictedEntries)), HumanBytes(plan.EvictedBytes), plan.Evicted) + options.Log("reshaping %d of %d packs old enough into %d; per job, overfetch %s -> %s and downloads %.1f -> %.1f", + len(plan.Rewrite)-plan.Evicted, plan.ReshapeEligible, len(plan.Groups)-plan.Evicted, + HumanBytes(plan.OverfetchBefore), HumanBytes(plan.OverfetchAfter), plan.DownloadsBefore, plan.DownloadsAfter) + options.Log("deleting %d empty packs; %s reclaimed", len(plan.Dead), HumanBytes(plan.ReclaimedBytes)) + if options.DryRun { + return result, nil + } + + repacker, err := server.NewRepacker(server.RepackOptions{ + Backend: options.Backend, + CacheDir: options.CacheDir, + KeyPrefix: options.KeyPrefix, + MaxBlobSize: options.MaxBlobSize, + Timeout: options.Timeout, + UploadsPerMinute: options.UploadsPerMinute, + Parents: layout.Heads, + Packs: layout.Packs, + }) + if err != nil { + return result, err + } + defer repacker.Close() + + remover := newRemover(ctx, options, layout) + // Dead packs hold nothing that is served, so removing them before anything + // is published frees quota rather than adding to the peak. + for _, packID := range plan.Dead { + if err := remover.remove(packID); err != nil { + return result, err + } + } + + // A source pack can go as soon as every entry it served has been + // republished, which keeps the old and new layouts from both being resident + // in full. + outstanding := make(map[string]int, len(plan.Rewrite)) + for _, group := range plan.Groups { + for _, entry := range group.Entries { + outstanding[entry.Pack]++ + } + } + + newBytes, err := publishGroups(ctx, options, plan.Groups, repacker, func(group Group, pack server.LayoutPack, manifestID string) error { + remover.republished(pack.Key) + remover.republished(server.ManifestKey(options.KeyPrefix, pack.ID, manifestID)) + result.Rebuilt++ + if group.Evicts != "" { + options.Log("published pack %s with %d entries under manifest %s, replacing %s without its stale entries", + pack.ID, len(group.Entries), manifestID, group.Evicts) + } else { + options.Log("published pack %s with %d entries under manifest %s", pack.ID, len(group.Entries), manifestID) + } + for _, entry := range group.Entries { + outstanding[entry.Pack]-- + if outstanding[entry.Pack] > 0 { + continue + } + delete(outstanding, entry.Pack) + repacker.Release(entry.Pack) + if err := remover.remove(entry.Pack); err != nil { + return err + } + } + return nil + }, &result.Incomplete) + result.Deleted = remover.deleted + result.PublishedBytes = newBytes + return result, err +} + +// packAges is when each pack's contents took their current shape: what its +// manifest records, or failing that when its cache entry was created. A pack +// with neither is left out, and so treated as brand new. +func packAges(ctx context.Context, options RunOptions, layout server.Layout) (map[string]time.Time, error) { + ages := make(map[string]time.Time, len(layout.Packs)) + var created map[string]time.Time + for _, pack := range layout.Packs { + if !pack.Since.IsZero() { + ages[pack.ID] = pack.Since + continue + } + if created == nil { + created = make(map[string]time.Time) + if options.Lister != nil { + entries, err := options.Lister.ListEntries(ctx, server.PackKeyPrefix(options.KeyPrefix)) + if err != nil { + return nil, fmt.Errorf("list packs for their ages: %w", err) + } + for _, entry := range entries { + created[entry.Key] = entry.CreatedAt + } + } + } + if at, known := created[pack.Key]; known && !at.IsZero() { + ages[pack.ID] = at + } + } + return ages, nil +} + +// publisher is the part of the repacker publishGroups drives. +type publisher interface { + Publish(ctx context.Context, entries []server.LayoutEntry, since time.Time) (server.LayoutPack, string, error) +} + +// publishGroups builds and uploads groups on several workers at once, since a +// pack spends most of its time waiting on downloads and uploads rather than on +// the upload rate limit. done runs on this goroutine, one group at a time, so +// whatever it deletes is decided by completed publications only. It stops +// dispatching once the byte budget is spent or anything fails, and lets work +// already started finish. +func publishGroups( + ctx context.Context, + options RunOptions, + groups []Group, + repacker publisher, + done func(Group, server.LayoutPack, string) error, + incomplete *bool, +) (int64, error) { + workers := max(options.Concurrency, 1) + publishCtx, cancel := context.WithCancel(ctx) + defer cancel() + + type outcome struct { + index int + pack server.LayoutPack + manifestID string + err error + } + jobs := make(chan int) + results := make(chan outcome, workers) + var wait sync.WaitGroup + for range workers { + wait.Add(1) + go func() { + defer wait.Done() + for index := range jobs { + pack, manifestID, err := repacker.Publish(publishCtx, groups[index].Entries, groups[index].Since) + results <- outcome{index: index, pack: pack, manifestID: manifestID, err: err} + } + }() + } + defer func() { + close(jobs) + wait.Wait() + }() + + var newBytes, pendingBytes int64 + var failure error + next, running := 0, 0 + for { + for failure == nil && running < workers && next < len(groups) { + // Counting work in flight keeps parallel workers from all starting + // just under the budget and overshooting it together. + if options.MaxNewBytes > 0 && newBytes+pendingBytes >= options.MaxNewBytes { + *incomplete = true + break + } + jobs <- next + pendingBytes += groups[next].Bytes + next++ + running++ + } + if running == 0 { + break + } + finished := <-results + running-- + pendingBytes -= groups[finished.index].Bytes + if failure != nil { + // Anything still finishing after a failure only duplicates entries + // the originals still serve, so it is left in place untouched. + continue + } + if finished.err != nil { + // Whatever was published already stays: it duplicates entries the + // originals still serve, and the originals are still there. + failure = fmt.Errorf("publish rebuilt pack %d of %d: %w", finished.index+1, len(groups), finished.err) + cancel() + continue + } + newBytes += finished.pack.StoredSize + if err := done(groups[finished.index], finished.pack, finished.manifestID); err != nil { + failure = err + cancel() + } + } + if *incomplete && failure == nil { + // Stopping early is safe: the packs still to be rebuilt were never + // touched, so they keep serving. The next pass re-plans. + options.Log("stopping after %d of %d packs, having published %s this pass", + next, len(groups), HumanBytes(newBytes)) + } + return newBytes, failure +} + +// remover deletes a pack and the manifests describing it. A pack is only +// reachable through a manifest that names it, and a manifest whose pack is gone +// is skipped and left to expire, so the pack is what has to go. +type remover struct { + ctx context.Context + options RunOptions + packs map[string]server.LayoutPack + manifests map[string][]server.LayoutManifest + // Packs are content-addressed, so a group that reproduces an existing pack + // byte for byte republishes under the key about to be deleted. Keys written + // by this pass are never removed. + written map[string]struct{} + deleted int +} + +func newRemover(ctx context.Context, options RunOptions, layout server.Layout) *remover { + packs := make(map[string]server.LayoutPack, len(layout.Packs)) + for _, pack := range layout.Packs { + packs[pack.ID] = pack + } + manifests := make(map[string][]server.LayoutManifest, len(layout.Manifests)) + for _, reference := range layout.Manifests { + manifests[reference.Pack] = append(manifests[reference.Pack], reference) + } + return &remover{ + ctx: ctx, + options: options, + packs: packs, + manifests: manifests, + written: make(map[string]struct{}), + } +} + +func (r *remover) republished(key string) { r.written[key] = struct{}{} } + +func (r *remover) remove(packID string) error { + pack, known := r.packs[packID] + if !known { + return fmt.Errorf("no descriptor for pack %s", packID) + } + if _, written := r.written[pack.Key]; written { + r.options.Log("keeping pack %s: the rebuild reproduced it exactly", packID) + } else { + if err := r.options.Pruner.Delete(r.ctx, pack.Key); err != nil { + return fmt.Errorf("delete replaced pack %s: %w", packID, err) + } + r.deleted++ + } + // Tidiness only, and safe in either order: an orphaned manifest is already + // skipped by readers. + for _, reference := range r.manifests[packID] { + if _, written := r.written[reference.Key]; written { + continue + } + if err := r.options.Pruner.Delete(r.ctx, reference.Key); err != nil { + r.options.Log("could not delete superseded manifest %s: %v", reference.ID, err) + } + } + return nil +} diff --git a/internal/optimiser/run_test.go b/internal/optimiser/run_test.go new file mode 100644 index 0000000..44b9632 --- /dev/null +++ b/internal/optimiser/run_test.go @@ -0,0 +1,221 @@ +package optimiser + +import ( + "context" + "errors" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/server" +) + +type recordingPruner struct { + deleted []string + err error +} + +func (p *recordingPruner) Delete(_ context.Context, key string) error { + if p.err != nil { + return p.err + } + p.deleted = append(p.deleted, key) + return nil +} + +func layoutWith(packs []server.LayoutPack, manifests []server.LayoutManifest) server.Layout { + return server.Layout{Packs: packs, Manifests: manifests} +} + +// A scheduled pass runs whether or not the repository was busy, so having too +// little to plan from has to be a clean no-op rather than a red workflow. +func TestTooFewRecordsIsReportedNotFailed(t *testing.T) { + demand := NewDemand() + demand.Observe("run-1", server.UsageReport{}) + + _, err := NewPlan(server.Layout{}, demand, Options{TargetPackSize: 1024, MinRuns: 3}) + if !errors.Is(err, errTooFewRuns) { + t.Fatalf("error = %v, want errTooFewRuns", err) + } +} + +// Packs are content addressed, so a rebuild that reproduces one exactly +// republishes under the very key about to be deleted. +func TestRemoverKeepsAPackTheRebuildReproduced(t *testing.T) { + pruner := &recordingPruner{} + layout := layoutWith( + []server.LayoutPack{ + {ID: "same", Key: "prefix-car-pack-v1-same"}, + {ID: "other", Key: "prefix-car-pack-v1-other"}, + }, + []server.LayoutManifest{ + {ID: "m1", Key: "prefix-car-manifest-v2-same-m1", Pack: "same"}, + {ID: "m2", Key: "prefix-car-manifest-v2-other-m2", Pack: "other"}, + }, + ) + options := RunOptions{Pruner: pruner, Log: func(string, ...any) {}} + remover := newRemover(context.Background(), options, layout) + remover.republished("prefix-car-pack-v1-same") + + for _, packID := range []string{"same", "other"} { + if err := remover.remove(packID); err != nil { + t.Fatal(err) + } + } + if remover.deleted != 1 { + t.Fatalf("deleted %d packs", remover.deleted) + } + for _, key := range pruner.deleted { + if key == "prefix-car-pack-v1-same" { + t.Fatal("deleted the pack the rebuild had just republished") + } + } +} + +func TestRemoverTakesTheManifestsDescribingAPack(t *testing.T) { + pruner := &recordingPruner{} + layout := layoutWith( + []server.LayoutPack{ + {ID: "kept", Key: "prefix-car-pack-v1-kept"}, + {ID: "dead", Key: "prefix-car-pack-v1-dead"}, + }, + []server.LayoutManifest{ + {ID: "m1", Key: "prefix-car-manifest-v2-kept-m1", Pack: "kept"}, + {ID: "m2", Key: "prefix-car-manifest-v2-dead-m2", Pack: "dead"}, + }, + ) + options := RunOptions{Pruner: pruner, Log: func(string, ...any) {}} + remover := newRemover(context.Background(), options, layout) + if err := remover.remove("dead"); err != nil { + t.Fatal(err) + } + for _, key := range pruner.deleted { + if key == "prefix-car-pack-v1-kept" || key == "prefix-car-manifest-v2-kept-m1" { + t.Fatalf("deleted %s, which was not being replaced", key) + } + } + if len(pruner.deleted) != 2 { + t.Fatalf("deleted %v", pruner.deleted) + } +} + +// A pack that will not delete must stop the pass rather than leave the rest of +// the old layout half removed under a silent failure. +func TestRemoverStopsOnAFailedPackDeletion(t *testing.T) { + pruner := &recordingPruner{err: errors.New("no permission")} + layout := layoutWith( + []server.LayoutPack{{ID: "dead", Key: "prefix-car-pack-v1-dead"}}, + nil, + ) + options := RunOptions{Pruner: pruner, Log: func(string, ...any) {}} + remover := newRemover(context.Background(), options, layout) + if err := remover.remove("dead"); err == nil { + t.Fatal("a failed deletion was ignored") + } +} + +// fakePublisher publishes instantly or after a delay, and records how many +// publications overlapped. +type fakePublisher struct { + mu sync.Mutex + delay time.Duration + failAt int + calls int + running int + peak int +} + +func (p *fakePublisher) Publish(ctx context.Context, entries []server.LayoutEntry, _ time.Time) (server.LayoutPack, string, error) { + p.mu.Lock() + p.calls++ + call := p.calls + p.running++ + p.peak = max(p.peak, p.running) + p.mu.Unlock() + defer func() { + p.mu.Lock() + p.running-- + p.mu.Unlock() + }() + select { + case <-time.After(p.delay): + case <-ctx.Done(): + return server.LayoutPack{}, "", ctx.Err() + } + if call == p.failAt { + return server.LayoutPack{}, "", errors.New("upload refused") + } + var size int64 + for _, entry := range entries { + size += entry.Size + } + return server.LayoutPack{ID: entries[0].Digest, Key: "pack-" + entries[0].Digest, StoredSize: size}, "manifest", nil +} + +func groupsOf(count int, size int64) []Group { + groups := make([]Group, 0, count) + for index := range count { + entries := entriesFor("source-"+strconv.Itoa(index), "cas", 1, size) + groups = append(groups, Group{Kind: "cas", Entries: entries, Bytes: size}) + } + return groups +} + +// A pack mostly waits on the network, so rebuilding them one at a time is what +// made a pass take most of half an hour. +func TestPublishGroupsRunsSeveralAtOnce(t *testing.T) { + publisher := &fakePublisher{delay: 20 * time.Millisecond} + options := RunOptions{Concurrency: 4, Log: func(string, ...any) {}} + var incomplete bool + var finished int + published, err := publishGroups(context.Background(), options, groupsOf(12, 100), publisher, + func(Group, server.LayoutPack, string) error { finished++; return nil }, &incomplete) + if err != nil { + t.Fatal(err) + } + if finished != 12 || published != 1200 || incomplete { + t.Fatalf("finished %d, published %d, incomplete %v", finished, published, incomplete) + } + if publisher.peak != 4 { + t.Fatalf("at most %d publications overlapped, want 4", publisher.peak) + } +} + +// Work in flight counts against the budget, or every worker would start just +// under it and overshoot together. +func TestPublishGroupsStopsAtTheByteBudget(t *testing.T) { + publisher := &fakePublisher{delay: 5 * time.Millisecond} + options := RunOptions{Concurrency: 4, MaxNewBytes: 250, Log: func(string, ...any) {}} + var incomplete bool + published, err := publishGroups(context.Background(), options, groupsOf(10, 100), publisher, + func(Group, server.LayoutPack, string) error { return nil }, &incomplete) + if err != nil { + t.Fatal(err) + } + if !incomplete || publisher.calls != 3 || published != 300 { + t.Fatalf("calls %d, published %d, incomplete %v; want 3 packs then a stop", publisher.calls, published, incomplete) + } +} + +// Nothing may be deleted on the strength of a publication that failed, and no +// more work starts once one has. +func TestPublishGroupsStopsOnAFailure(t *testing.T) { + publisher := &fakePublisher{delay: 5 * time.Millisecond, failAt: 3} + options := RunOptions{Concurrency: 2, Log: func(string, ...any) {}} + var incomplete bool + var done []string + _, err := publishGroups(context.Background(), options, groupsOf(20, 100), publisher, + func(_ Group, pack server.LayoutPack, _ string) error { done = append(done, pack.ID); return nil }, &incomplete) + if err == nil || !strings.Contains(err.Error(), "upload refused") { + t.Fatalf("error = %v", err) + } + // Each worker can have started one more before the failure was seen. + if publisher.calls > 3+options.Concurrency { + t.Fatalf("%d publications started, want dispatch to stop at the failure", publisher.calls) + } + if len(done) > 2+options.Concurrency { + t.Fatalf("%d publications were acted on after the failure", len(done)) + } +} diff --git a/internal/optimiser/runset.go b/internal/optimiser/runset.go new file mode 100644 index 0000000..8937a4c --- /dev/null +++ b/internal/optimiser/runset.go @@ -0,0 +1,68 @@ +package optimiser + +import ( + "encoding/binary" + "math/bits" +) + +// runSet is a set of observed runs, numbered by Demand.index. +type runSet []uint64 + +func newRunSet(runs int) runSet { return make(runSet, (runs+63)/64) } + +func (s runSet) add(at int) { s[at/64] |= 1 << (at % 64) } +func (s runSet) has(at int) bool { return s[at/64]&(1<<(at%64)) != 0 } + +func (s runSet) count() int { + total := 0 + for _, word := range s { + total += bits.OnesCount64(word) + } + return total +} + +func (s runSet) empty() bool { + for _, word := range s { + if word != 0 { + return false + } + } + return true +} + +// without counts the runs in s that are not in other. +func (s runSet) without(other runSet) int { + total := 0 + for at, word := range s { + total += bits.OnesCount64(word &^ other[at]) + } + return total +} + +func (s runSet) union(other runSet) { + for at := range s { + s[at] |= other[at] + } +} + +func (s runSet) clone() runSet { return append(runSet(nil), s...) } + +func (s runSet) key() string { + buffer := make([]byte, 8*len(s)) + for at, word := range s { + binary.LittleEndian.PutUint64(buffer[8*at:], word) + } + return string(buffer) +} + +// before orders sets by their lowest differing run, the set holding it first. +// Runs are numbered busiest first, so this nests sets under the jobs that +// restore the most, which keeps sets that share those jobs adjacent. +func (s runSet) before(other runSet) bool { + for at, word := range s { + if differ := word ^ other[at]; differ != 0 { + return word&(differ&-differ) != 0 + } + } + return false +} diff --git a/internal/proto/gen/build/bazel/remote/asset/v1/remote_asset.pb.go b/internal/proto/gen/build/bazel/remote/asset/v1/remote_asset.pb.go new file mode 100644 index 0000000..88a4f24 --- /dev/null +++ b/internal/proto/gen/build/bazel/remote/asset/v1/remote_asset.pb.go @@ -0,0 +1,1575 @@ +// Copyright 2020 The Bazel Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.12 +// protoc (unknown) +// source: build/bazel/remote/asset/v1/remote_asset.proto + +package remoteasset + +import ( + v2 "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/execution/v2" + _ "google.golang.org/genproto/googleapis/api/annotations" + status "google.golang.org/genproto/googleapis/rpc/status" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + durationpb "google.golang.org/protobuf/types/known/durationpb" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" + reflect "reflect" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// Qualifiers are used to disambiguate or sub-select content that shares a URI. +// This may include specifying a particular commit or branch, in the case of +// URIs referencing a repository; they could also be used to specify a +// particular subdirectory of a repository or tarball. Qualifiers may also be +// used to ensure content matches what the client expects, even when there is +// no ambiguity to be had - for example, a qualifier specifying a checksum +// value. +// +// In cases where the semantics of the request are not immediately clear from +// the URL and/or qualifiers - e.g. dictated by URL scheme - it is recommended +// to use an additional qualifier to remove the ambiguity. The `resource_type` +// qualifier is recommended for this purpose. +// +// Qualifiers may be supplied in any order. +type Qualifier struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Name string `protobuf:"bytes,1,opt,name=name,proto3"` + xxx_hidden_Value string `protobuf:"bytes,2,opt,name=value,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Qualifier) Reset() { + *x = Qualifier{} + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Qualifier) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Qualifier) ProtoMessage() {} + +func (x *Qualifier) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *Qualifier) GetName() string { + if x != nil { + return x.xxx_hidden_Name + } + return "" +} + +func (x *Qualifier) GetValue() string { + if x != nil { + return x.xxx_hidden_Value + } + return "" +} + +func (x *Qualifier) SetName(v string) { + x.xxx_hidden_Name = v +} + +func (x *Qualifier) SetValue(v string) { + x.xxx_hidden_Value = v +} + +type Qualifier_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The "name" of the qualifier, for example "resource_type". + // No separation is made between 'standard' and 'nonstandard' + // qualifiers, in accordance with https://tools.ietf.org/html/rfc6648, + // however implementers *SHOULD* take care to avoid ambiguity. + Name string + // The "value" of the qualifier. Semantics will be dictated by the name. + Value string +} + +func (b0 Qualifier_builder) Build() *Qualifier { + m0 := &Qualifier{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Name = b.Name + x.xxx_hidden_Value = b.Value + return m0 +} + +// A request message for +// [Fetch.FetchBlob][build.bazel.remote.asset.v1.Fetch.FetchBlob]. +type FetchBlobRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3"` + xxx_hidden_Timeout *durationpb.Duration `protobuf:"bytes,2,opt,name=timeout,proto3"` + xxx_hidden_OldestContentAccepted *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=oldest_content_accepted,json=oldestContentAccepted,proto3"` + xxx_hidden_Uris []string `protobuf:"bytes,4,rep,name=uris,proto3"` + xxx_hidden_Qualifiers *[]*Qualifier `protobuf:"bytes,5,rep,name=qualifiers,proto3"` + xxx_hidden_DigestFunction v2.DigestFunction_Value `protobuf:"varint,6,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FetchBlobRequest) Reset() { + *x = FetchBlobRequest{} + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FetchBlobRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FetchBlobRequest) ProtoMessage() {} + +func (x *FetchBlobRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *FetchBlobRequest) GetInstanceName() string { + if x != nil { + return x.xxx_hidden_InstanceName + } + return "" +} + +func (x *FetchBlobRequest) GetTimeout() *durationpb.Duration { + if x != nil { + return x.xxx_hidden_Timeout + } + return nil +} + +func (x *FetchBlobRequest) GetOldestContentAccepted() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_OldestContentAccepted + } + return nil +} + +func (x *FetchBlobRequest) GetUris() []string { + if x != nil { + return x.xxx_hidden_Uris + } + return nil +} + +func (x *FetchBlobRequest) GetQualifiers() []*Qualifier { + if x != nil { + if x.xxx_hidden_Qualifiers != nil { + return *x.xxx_hidden_Qualifiers + } + } + return nil +} + +func (x *FetchBlobRequest) GetDigestFunction() v2.DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return v2.DigestFunction_Value(0) +} + +func (x *FetchBlobRequest) SetInstanceName(v string) { + x.xxx_hidden_InstanceName = v +} + +func (x *FetchBlobRequest) SetTimeout(v *durationpb.Duration) { + x.xxx_hidden_Timeout = v +} + +func (x *FetchBlobRequest) SetOldestContentAccepted(v *timestamppb.Timestamp) { + x.xxx_hidden_OldestContentAccepted = v +} + +func (x *FetchBlobRequest) SetUris(v []string) { + x.xxx_hidden_Uris = v +} + +func (x *FetchBlobRequest) SetQualifiers(v []*Qualifier) { + x.xxx_hidden_Qualifiers = &v +} + +func (x *FetchBlobRequest) SetDigestFunction(v v2.DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +func (x *FetchBlobRequest) HasTimeout() bool { + if x == nil { + return false + } + return x.xxx_hidden_Timeout != nil +} + +func (x *FetchBlobRequest) HasOldestContentAccepted() bool { + if x == nil { + return false + } + return x.xxx_hidden_OldestContentAccepted != nil +} + +func (x *FetchBlobRequest) ClearTimeout() { + x.xxx_hidden_Timeout = nil +} + +func (x *FetchBlobRequest) ClearOldestContentAccepted() { + x.xxx_hidden_OldestContentAccepted = nil +} + +type FetchBlobRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + InstanceName string + // The timeout for the underlying fetch, if content needs to be retrieved from + // origin. + // + // If unset, the server *MAY* apply an implementation-defined timeout. + // + // If set, and the user-provided timeout exceeds the RPC deadline, the server + // *SHOULD* keep the fetch going after the RPC completes, to be made + // available for future Fetch calls. The server may also enforce (via clamping + // and/or an INVALID_ARGUMENT error) implementation-defined minimum and + // maximum timeout values. + // + // If this timeout is exceeded on an attempt to retrieve content from origin + // the client will receive DEADLINE_EXCEEDED in [FetchBlobResponse.status]. + Timeout *durationpb.Duration + // The oldest content the client is willing to accept, as measured from the + // time it was Push'd or when the underlying retrieval from origin was + // started. + // Upon retries of Fetch requests that cannot be completed within a single + // RPC, clients *SHOULD* provide the same value for subsequent requests as the + // original, to simplify combining the request with the previous attempt. + // + // If unset, the client *SHOULD* accept content of any age. + OldestContentAccepted *timestamppb.Timestamp + // The URI(s) of the content to fetch. These may be resources that the server + // can directly fetch from origin, in which case multiple URIs *SHOULD* + // represent the same content available at different locations (such as an + // origin and secondary mirrors). These may also be URIs for content known to + // the server through other mechanisms, e.g. pushed via the [Push][build.bazel.remote.asset.v1.Push] + // service. + // + // Clients *MUST* supply at least one URI. Servers *MAY* match any one of the + // supplied URIs. + Uris []string + // Qualifiers sub-specifying the content to fetch - see comments on + // [Qualifier][build.bazel.remote.asset.v1.Qualifier]. + // The same qualifiers apply to all URIs. + // + // Specified qualifier names *MUST* be unique. + Qualifiers []*Qualifier + // The digest function the server must use to compute the digest. + // + // If unset, the server SHOULD default to SHA256. + DigestFunction v2.DigestFunction_Value +} + +func (b0 FetchBlobRequest_builder) Build() *FetchBlobRequest { + m0 := &FetchBlobRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_InstanceName = b.InstanceName + x.xxx_hidden_Timeout = b.Timeout + x.xxx_hidden_OldestContentAccepted = b.OldestContentAccepted + x.xxx_hidden_Uris = b.Uris + x.xxx_hidden_Qualifiers = &b.Qualifiers + x.xxx_hidden_DigestFunction = b.DigestFunction + return m0 +} + +// A response message for +// [Fetch.FetchBlob][build.bazel.remote.asset.v1.Fetch.FetchBlob]. +type FetchBlobResponse struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Status *status.Status `protobuf:"bytes,1,opt,name=status,proto3"` + xxx_hidden_Uri string `protobuf:"bytes,2,opt,name=uri,proto3"` + xxx_hidden_Qualifiers *[]*Qualifier `protobuf:"bytes,3,rep,name=qualifiers,proto3"` + xxx_hidden_ExpiresAt *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=expires_at,json=expiresAt,proto3"` + xxx_hidden_BlobDigest *v2.Digest `protobuf:"bytes,5,opt,name=blob_digest,json=blobDigest,proto3"` + xxx_hidden_DigestFunction v2.DigestFunction_Value `protobuf:"varint,6,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FetchBlobResponse) Reset() { + *x = FetchBlobResponse{} + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FetchBlobResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FetchBlobResponse) ProtoMessage() {} + +func (x *FetchBlobResponse) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *FetchBlobResponse) GetStatus() *status.Status { + if x != nil { + return x.xxx_hidden_Status + } + return nil +} + +func (x *FetchBlobResponse) GetUri() string { + if x != nil { + return x.xxx_hidden_Uri + } + return "" +} + +func (x *FetchBlobResponse) GetQualifiers() []*Qualifier { + if x != nil { + if x.xxx_hidden_Qualifiers != nil { + return *x.xxx_hidden_Qualifiers + } + } + return nil +} + +func (x *FetchBlobResponse) GetExpiresAt() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_ExpiresAt + } + return nil +} + +func (x *FetchBlobResponse) GetBlobDigest() *v2.Digest { + if x != nil { + return x.xxx_hidden_BlobDigest + } + return nil +} + +func (x *FetchBlobResponse) GetDigestFunction() v2.DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return v2.DigestFunction_Value(0) +} + +func (x *FetchBlobResponse) SetStatus(v *status.Status) { + x.xxx_hidden_Status = v +} + +func (x *FetchBlobResponse) SetUri(v string) { + x.xxx_hidden_Uri = v +} + +func (x *FetchBlobResponse) SetQualifiers(v []*Qualifier) { + x.xxx_hidden_Qualifiers = &v +} + +func (x *FetchBlobResponse) SetExpiresAt(v *timestamppb.Timestamp) { + x.xxx_hidden_ExpiresAt = v +} + +func (x *FetchBlobResponse) SetBlobDigest(v *v2.Digest) { + x.xxx_hidden_BlobDigest = v +} + +func (x *FetchBlobResponse) SetDigestFunction(v v2.DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +func (x *FetchBlobResponse) HasStatus() bool { + if x == nil { + return false + } + return x.xxx_hidden_Status != nil +} + +func (x *FetchBlobResponse) HasExpiresAt() bool { + if x == nil { + return false + } + return x.xxx_hidden_ExpiresAt != nil +} + +func (x *FetchBlobResponse) HasBlobDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_BlobDigest != nil +} + +func (x *FetchBlobResponse) ClearStatus() { + x.xxx_hidden_Status = nil +} + +func (x *FetchBlobResponse) ClearExpiresAt() { + x.xxx_hidden_ExpiresAt = nil +} + +func (x *FetchBlobResponse) ClearBlobDigest() { + x.xxx_hidden_BlobDigest = nil +} + +type FetchBlobResponse_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // If the status has a code other than `OK`, it indicates that the operation + // was unable to be completed for reasons outside the servers' control. + // The possible fetch errors include: + // - `DEADLINE_EXCEEDED`: The operation could not be completed within the + // specified timeout. + // - `NOT_FOUND`: The requested asset was not found at the specified location. + // - `PERMISSION_DENIED`: The request was rejected by a remote server, or + // requested an asset from a disallowed origin. + // - `ABORTED`: The operation could not be completed, typically due to a + // failed consistency check. + // - `RESOURCE_EXHAUSTED`: There is insufficient quota of some resource to + // perform the requested operation. The client may retry after a delay. + Status *status.Status + // The uri from the request that resulted in a successful retrieval, or from + // which the error indicated in `status` was obtained. + Uri string + // Any qualifiers known to the server and of interest to clients. + Qualifiers []*Qualifier + // A minimum timestamp the content is expected to be available through. + // Servers *MAY* omit this field, if not known with confidence. + ExpiresAt *timestamppb.Timestamp + // The result of the fetch, if the status had code `OK`. + // The digest of the file's contents, available for download through the CAS. + BlobDigest *v2.Digest + // This field SHOULD be set to the digest function that was used by the server + // to compute [FetchBlobResponse.blob_digest]. + // Clients could use this to determine whether the server honors + // [FetchBlobRequest.digest_function] that was set in the request. + // + // If unset, clients SHOULD default to use SHA256 regardless of the requested + // [FetchBlobRequest.digest_function]. + DigestFunction v2.DigestFunction_Value +} + +func (b0 FetchBlobResponse_builder) Build() *FetchBlobResponse { + m0 := &FetchBlobResponse{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Status = b.Status + x.xxx_hidden_Uri = b.Uri + x.xxx_hidden_Qualifiers = &b.Qualifiers + x.xxx_hidden_ExpiresAt = b.ExpiresAt + x.xxx_hidden_BlobDigest = b.BlobDigest + x.xxx_hidden_DigestFunction = b.DigestFunction + return m0 +} + +// A request message for +// [Fetch.FetchDirectory][build.bazel.remote.asset.v1.Fetch.FetchDirectory]. +type FetchDirectoryRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3"` + xxx_hidden_Timeout *durationpb.Duration `protobuf:"bytes,2,opt,name=timeout,proto3"` + xxx_hidden_OldestContentAccepted *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=oldest_content_accepted,json=oldestContentAccepted,proto3"` + xxx_hidden_Uris []string `protobuf:"bytes,4,rep,name=uris,proto3"` + xxx_hidden_Qualifiers *[]*Qualifier `protobuf:"bytes,5,rep,name=qualifiers,proto3"` + xxx_hidden_DigestFunction v2.DigestFunction_Value `protobuf:"varint,6,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FetchDirectoryRequest) Reset() { + *x = FetchDirectoryRequest{} + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FetchDirectoryRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FetchDirectoryRequest) ProtoMessage() {} + +func (x *FetchDirectoryRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *FetchDirectoryRequest) GetInstanceName() string { + if x != nil { + return x.xxx_hidden_InstanceName + } + return "" +} + +func (x *FetchDirectoryRequest) GetTimeout() *durationpb.Duration { + if x != nil { + return x.xxx_hidden_Timeout + } + return nil +} + +func (x *FetchDirectoryRequest) GetOldestContentAccepted() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_OldestContentAccepted + } + return nil +} + +func (x *FetchDirectoryRequest) GetUris() []string { + if x != nil { + return x.xxx_hidden_Uris + } + return nil +} + +func (x *FetchDirectoryRequest) GetQualifiers() []*Qualifier { + if x != nil { + if x.xxx_hidden_Qualifiers != nil { + return *x.xxx_hidden_Qualifiers + } + } + return nil +} + +func (x *FetchDirectoryRequest) GetDigestFunction() v2.DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return v2.DigestFunction_Value(0) +} + +func (x *FetchDirectoryRequest) SetInstanceName(v string) { + x.xxx_hidden_InstanceName = v +} + +func (x *FetchDirectoryRequest) SetTimeout(v *durationpb.Duration) { + x.xxx_hidden_Timeout = v +} + +func (x *FetchDirectoryRequest) SetOldestContentAccepted(v *timestamppb.Timestamp) { + x.xxx_hidden_OldestContentAccepted = v +} + +func (x *FetchDirectoryRequest) SetUris(v []string) { + x.xxx_hidden_Uris = v +} + +func (x *FetchDirectoryRequest) SetQualifiers(v []*Qualifier) { + x.xxx_hidden_Qualifiers = &v +} + +func (x *FetchDirectoryRequest) SetDigestFunction(v v2.DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +func (x *FetchDirectoryRequest) HasTimeout() bool { + if x == nil { + return false + } + return x.xxx_hidden_Timeout != nil +} + +func (x *FetchDirectoryRequest) HasOldestContentAccepted() bool { + if x == nil { + return false + } + return x.xxx_hidden_OldestContentAccepted != nil +} + +func (x *FetchDirectoryRequest) ClearTimeout() { + x.xxx_hidden_Timeout = nil +} + +func (x *FetchDirectoryRequest) ClearOldestContentAccepted() { + x.xxx_hidden_OldestContentAccepted = nil +} + +type FetchDirectoryRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + InstanceName string + // The timeout for the underlying fetch, if content needs to be retrieved from + // origin. This value is allowed to exceed the RPC deadline, in which case the + // server *SHOULD* keep the fetch going after the RPC completes, to be made + // available for future Fetch calls. + // + // If this timeout is exceeded on an attempt to retrieve content from origin + // the client will receive DEADLINE_EXCEEDED in [FetchDirectoryResponse.status]. + Timeout *durationpb.Duration + // The oldest content the client is willing to accept, as measured from the + // time it was Push'd or when the underlying retrieval from origin was + // started. + // Upon retries of Fetch requests that cannot be completed within a single + // RPC, clients *SHOULD* provide the same value for subsequent requests as the + // original, to simplify combining the request with the previous attempt. + // + // If unset, the client *SHOULD* accept content of any age. + OldestContentAccepted *timestamppb.Timestamp + // The URI(s) of the content to fetch. These may be resources that the server + // can directly fetch from origin, in which case multiple URIs *SHOULD* + // represent the same content available at different locations (such as an + // origin and secondary mirrors). These may also be URIs for content known to + // the server through other mechanisms, e.g. pushed via the [Push][build.bazel.remote.asset.v1.Push] + // service. + // + // Clients *MUST* supply at least one URI. Servers *MAY* match any one of the + // supplied URIs. + Uris []string + // Qualifiers sub-specifying the content to fetch - see comments on + // [Qualifier][build.bazel.remote.asset.v1.Qualifier]. + // The same qualifiers apply to all URIs. + // + // Specified qualifier names *MUST* be unique. + Qualifiers []*Qualifier + // The digest function the server must use to compute the digest. + // + // If unset, the server SHOULD default to SHA256. + DigestFunction v2.DigestFunction_Value +} + +func (b0 FetchDirectoryRequest_builder) Build() *FetchDirectoryRequest { + m0 := &FetchDirectoryRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_InstanceName = b.InstanceName + x.xxx_hidden_Timeout = b.Timeout + x.xxx_hidden_OldestContentAccepted = b.OldestContentAccepted + x.xxx_hidden_Uris = b.Uris + x.xxx_hidden_Qualifiers = &b.Qualifiers + x.xxx_hidden_DigestFunction = b.DigestFunction + return m0 +} + +// A response message for +// [Fetch.FetchDirectory][build.bazel.remote.asset.v1.Fetch.FetchDirectory]. +type FetchDirectoryResponse struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Status *status.Status `protobuf:"bytes,1,opt,name=status,proto3"` + xxx_hidden_Uri string `protobuf:"bytes,2,opt,name=uri,proto3"` + xxx_hidden_Qualifiers *[]*Qualifier `protobuf:"bytes,3,rep,name=qualifiers,proto3"` + xxx_hidden_ExpiresAt *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=expires_at,json=expiresAt,proto3"` + xxx_hidden_RootDirectoryDigest *v2.Digest `protobuf:"bytes,5,opt,name=root_directory_digest,json=rootDirectoryDigest,proto3"` + xxx_hidden_DigestFunction v2.DigestFunction_Value `protobuf:"varint,6,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FetchDirectoryResponse) Reset() { + *x = FetchDirectoryResponse{} + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FetchDirectoryResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FetchDirectoryResponse) ProtoMessage() {} + +func (x *FetchDirectoryResponse) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *FetchDirectoryResponse) GetStatus() *status.Status { + if x != nil { + return x.xxx_hidden_Status + } + return nil +} + +func (x *FetchDirectoryResponse) GetUri() string { + if x != nil { + return x.xxx_hidden_Uri + } + return "" +} + +func (x *FetchDirectoryResponse) GetQualifiers() []*Qualifier { + if x != nil { + if x.xxx_hidden_Qualifiers != nil { + return *x.xxx_hidden_Qualifiers + } + } + return nil +} + +func (x *FetchDirectoryResponse) GetExpiresAt() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_ExpiresAt + } + return nil +} + +func (x *FetchDirectoryResponse) GetRootDirectoryDigest() *v2.Digest { + if x != nil { + return x.xxx_hidden_RootDirectoryDigest + } + return nil +} + +func (x *FetchDirectoryResponse) GetDigestFunction() v2.DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return v2.DigestFunction_Value(0) +} + +func (x *FetchDirectoryResponse) SetStatus(v *status.Status) { + x.xxx_hidden_Status = v +} + +func (x *FetchDirectoryResponse) SetUri(v string) { + x.xxx_hidden_Uri = v +} + +func (x *FetchDirectoryResponse) SetQualifiers(v []*Qualifier) { + x.xxx_hidden_Qualifiers = &v +} + +func (x *FetchDirectoryResponse) SetExpiresAt(v *timestamppb.Timestamp) { + x.xxx_hidden_ExpiresAt = v +} + +func (x *FetchDirectoryResponse) SetRootDirectoryDigest(v *v2.Digest) { + x.xxx_hidden_RootDirectoryDigest = v +} + +func (x *FetchDirectoryResponse) SetDigestFunction(v v2.DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +func (x *FetchDirectoryResponse) HasStatus() bool { + if x == nil { + return false + } + return x.xxx_hidden_Status != nil +} + +func (x *FetchDirectoryResponse) HasExpiresAt() bool { + if x == nil { + return false + } + return x.xxx_hidden_ExpiresAt != nil +} + +func (x *FetchDirectoryResponse) HasRootDirectoryDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_RootDirectoryDigest != nil +} + +func (x *FetchDirectoryResponse) ClearStatus() { + x.xxx_hidden_Status = nil +} + +func (x *FetchDirectoryResponse) ClearExpiresAt() { + x.xxx_hidden_ExpiresAt = nil +} + +func (x *FetchDirectoryResponse) ClearRootDirectoryDigest() { + x.xxx_hidden_RootDirectoryDigest = nil +} + +type FetchDirectoryResponse_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // If the status has a code other than `OK`, it indicates that the operation + // was unable to be completed for reasons outside the servers' control. + // The possible fetch errors include: + // - `DEADLINE_EXCEEDED`: The operation could not be completed within the + // specified timeout. + // - `NOT_FOUND`: The requested asset was not found at the specified location. + // - `PERMISSION_DENIED`: The request was rejected by a remote server, or + // requested an asset from a disallowed origin. + // - `ABORTED`: The operation could not be completed, typically due to a + // failed consistency check. + // - `RESOURCE_EXHAUSTED`: There is insufficient quota of some resource to + // perform the requested operation. The client may retry after a delay. + Status *status.Status + // The uri from the request that resulted in a successful retrieval, or from + // which the error indicated in `status` was obtained. + Uri string + // Any qualifiers known to the server and of interest to clients. + Qualifiers []*Qualifier + // A minimum timestamp the content is expected to be available through. + // Servers *MAY* omit this field, if not known with confidence. + ExpiresAt *timestamppb.Timestamp + // The result of the fetch, if the status had code `OK`. + // the root digest of a directory tree, suitable for fetching via + // [ContentAddressableStorage.GetTree]. + RootDirectoryDigest *v2.Digest + // This field SHOULD be set to the digest function that was used by the server + // to compute [FetchBlobResponse.root_directory_digest]. + // Clients could use this to determine whether the server honors + // [FetchDirectoryRequest.digest_function] that was set in the request. + // + // If unset, clients SHOULD default to use SHA256 regardless of the requested + // [FetchDirectoryRequest.digest_function]. + DigestFunction v2.DigestFunction_Value +} + +func (b0 FetchDirectoryResponse_builder) Build() *FetchDirectoryResponse { + m0 := &FetchDirectoryResponse{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Status = b.Status + x.xxx_hidden_Uri = b.Uri + x.xxx_hidden_Qualifiers = &b.Qualifiers + x.xxx_hidden_ExpiresAt = b.ExpiresAt + x.xxx_hidden_RootDirectoryDigest = b.RootDirectoryDigest + x.xxx_hidden_DigestFunction = b.DigestFunction + return m0 +} + +// A request message for +// [Push.PushBlob][build.bazel.remote.asset.v1.Push.PushBlob]. +type PushBlobRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3"` + xxx_hidden_Uris []string `protobuf:"bytes,2,rep,name=uris,proto3"` + xxx_hidden_Qualifiers *[]*Qualifier `protobuf:"bytes,3,rep,name=qualifiers,proto3"` + xxx_hidden_ExpireAt *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=expire_at,json=expireAt,proto3"` + xxx_hidden_BlobDigest *v2.Digest `protobuf:"bytes,5,opt,name=blob_digest,json=blobDigest,proto3"` + xxx_hidden_ReferencesBlobs *[]*v2.Digest `protobuf:"bytes,6,rep,name=references_blobs,json=referencesBlobs,proto3"` + xxx_hidden_ReferencesDirectories *[]*v2.Digest `protobuf:"bytes,7,rep,name=references_directories,json=referencesDirectories,proto3"` + xxx_hidden_DigestFunction v2.DigestFunction_Value `protobuf:"varint,8,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PushBlobRequest) Reset() { + *x = PushBlobRequest{} + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PushBlobRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PushBlobRequest) ProtoMessage() {} + +func (x *PushBlobRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *PushBlobRequest) GetInstanceName() string { + if x != nil { + return x.xxx_hidden_InstanceName + } + return "" +} + +func (x *PushBlobRequest) GetUris() []string { + if x != nil { + return x.xxx_hidden_Uris + } + return nil +} + +func (x *PushBlobRequest) GetQualifiers() []*Qualifier { + if x != nil { + if x.xxx_hidden_Qualifiers != nil { + return *x.xxx_hidden_Qualifiers + } + } + return nil +} + +func (x *PushBlobRequest) GetExpireAt() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_ExpireAt + } + return nil +} + +func (x *PushBlobRequest) GetBlobDigest() *v2.Digest { + if x != nil { + return x.xxx_hidden_BlobDigest + } + return nil +} + +func (x *PushBlobRequest) GetReferencesBlobs() []*v2.Digest { + if x != nil { + if x.xxx_hidden_ReferencesBlobs != nil { + return *x.xxx_hidden_ReferencesBlobs + } + } + return nil +} + +func (x *PushBlobRequest) GetReferencesDirectories() []*v2.Digest { + if x != nil { + if x.xxx_hidden_ReferencesDirectories != nil { + return *x.xxx_hidden_ReferencesDirectories + } + } + return nil +} + +func (x *PushBlobRequest) GetDigestFunction() v2.DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return v2.DigestFunction_Value(0) +} + +func (x *PushBlobRequest) SetInstanceName(v string) { + x.xxx_hidden_InstanceName = v +} + +func (x *PushBlobRequest) SetUris(v []string) { + x.xxx_hidden_Uris = v +} + +func (x *PushBlobRequest) SetQualifiers(v []*Qualifier) { + x.xxx_hidden_Qualifiers = &v +} + +func (x *PushBlobRequest) SetExpireAt(v *timestamppb.Timestamp) { + x.xxx_hidden_ExpireAt = v +} + +func (x *PushBlobRequest) SetBlobDigest(v *v2.Digest) { + x.xxx_hidden_BlobDigest = v +} + +func (x *PushBlobRequest) SetReferencesBlobs(v []*v2.Digest) { + x.xxx_hidden_ReferencesBlobs = &v +} + +func (x *PushBlobRequest) SetReferencesDirectories(v []*v2.Digest) { + x.xxx_hidden_ReferencesDirectories = &v +} + +func (x *PushBlobRequest) SetDigestFunction(v v2.DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +func (x *PushBlobRequest) HasExpireAt() bool { + if x == nil { + return false + } + return x.xxx_hidden_ExpireAt != nil +} + +func (x *PushBlobRequest) HasBlobDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_BlobDigest != nil +} + +func (x *PushBlobRequest) ClearExpireAt() { + x.xxx_hidden_ExpireAt = nil +} + +func (x *PushBlobRequest) ClearBlobDigest() { + x.xxx_hidden_BlobDigest = nil +} + +type PushBlobRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + InstanceName string + // The URI(s) of the content to associate. If multiple URIs are specified, the + // pushed content will be available to fetch by specifying any of them. + Uris []string + // Qualifiers sub-specifying the content that is being pushed - see comments + // on [Qualifier][build.bazel.remote.asset.v1.Qualifier]. + // The same qualifiers apply to all URIs. + Qualifiers []*Qualifier + // A time after which this content should stop being returned via [FetchBlob][build.bazel.remote.asset.v1.Fetch.FetchBlob]. + // Servers *MAY* expire content early, e.g. due to storage pressure. + ExpireAt *timestamppb.Timestamp + // The blob to associate. + BlobDigest *v2.Digest + // Referenced blobs or directories that need to not expire before expiration + // of this association, in addition to `blob_digest` itself. + // These fields are hints - clients *MAY* omit them, and servers *SHOULD* + // respect them, at the risk of increased incidents of Fetch responses + // indirectly referencing unavailable blobs. + ReferencesBlobs []*v2.Digest + ReferencesDirectories []*v2.Digest + // The digest function that was used to compute the blob digest. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the action digest hash and the digest functions announced + // in the server's capabilities. + DigestFunction v2.DigestFunction_Value +} + +func (b0 PushBlobRequest_builder) Build() *PushBlobRequest { + m0 := &PushBlobRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_InstanceName = b.InstanceName + x.xxx_hidden_Uris = b.Uris + x.xxx_hidden_Qualifiers = &b.Qualifiers + x.xxx_hidden_ExpireAt = b.ExpireAt + x.xxx_hidden_BlobDigest = b.BlobDigest + x.xxx_hidden_ReferencesBlobs = &b.ReferencesBlobs + x.xxx_hidden_ReferencesDirectories = &b.ReferencesDirectories + x.xxx_hidden_DigestFunction = b.DigestFunction + return m0 +} + +// A response message for +// [Push.PushBlob][build.bazel.remote.asset.v1.Push.PushBlob]. +type PushBlobResponse struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PushBlobResponse) Reset() { + *x = PushBlobResponse{} + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PushBlobResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PushBlobResponse) ProtoMessage() {} + +func (x *PushBlobResponse) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[6] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +type PushBlobResponse_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + +} + +func (b0 PushBlobResponse_builder) Build() *PushBlobResponse { + m0 := &PushBlobResponse{} + b, x := &b0, m0 + _, _ = b, x + return m0 +} + +// A request message for +// [Push.PushDirectory][build.bazel.remote.asset.v1.Push.PushDirectory]. +type PushDirectoryRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3"` + xxx_hidden_Uris []string `protobuf:"bytes,2,rep,name=uris,proto3"` + xxx_hidden_Qualifiers *[]*Qualifier `protobuf:"bytes,3,rep,name=qualifiers,proto3"` + xxx_hidden_ExpireAt *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=expire_at,json=expireAt,proto3"` + xxx_hidden_RootDirectoryDigest *v2.Digest `protobuf:"bytes,5,opt,name=root_directory_digest,json=rootDirectoryDigest,proto3"` + xxx_hidden_ReferencesBlobs *[]*v2.Digest `protobuf:"bytes,6,rep,name=references_blobs,json=referencesBlobs,proto3"` + xxx_hidden_ReferencesDirectories *[]*v2.Digest `protobuf:"bytes,7,rep,name=references_directories,json=referencesDirectories,proto3"` + xxx_hidden_DigestFunction v2.DigestFunction_Value `protobuf:"varint,8,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PushDirectoryRequest) Reset() { + *x = PushDirectoryRequest{} + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PushDirectoryRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PushDirectoryRequest) ProtoMessage() {} + +func (x *PushDirectoryRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[7] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *PushDirectoryRequest) GetInstanceName() string { + if x != nil { + return x.xxx_hidden_InstanceName + } + return "" +} + +func (x *PushDirectoryRequest) GetUris() []string { + if x != nil { + return x.xxx_hidden_Uris + } + return nil +} + +func (x *PushDirectoryRequest) GetQualifiers() []*Qualifier { + if x != nil { + if x.xxx_hidden_Qualifiers != nil { + return *x.xxx_hidden_Qualifiers + } + } + return nil +} + +func (x *PushDirectoryRequest) GetExpireAt() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_ExpireAt + } + return nil +} + +func (x *PushDirectoryRequest) GetRootDirectoryDigest() *v2.Digest { + if x != nil { + return x.xxx_hidden_RootDirectoryDigest + } + return nil +} + +func (x *PushDirectoryRequest) GetReferencesBlobs() []*v2.Digest { + if x != nil { + if x.xxx_hidden_ReferencesBlobs != nil { + return *x.xxx_hidden_ReferencesBlobs + } + } + return nil +} + +func (x *PushDirectoryRequest) GetReferencesDirectories() []*v2.Digest { + if x != nil { + if x.xxx_hidden_ReferencesDirectories != nil { + return *x.xxx_hidden_ReferencesDirectories + } + } + return nil +} + +func (x *PushDirectoryRequest) GetDigestFunction() v2.DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return v2.DigestFunction_Value(0) +} + +func (x *PushDirectoryRequest) SetInstanceName(v string) { + x.xxx_hidden_InstanceName = v +} + +func (x *PushDirectoryRequest) SetUris(v []string) { + x.xxx_hidden_Uris = v +} + +func (x *PushDirectoryRequest) SetQualifiers(v []*Qualifier) { + x.xxx_hidden_Qualifiers = &v +} + +func (x *PushDirectoryRequest) SetExpireAt(v *timestamppb.Timestamp) { + x.xxx_hidden_ExpireAt = v +} + +func (x *PushDirectoryRequest) SetRootDirectoryDigest(v *v2.Digest) { + x.xxx_hidden_RootDirectoryDigest = v +} + +func (x *PushDirectoryRequest) SetReferencesBlobs(v []*v2.Digest) { + x.xxx_hidden_ReferencesBlobs = &v +} + +func (x *PushDirectoryRequest) SetReferencesDirectories(v []*v2.Digest) { + x.xxx_hidden_ReferencesDirectories = &v +} + +func (x *PushDirectoryRequest) SetDigestFunction(v v2.DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +func (x *PushDirectoryRequest) HasExpireAt() bool { + if x == nil { + return false + } + return x.xxx_hidden_ExpireAt != nil +} + +func (x *PushDirectoryRequest) HasRootDirectoryDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_RootDirectoryDigest != nil +} + +func (x *PushDirectoryRequest) ClearExpireAt() { + x.xxx_hidden_ExpireAt = nil +} + +func (x *PushDirectoryRequest) ClearRootDirectoryDigest() { + x.xxx_hidden_RootDirectoryDigest = nil +} + +type PushDirectoryRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + InstanceName string + // The URI(s) of the content to associate. If multiple URIs are specified, the + // pushed content will be available to fetch by specifying any of them. + Uris []string + // Qualifiers sub-specifying the content that is being pushed - see comments + // on [Qualifier][build.bazel.remote.asset.v1.Qualifier]. + // The same qualifiers apply to all URIs. + Qualifiers []*Qualifier + // A time after which this content should stop being returned via + // [FetchDirectory][build.bazel.remote.asset.v1.Fetch.FetchDirectory]. + // Servers *MAY* expire content early, e.g. due to storage pressure. + ExpireAt *timestamppb.Timestamp + // Directory to associate + RootDirectoryDigest *v2.Digest + // Referenced blobs or directories that need to not expire before expiration + // of this association, in addition to `root_directory_digest` itself. + // These fields are hints - clients *MAY* omit them, and servers *SHOULD* + // respect them, at the risk of increased incidents of Fetch responses + // indirectly referencing unavailable blobs. + ReferencesBlobs []*v2.Digest + ReferencesDirectories []*v2.Digest + // The digest function that was used to compute blob digests. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the action digest hash and the digest functions announced + // in the server's capabilities. + DigestFunction v2.DigestFunction_Value +} + +func (b0 PushDirectoryRequest_builder) Build() *PushDirectoryRequest { + m0 := &PushDirectoryRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_InstanceName = b.InstanceName + x.xxx_hidden_Uris = b.Uris + x.xxx_hidden_Qualifiers = &b.Qualifiers + x.xxx_hidden_ExpireAt = b.ExpireAt + x.xxx_hidden_RootDirectoryDigest = b.RootDirectoryDigest + x.xxx_hidden_ReferencesBlobs = &b.ReferencesBlobs + x.xxx_hidden_ReferencesDirectories = &b.ReferencesDirectories + x.xxx_hidden_DigestFunction = b.DigestFunction + return m0 +} + +// A response message for +// [Push.PushDirectory][build.bazel.remote.asset.v1.Push.PushDirectory]. +type PushDirectoryResponse struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PushDirectoryResponse) Reset() { + *x = PushDirectoryResponse{} + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PushDirectoryResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PushDirectoryResponse) ProtoMessage() {} + +func (x *PushDirectoryResponse) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +type PushDirectoryResponse_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + +} + +func (b0 PushDirectoryResponse_builder) Build() *PushDirectoryResponse { + m0 := &PushDirectoryResponse{} + b, x := &b0, m0 + _, _ = b, x + return m0 +} + +var File_build_bazel_remote_asset_v1_remote_asset_proto protoreflect.FileDescriptor + +const file_build_bazel_remote_asset_v1_remote_asset_proto_rawDesc = "" + + "\n" + + ".build/bazel/remote/asset/v1/remote_asset.proto\x12\x1bbuild.bazel.remote.asset.v1\x1a6build/bazel/remote/execution/v2/remote_execution.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/rpc/status.proto\"5\n" + + "\tQualifier\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" + + "\x05value\x18\x02 \x01(\tR\x05value\"\xfc\x02\n" + + "\x10FetchBlobRequest\x12#\n" + + "\rinstance_name\x18\x01 \x01(\tR\finstanceName\x123\n" + + "\atimeout\x18\x02 \x01(\v2\x19.google.protobuf.DurationR\atimeout\x12R\n" + + "\x17oldest_content_accepted\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\x15oldestContentAccepted\x12\x12\n" + + "\x04uris\x18\x04 \x03(\tR\x04uris\x12F\n" + + "\n" + + "qualifiers\x18\x05 \x03(\v2&.build.bazel.remote.asset.v1.QualifierR\n" + + "qualifiers\x12^\n" + + "\x0fdigest_function\x18\x06 \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\"\xfe\x02\n" + + "\x11FetchBlobResponse\x12*\n" + + "\x06status\x18\x01 \x01(\v2\x12.google.rpc.StatusR\x06status\x12\x10\n" + + "\x03uri\x18\x02 \x01(\tR\x03uri\x12F\n" + + "\n" + + "qualifiers\x18\x03 \x03(\v2&.build.bazel.remote.asset.v1.QualifierR\n" + + "qualifiers\x129\n" + + "\n" + + "expires_at\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\texpiresAt\x12H\n" + + "\vblob_digest\x18\x05 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\n" + + "blobDigest\x12^\n" + + "\x0fdigest_function\x18\x06 \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\"\x81\x03\n" + + "\x15FetchDirectoryRequest\x12#\n" + + "\rinstance_name\x18\x01 \x01(\tR\finstanceName\x123\n" + + "\atimeout\x18\x02 \x01(\v2\x19.google.protobuf.DurationR\atimeout\x12R\n" + + "\x17oldest_content_accepted\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\x15oldestContentAccepted\x12\x12\n" + + "\x04uris\x18\x04 \x03(\tR\x04uris\x12F\n" + + "\n" + + "qualifiers\x18\x05 \x03(\v2&.build.bazel.remote.asset.v1.QualifierR\n" + + "qualifiers\x12^\n" + + "\x0fdigest_function\x18\x06 \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\"\x96\x03\n" + + "\x16FetchDirectoryResponse\x12*\n" + + "\x06status\x18\x01 \x01(\v2\x12.google.rpc.StatusR\x06status\x12\x10\n" + + "\x03uri\x18\x02 \x01(\tR\x03uri\x12F\n" + + "\n" + + "qualifiers\x18\x03 \x03(\v2&.build.bazel.remote.asset.v1.QualifierR\n" + + "qualifiers\x129\n" + + "\n" + + "expires_at\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\texpiresAt\x12[\n" + + "\x15root_directory_digest\x18\x05 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\x13rootDirectoryDigest\x12^\n" + + "\x0fdigest_function\x18\x06 \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\"\xa9\x04\n" + + "\x0fPushBlobRequest\x12#\n" + + "\rinstance_name\x18\x01 \x01(\tR\finstanceName\x12\x12\n" + + "\x04uris\x18\x02 \x03(\tR\x04uris\x12F\n" + + "\n" + + "qualifiers\x18\x03 \x03(\v2&.build.bazel.remote.asset.v1.QualifierR\n" + + "qualifiers\x127\n" + + "\texpire_at\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\bexpireAt\x12H\n" + + "\vblob_digest\x18\x05 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\n" + + "blobDigest\x12R\n" + + "\x10references_blobs\x18\x06 \x03(\v2'.build.bazel.remote.execution.v2.DigestR\x0freferencesBlobs\x12^\n" + + "\x16references_directories\x18\a \x03(\v2'.build.bazel.remote.execution.v2.DigestR\x15referencesDirectories\x12^\n" + + "\x0fdigest_function\x18\b \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\"\x12\n" + + "\x10PushBlobResponse\"\xc1\x04\n" + + "\x14PushDirectoryRequest\x12#\n" + + "\rinstance_name\x18\x01 \x01(\tR\finstanceName\x12\x12\n" + + "\x04uris\x18\x02 \x03(\tR\x04uris\x12F\n" + + "\n" + + "qualifiers\x18\x03 \x03(\v2&.build.bazel.remote.asset.v1.QualifierR\n" + + "qualifiers\x127\n" + + "\texpire_at\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\bexpireAt\x12[\n" + + "\x15root_directory_digest\x18\x05 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\x13rootDirectoryDigest\x12R\n" + + "\x10references_blobs\x18\x06 \x03(\v2'.build.bazel.remote.execution.v2.DigestR\x0freferencesBlobs\x12^\n" + + "\x16references_directories\x18\a \x03(\v2'.build.bazel.remote.execution.v2.DigestR\x15referencesDirectories\x12^\n" + + "\x0fdigest_function\x18\b \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\"\x17\n" + + "\x15PushDirectoryResponse2\xdd\x02\n" + + "\x05Fetch\x12\x9e\x01\n" + + "\tFetchBlob\x12-.build.bazel.remote.asset.v1.FetchBlobRequest\x1a..build.bazel.remote.asset.v1.FetchBlobResponse\"2\x82\xd3\xe4\x93\x02,:\x01*\"'/v1/{instance_name=**}/assets:fetchBlob\x12\xb2\x01\n" + + "\x0eFetchDirectory\x122.build.bazel.remote.asset.v1.FetchDirectoryRequest\x1a3.build.bazel.remote.asset.v1.FetchDirectoryResponse\"7\x82\xd3\xe4\x93\x021:\x01*\",/v1/{instance_name=**}/assets:fetchDirectory2\xd4\x02\n" + + "\x04Push\x12\x9a\x01\n" + + "\bPushBlob\x12,.build.bazel.remote.asset.v1.PushBlobRequest\x1a-.build.bazel.remote.asset.v1.PushBlobResponse\"1\x82\xd3\xe4\x93\x02+:\x01*\"&/v1/{instance_name=**}/assets:pushBlob\x12\xae\x01\n" + + "\rPushDirectory\x121.build.bazel.remote.asset.v1.PushDirectoryRequest\x1a2.build.bazel.remote.asset.v1.PushDirectoryResponse\"6\x82\xd3\xe4\x93\x020:\x01*\"+/v1/{instance_name=**}/assets:pushDirectoryB\x9f\x01\n" + + "\x1bbuild.bazel.remote.asset.v1B\x10RemoteAssetProtoP\x01ZIgithub.com/bazelbuild/remote-apis/build/bazel/remote/asset/v1;remoteasset\xa2\x02\x02RA\xaa\x02\x1bBuild.Bazel.Remote.Asset.v1b\x06proto3" + +var file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes = make([]protoimpl.MessageInfo, 9) +var file_build_bazel_remote_asset_v1_remote_asset_proto_goTypes = []any{ + (*Qualifier)(nil), // 0: build.bazel.remote.asset.v1.Qualifier + (*FetchBlobRequest)(nil), // 1: build.bazel.remote.asset.v1.FetchBlobRequest + (*FetchBlobResponse)(nil), // 2: build.bazel.remote.asset.v1.FetchBlobResponse + (*FetchDirectoryRequest)(nil), // 3: build.bazel.remote.asset.v1.FetchDirectoryRequest + (*FetchDirectoryResponse)(nil), // 4: build.bazel.remote.asset.v1.FetchDirectoryResponse + (*PushBlobRequest)(nil), // 5: build.bazel.remote.asset.v1.PushBlobRequest + (*PushBlobResponse)(nil), // 6: build.bazel.remote.asset.v1.PushBlobResponse + (*PushDirectoryRequest)(nil), // 7: build.bazel.remote.asset.v1.PushDirectoryRequest + (*PushDirectoryResponse)(nil), // 8: build.bazel.remote.asset.v1.PushDirectoryResponse + (*durationpb.Duration)(nil), // 9: google.protobuf.Duration + (*timestamppb.Timestamp)(nil), // 10: google.protobuf.Timestamp + (v2.DigestFunction_Value)(0), // 11: build.bazel.remote.execution.v2.DigestFunction.Value + (*status.Status)(nil), // 12: google.rpc.Status + (*v2.Digest)(nil), // 13: build.bazel.remote.execution.v2.Digest +} +var file_build_bazel_remote_asset_v1_remote_asset_proto_depIdxs = []int32{ + 9, // 0: build.bazel.remote.asset.v1.FetchBlobRequest.timeout:type_name -> google.protobuf.Duration + 10, // 1: build.bazel.remote.asset.v1.FetchBlobRequest.oldest_content_accepted:type_name -> google.protobuf.Timestamp + 0, // 2: build.bazel.remote.asset.v1.FetchBlobRequest.qualifiers:type_name -> build.bazel.remote.asset.v1.Qualifier + 11, // 3: build.bazel.remote.asset.v1.FetchBlobRequest.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 12, // 4: build.bazel.remote.asset.v1.FetchBlobResponse.status:type_name -> google.rpc.Status + 0, // 5: build.bazel.remote.asset.v1.FetchBlobResponse.qualifiers:type_name -> build.bazel.remote.asset.v1.Qualifier + 10, // 6: build.bazel.remote.asset.v1.FetchBlobResponse.expires_at:type_name -> google.protobuf.Timestamp + 13, // 7: build.bazel.remote.asset.v1.FetchBlobResponse.blob_digest:type_name -> build.bazel.remote.execution.v2.Digest + 11, // 8: build.bazel.remote.asset.v1.FetchBlobResponse.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 9, // 9: build.bazel.remote.asset.v1.FetchDirectoryRequest.timeout:type_name -> google.protobuf.Duration + 10, // 10: build.bazel.remote.asset.v1.FetchDirectoryRequest.oldest_content_accepted:type_name -> google.protobuf.Timestamp + 0, // 11: build.bazel.remote.asset.v1.FetchDirectoryRequest.qualifiers:type_name -> build.bazel.remote.asset.v1.Qualifier + 11, // 12: build.bazel.remote.asset.v1.FetchDirectoryRequest.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 12, // 13: build.bazel.remote.asset.v1.FetchDirectoryResponse.status:type_name -> google.rpc.Status + 0, // 14: build.bazel.remote.asset.v1.FetchDirectoryResponse.qualifiers:type_name -> build.bazel.remote.asset.v1.Qualifier + 10, // 15: build.bazel.remote.asset.v1.FetchDirectoryResponse.expires_at:type_name -> google.protobuf.Timestamp + 13, // 16: build.bazel.remote.asset.v1.FetchDirectoryResponse.root_directory_digest:type_name -> build.bazel.remote.execution.v2.Digest + 11, // 17: build.bazel.remote.asset.v1.FetchDirectoryResponse.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 0, // 18: build.bazel.remote.asset.v1.PushBlobRequest.qualifiers:type_name -> build.bazel.remote.asset.v1.Qualifier + 10, // 19: build.bazel.remote.asset.v1.PushBlobRequest.expire_at:type_name -> google.protobuf.Timestamp + 13, // 20: build.bazel.remote.asset.v1.PushBlobRequest.blob_digest:type_name -> build.bazel.remote.execution.v2.Digest + 13, // 21: build.bazel.remote.asset.v1.PushBlobRequest.references_blobs:type_name -> build.bazel.remote.execution.v2.Digest + 13, // 22: build.bazel.remote.asset.v1.PushBlobRequest.references_directories:type_name -> build.bazel.remote.execution.v2.Digest + 11, // 23: build.bazel.remote.asset.v1.PushBlobRequest.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 0, // 24: build.bazel.remote.asset.v1.PushDirectoryRequest.qualifiers:type_name -> build.bazel.remote.asset.v1.Qualifier + 10, // 25: build.bazel.remote.asset.v1.PushDirectoryRequest.expire_at:type_name -> google.protobuf.Timestamp + 13, // 26: build.bazel.remote.asset.v1.PushDirectoryRequest.root_directory_digest:type_name -> build.bazel.remote.execution.v2.Digest + 13, // 27: build.bazel.remote.asset.v1.PushDirectoryRequest.references_blobs:type_name -> build.bazel.remote.execution.v2.Digest + 13, // 28: build.bazel.remote.asset.v1.PushDirectoryRequest.references_directories:type_name -> build.bazel.remote.execution.v2.Digest + 11, // 29: build.bazel.remote.asset.v1.PushDirectoryRequest.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 1, // 30: build.bazel.remote.asset.v1.Fetch.FetchBlob:input_type -> build.bazel.remote.asset.v1.FetchBlobRequest + 3, // 31: build.bazel.remote.asset.v1.Fetch.FetchDirectory:input_type -> build.bazel.remote.asset.v1.FetchDirectoryRequest + 5, // 32: build.bazel.remote.asset.v1.Push.PushBlob:input_type -> build.bazel.remote.asset.v1.PushBlobRequest + 7, // 33: build.bazel.remote.asset.v1.Push.PushDirectory:input_type -> build.bazel.remote.asset.v1.PushDirectoryRequest + 2, // 34: build.bazel.remote.asset.v1.Fetch.FetchBlob:output_type -> build.bazel.remote.asset.v1.FetchBlobResponse + 4, // 35: build.bazel.remote.asset.v1.Fetch.FetchDirectory:output_type -> build.bazel.remote.asset.v1.FetchDirectoryResponse + 6, // 36: build.bazel.remote.asset.v1.Push.PushBlob:output_type -> build.bazel.remote.asset.v1.PushBlobResponse + 8, // 37: build.bazel.remote.asset.v1.Push.PushDirectory:output_type -> build.bazel.remote.asset.v1.PushDirectoryResponse + 34, // [34:38] is the sub-list for method output_type + 30, // [30:34] is the sub-list for method input_type + 30, // [30:30] is the sub-list for extension type_name + 30, // [30:30] is the sub-list for extension extendee + 0, // [0:30] is the sub-list for field type_name +} + +func init() { file_build_bazel_remote_asset_v1_remote_asset_proto_init() } +func file_build_bazel_remote_asset_v1_remote_asset_proto_init() { + if File_build_bazel_remote_asset_v1_remote_asset_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_build_bazel_remote_asset_v1_remote_asset_proto_rawDesc), len(file_build_bazel_remote_asset_v1_remote_asset_proto_rawDesc)), + NumEnums: 0, + NumMessages: 9, + NumExtensions: 0, + NumServices: 2, + }, + GoTypes: file_build_bazel_remote_asset_v1_remote_asset_proto_goTypes, + DependencyIndexes: file_build_bazel_remote_asset_v1_remote_asset_proto_depIdxs, + MessageInfos: file_build_bazel_remote_asset_v1_remote_asset_proto_msgTypes, + }.Build() + File_build_bazel_remote_asset_v1_remote_asset_proto = out.File + file_build_bazel_remote_asset_v1_remote_asset_proto_goTypes = nil + file_build_bazel_remote_asset_v1_remote_asset_proto_depIdxs = nil +} diff --git a/internal/proto/gen/build/bazel/remote/asset/v1/remote_asset_grpc.pb.go b/internal/proto/gen/build/bazel/remote/asset/v1/remote_asset_grpc.pb.go new file mode 100644 index 0000000..de5b577 --- /dev/null +++ b/internal/proto/gen/build/bazel/remote/asset/v1/remote_asset_grpc.pb.go @@ -0,0 +1,529 @@ +// Copyright 2020 The Bazel Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.5.1 +// - protoc (unknown) +// source: build/bazel/remote/asset/v1/remote_asset.proto + +package remoteasset + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + Fetch_FetchBlob_FullMethodName = "/build.bazel.remote.asset.v1.Fetch/FetchBlob" + Fetch_FetchDirectory_FullMethodName = "/build.bazel.remote.asset.v1.Fetch/FetchDirectory" +) + +// FetchClient is the client API for Fetch service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// The Fetch service resolves or fetches assets referenced by URI and +// Qualifiers, returning a Digest for the content in +// [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +type FetchClient interface { + // Resolve or fetch referenced assets, making them available to the caller and + // other consumers in the [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + // + // Servers *MAY* fetch content that they do not already have cached, for any + // URLs they support. + // + // Servers *SHOULD* ensure that referenced files are present in the CAS at the + // time of the response, and (if supported) that they will remain available + // for a reasonable period of time. The lifetimes of the referenced blobs *SHOULD* + // be increased if necessary and applicable. + // In the event that a client receives a reference to content that is no + // longer present, it *MAY* re-issue the request with + // `oldest_content_accepted` set to a more recent timestamp than the original + // attempt, to induce a re-fetch from origin. + // + // Servers *MAY* cache fetched content and reuse it for subsequent requests, + // subject to `oldest_content_accepted`. + // + // Servers *MAY* support the complementary [Push][build.bazel.remote.asset.v1.Push] + // API and allow content to be directly inserted for use in future fetch + // responses. + // + // Servers *MUST* ensure Fetch'd content matches all the specified + // qualifiers except in the case of previously Push'd resources, for which + // the server *MAY* trust the pushing client to have set the qualifiers + // correctly, without validation. + // + // Servers not implementing the complementary [Push][build.bazel.remote.asset.v1.Push] + // API *MUST* reject requests containing qualifiers it does not support. + // + // Servers *MAY* transform assets as part of the fetch. For example a + // tarball fetched by [FetchDirectory][build.bazel.remote.asset.v1.Fetch.FetchDirectory] + // might be unpacked, or a Git repository + // fetched by [FetchBlob][build.bazel.remote.asset.v1.Fetch.FetchBlob] + // might be passed through `git-archive`. + // + // Errors handling the requested assets will be returned as gRPC Status errors + // here; errors outside the server's control will be returned inline in the + // `status` field of the response (see comment there for details). + // The possible RPC errors include: + // - `INVALID_ARGUMENT`: One or more arguments were invalid, such as a + // qualifier that is not supported by the server. + // - `RESOURCE_EXHAUSTED`: There is insufficient quota of some resource to + // perform the requested operation. The client may retry after a delay. + // - `UNAVAILABLE`: Due to a transient condition the operation could not be + // completed. The client should retry. + // - `INTERNAL`: An internal error occurred while performing the operation. + // The client should retry. + // - `DEADLINE_EXCEEDED`: The fetch could not be completed within the given + // RPC deadline. The client should retry for at least as long as the value + // provided in `timeout` field of the request. + // + // In the case of unsupported qualifiers, the server *SHOULD* additionally + // send a [BadRequest][google.rpc.BadRequest] error detail where, for each + // unsupported qualifier, there is a `FieldViolation` with a `field` of + // `qualifiers.name` and a `description` of `"{qualifier}" not supported` + // indicating the name of the unsupported qualifier. + FetchBlob(ctx context.Context, in *FetchBlobRequest, opts ...grpc.CallOption) (*FetchBlobResponse, error) + FetchDirectory(ctx context.Context, in *FetchDirectoryRequest, opts ...grpc.CallOption) (*FetchDirectoryResponse, error) +} + +type fetchClient struct { + cc grpc.ClientConnInterface +} + +func NewFetchClient(cc grpc.ClientConnInterface) FetchClient { + return &fetchClient{cc} +} + +func (c *fetchClient) FetchBlob(ctx context.Context, in *FetchBlobRequest, opts ...grpc.CallOption) (*FetchBlobResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(FetchBlobResponse) + err := c.cc.Invoke(ctx, Fetch_FetchBlob_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *fetchClient) FetchDirectory(ctx context.Context, in *FetchDirectoryRequest, opts ...grpc.CallOption) (*FetchDirectoryResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(FetchDirectoryResponse) + err := c.cc.Invoke(ctx, Fetch_FetchDirectory_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// FetchServer is the server API for Fetch service. +// All implementations must embed UnimplementedFetchServer +// for forward compatibility. +// +// The Fetch service resolves or fetches assets referenced by URI and +// Qualifiers, returning a Digest for the content in +// [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +type FetchServer interface { + // Resolve or fetch referenced assets, making them available to the caller and + // other consumers in the [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + // + // Servers *MAY* fetch content that they do not already have cached, for any + // URLs they support. + // + // Servers *SHOULD* ensure that referenced files are present in the CAS at the + // time of the response, and (if supported) that they will remain available + // for a reasonable period of time. The lifetimes of the referenced blobs *SHOULD* + // be increased if necessary and applicable. + // In the event that a client receives a reference to content that is no + // longer present, it *MAY* re-issue the request with + // `oldest_content_accepted` set to a more recent timestamp than the original + // attempt, to induce a re-fetch from origin. + // + // Servers *MAY* cache fetched content and reuse it for subsequent requests, + // subject to `oldest_content_accepted`. + // + // Servers *MAY* support the complementary [Push][build.bazel.remote.asset.v1.Push] + // API and allow content to be directly inserted for use in future fetch + // responses. + // + // Servers *MUST* ensure Fetch'd content matches all the specified + // qualifiers except in the case of previously Push'd resources, for which + // the server *MAY* trust the pushing client to have set the qualifiers + // correctly, without validation. + // + // Servers not implementing the complementary [Push][build.bazel.remote.asset.v1.Push] + // API *MUST* reject requests containing qualifiers it does not support. + // + // Servers *MAY* transform assets as part of the fetch. For example a + // tarball fetched by [FetchDirectory][build.bazel.remote.asset.v1.Fetch.FetchDirectory] + // might be unpacked, or a Git repository + // fetched by [FetchBlob][build.bazel.remote.asset.v1.Fetch.FetchBlob] + // might be passed through `git-archive`. + // + // Errors handling the requested assets will be returned as gRPC Status errors + // here; errors outside the server's control will be returned inline in the + // `status` field of the response (see comment there for details). + // The possible RPC errors include: + // - `INVALID_ARGUMENT`: One or more arguments were invalid, such as a + // qualifier that is not supported by the server. + // - `RESOURCE_EXHAUSTED`: There is insufficient quota of some resource to + // perform the requested operation. The client may retry after a delay. + // - `UNAVAILABLE`: Due to a transient condition the operation could not be + // completed. The client should retry. + // - `INTERNAL`: An internal error occurred while performing the operation. + // The client should retry. + // - `DEADLINE_EXCEEDED`: The fetch could not be completed within the given + // RPC deadline. The client should retry for at least as long as the value + // provided in `timeout` field of the request. + // + // In the case of unsupported qualifiers, the server *SHOULD* additionally + // send a [BadRequest][google.rpc.BadRequest] error detail where, for each + // unsupported qualifier, there is a `FieldViolation` with a `field` of + // `qualifiers.name` and a `description` of `"{qualifier}" not supported` + // indicating the name of the unsupported qualifier. + FetchBlob(context.Context, *FetchBlobRequest) (*FetchBlobResponse, error) + FetchDirectory(context.Context, *FetchDirectoryRequest) (*FetchDirectoryResponse, error) + mustEmbedUnimplementedFetchServer() +} + +// UnimplementedFetchServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedFetchServer struct{} + +func (UnimplementedFetchServer) FetchBlob(context.Context, *FetchBlobRequest) (*FetchBlobResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method FetchBlob not implemented") +} +func (UnimplementedFetchServer) FetchDirectory(context.Context, *FetchDirectoryRequest) (*FetchDirectoryResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method FetchDirectory not implemented") +} +func (UnimplementedFetchServer) mustEmbedUnimplementedFetchServer() {} +func (UnimplementedFetchServer) testEmbeddedByValue() {} + +// UnsafeFetchServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to FetchServer will +// result in compilation errors. +type UnsafeFetchServer interface { + mustEmbedUnimplementedFetchServer() +} + +func RegisterFetchServer(s grpc.ServiceRegistrar, srv FetchServer) { + // If the following call pancis, it indicates UnimplementedFetchServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&Fetch_ServiceDesc, srv) +} + +func _Fetch_FetchBlob_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(FetchBlobRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(FetchServer).FetchBlob(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Fetch_FetchBlob_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(FetchServer).FetchBlob(ctx, req.(*FetchBlobRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Fetch_FetchDirectory_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(FetchDirectoryRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(FetchServer).FetchDirectory(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Fetch_FetchDirectory_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(FetchServer).FetchDirectory(ctx, req.(*FetchDirectoryRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// Fetch_ServiceDesc is the grpc.ServiceDesc for Fetch service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Fetch_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "build.bazel.remote.asset.v1.Fetch", + HandlerType: (*FetchServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "FetchBlob", + Handler: _Fetch_FetchBlob_Handler, + }, + { + MethodName: "FetchDirectory", + Handler: _Fetch_FetchDirectory_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "build/bazel/remote/asset/v1/remote_asset.proto", +} + +const ( + Push_PushBlob_FullMethodName = "/build.bazel.remote.asset.v1.Push/PushBlob" + Push_PushDirectory_FullMethodName = "/build.bazel.remote.asset.v1.Push/PushDirectory" +) + +// PushClient is the client API for Push service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// The Push service is complementary to the Fetch, and allows for +// associating contents of URLs to be returned in future Fetch API calls. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +type PushClient interface { + // These APIs associate the identifying information of a resource, as + // indicated by URI and optionally Qualifiers, with content available in the + // CAS. For example, associating a repository url and a commit id with a + // Directory Digest. + // + // Servers *SHOULD* only allow trusted clients to associate content, and *MAY* + // only allow certain URIs to be pushed. + // + // Clients *MUST* ensure associated content is available in CAS prior to + // pushing. + // + // Clients *MUST* ensure the Qualifiers listed correctly match the contents, + // and Servers *MAY* trust these values without validation. + // Fetch servers *MAY* require exact match of all qualifiers when returning + // content previously pushed, or allow fetching content with only a subset of + // the qualifiers specified on Push. + // + // Clients can specify expiration information that the server *SHOULD* + // respect. Subsequent requests can be used to alter the expiration time. + // + // A minimal compliant Fetch implementation may support only Push'd content + // and return `NOT_FOUND` for any resource that was not pushed first. + // Alternatively, a compliant implementation may choose to not support Push + // and only return resources that can be Fetch'd from origin. + // + // Errors will be returned as gRPC Status errors. + // The possible RPC errors include: + // - `INVALID_ARGUMENT`: One or more arguments to the RPC were invalid. + // - `RESOURCE_EXHAUSTED`: There is insufficient quota of some resource to + // perform the requested operation. The client may retry after a delay. + // - `UNAVAILABLE`: Due to a transient condition the operation could not be + // completed. The client should retry. + // - `INTERNAL`: An internal error occurred while performing the operation. + // The client should retry. + PushBlob(ctx context.Context, in *PushBlobRequest, opts ...grpc.CallOption) (*PushBlobResponse, error) + PushDirectory(ctx context.Context, in *PushDirectoryRequest, opts ...grpc.CallOption) (*PushDirectoryResponse, error) +} + +type pushClient struct { + cc grpc.ClientConnInterface +} + +func NewPushClient(cc grpc.ClientConnInterface) PushClient { + return &pushClient{cc} +} + +func (c *pushClient) PushBlob(ctx context.Context, in *PushBlobRequest, opts ...grpc.CallOption) (*PushBlobResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(PushBlobResponse) + err := c.cc.Invoke(ctx, Push_PushBlob_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *pushClient) PushDirectory(ctx context.Context, in *PushDirectoryRequest, opts ...grpc.CallOption) (*PushDirectoryResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(PushDirectoryResponse) + err := c.cc.Invoke(ctx, Push_PushDirectory_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// PushServer is the server API for Push service. +// All implementations must embed UnimplementedPushServer +// for forward compatibility. +// +// The Push service is complementary to the Fetch, and allows for +// associating contents of URLs to be returned in future Fetch API calls. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +type PushServer interface { + // These APIs associate the identifying information of a resource, as + // indicated by URI and optionally Qualifiers, with content available in the + // CAS. For example, associating a repository url and a commit id with a + // Directory Digest. + // + // Servers *SHOULD* only allow trusted clients to associate content, and *MAY* + // only allow certain URIs to be pushed. + // + // Clients *MUST* ensure associated content is available in CAS prior to + // pushing. + // + // Clients *MUST* ensure the Qualifiers listed correctly match the contents, + // and Servers *MAY* trust these values without validation. + // Fetch servers *MAY* require exact match of all qualifiers when returning + // content previously pushed, or allow fetching content with only a subset of + // the qualifiers specified on Push. + // + // Clients can specify expiration information that the server *SHOULD* + // respect. Subsequent requests can be used to alter the expiration time. + // + // A minimal compliant Fetch implementation may support only Push'd content + // and return `NOT_FOUND` for any resource that was not pushed first. + // Alternatively, a compliant implementation may choose to not support Push + // and only return resources that can be Fetch'd from origin. + // + // Errors will be returned as gRPC Status errors. + // The possible RPC errors include: + // - `INVALID_ARGUMENT`: One or more arguments to the RPC were invalid. + // - `RESOURCE_EXHAUSTED`: There is insufficient quota of some resource to + // perform the requested operation. The client may retry after a delay. + // - `UNAVAILABLE`: Due to a transient condition the operation could not be + // completed. The client should retry. + // - `INTERNAL`: An internal error occurred while performing the operation. + // The client should retry. + PushBlob(context.Context, *PushBlobRequest) (*PushBlobResponse, error) + PushDirectory(context.Context, *PushDirectoryRequest) (*PushDirectoryResponse, error) + mustEmbedUnimplementedPushServer() +} + +// UnimplementedPushServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedPushServer struct{} + +func (UnimplementedPushServer) PushBlob(context.Context, *PushBlobRequest) (*PushBlobResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method PushBlob not implemented") +} +func (UnimplementedPushServer) PushDirectory(context.Context, *PushDirectoryRequest) (*PushDirectoryResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method PushDirectory not implemented") +} +func (UnimplementedPushServer) mustEmbedUnimplementedPushServer() {} +func (UnimplementedPushServer) testEmbeddedByValue() {} + +// UnsafePushServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to PushServer will +// result in compilation errors. +type UnsafePushServer interface { + mustEmbedUnimplementedPushServer() +} + +func RegisterPushServer(s grpc.ServiceRegistrar, srv PushServer) { + // If the following call pancis, it indicates UnimplementedPushServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&Push_ServiceDesc, srv) +} + +func _Push_PushBlob_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(PushBlobRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(PushServer).PushBlob(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Push_PushBlob_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(PushServer).PushBlob(ctx, req.(*PushBlobRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Push_PushDirectory_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(PushDirectoryRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(PushServer).PushDirectory(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Push_PushDirectory_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(PushServer).PushDirectory(ctx, req.(*PushDirectoryRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// Push_ServiceDesc is the grpc.ServiceDesc for Push service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Push_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "build.bazel.remote.asset.v1.Push", + HandlerType: (*PushServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "PushBlob", + Handler: _Push_PushBlob_Handler, + }, + { + MethodName: "PushDirectory", + Handler: _Push_PushDirectory_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "build/bazel/remote/asset/v1/remote_asset.proto", +} diff --git a/internal/proto/gen/build/bazel/remote/execution/v2/remote_execution.pb.go b/internal/proto/gen/build/bazel/remote/execution/v2/remote_execution.pb.go new file mode 100644 index 0000000..ee873fb --- /dev/null +++ b/internal/proto/gen/build/bazel/remote/execution/v2/remote_execution.pb.go @@ -0,0 +1,8259 @@ +// Copyright 2018 The Bazel Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.12 +// protoc (unknown) +// source: build/bazel/remote/execution/v2/remote_execution.proto + +package remoteexecution + +import ( + longrunningpb "cloud.google.com/go/longrunning/autogen/longrunningpb" + semver "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/semver" + _ "google.golang.org/genproto/googleapis/api/annotations" + status "google.golang.org/genproto/googleapis/rpc/status" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + anypb "google.golang.org/protobuf/types/known/anypb" + durationpb "google.golang.org/protobuf/types/known/durationpb" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" + wrapperspb "google.golang.org/protobuf/types/known/wrapperspb" + reflect "reflect" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type Command_OutputDirectoryFormat int32 + +const ( + // The client is only interested in receiving output directories in + // the form of a single Tree object, using the `tree_digest` field. + Command_TREE_ONLY Command_OutputDirectoryFormat = 0 + // The client is only interested in receiving output directories in + // the form of a hierarchy of separately stored Directory objects, + // using the `root_directory_digest` field. + Command_DIRECTORY_ONLY Command_OutputDirectoryFormat = 1 + // The client is interested in receiving output directories both in + // the form of a single Tree object and a hierarchy of separately + // stored Directory objects, using both the `tree_digest` and + // `root_directory_digest` fields. + Command_TREE_AND_DIRECTORY Command_OutputDirectoryFormat = 2 +) + +// Enum value maps for Command_OutputDirectoryFormat. +var ( + Command_OutputDirectoryFormat_name = map[int32]string{ + 0: "TREE_ONLY", + 1: "DIRECTORY_ONLY", + 2: "TREE_AND_DIRECTORY", + } + Command_OutputDirectoryFormat_value = map[string]int32{ + "TREE_ONLY": 0, + "DIRECTORY_ONLY": 1, + "TREE_AND_DIRECTORY": 2, + } +) + +func (x Command_OutputDirectoryFormat) Enum() *Command_OutputDirectoryFormat { + p := new(Command_OutputDirectoryFormat) + *p = x + return p +} + +func (x Command_OutputDirectoryFormat) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (Command_OutputDirectoryFormat) Descriptor() protoreflect.EnumDescriptor { + return file_build_bazel_remote_execution_v2_remote_execution_proto_enumTypes[0].Descriptor() +} + +func (Command_OutputDirectoryFormat) Type() protoreflect.EnumType { + return &file_build_bazel_remote_execution_v2_remote_execution_proto_enumTypes[0] +} + +func (x Command_OutputDirectoryFormat) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +type ExecutionStage_Value int32 + +const ( + // Invalid value. + ExecutionStage_UNKNOWN ExecutionStage_Value = 0 + // Checking the result against the cache. + ExecutionStage_CACHE_CHECK ExecutionStage_Value = 1 + // Currently idle, awaiting a free machine to execute. + ExecutionStage_QUEUED ExecutionStage_Value = 2 + // Currently being executed by a worker. + ExecutionStage_EXECUTING ExecutionStage_Value = 3 + // Finished execution. + ExecutionStage_COMPLETED ExecutionStage_Value = 4 +) + +// Enum value maps for ExecutionStage_Value. +var ( + ExecutionStage_Value_name = map[int32]string{ + 0: "UNKNOWN", + 1: "CACHE_CHECK", + 2: "QUEUED", + 3: "EXECUTING", + 4: "COMPLETED", + } + ExecutionStage_Value_value = map[string]int32{ + "UNKNOWN": 0, + "CACHE_CHECK": 1, + "QUEUED": 2, + "EXECUTING": 3, + "COMPLETED": 4, + } +) + +func (x ExecutionStage_Value) Enum() *ExecutionStage_Value { + p := new(ExecutionStage_Value) + *p = x + return p +} + +func (x ExecutionStage_Value) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ExecutionStage_Value) Descriptor() protoreflect.EnumDescriptor { + return file_build_bazel_remote_execution_v2_remote_execution_proto_enumTypes[1].Descriptor() +} + +func (ExecutionStage_Value) Type() protoreflect.EnumType { + return &file_build_bazel_remote_execution_v2_remote_execution_proto_enumTypes[1] +} + +func (x ExecutionStage_Value) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +type DigestFunction_Value int32 + +const ( + // It is an error for the server to return this value. + DigestFunction_UNKNOWN DigestFunction_Value = 0 + // The SHA-256 digest function. + DigestFunction_SHA256 DigestFunction_Value = 1 + // The SHA-1 digest function. + DigestFunction_SHA1 DigestFunction_Value = 2 + // The MD5 digest function. + DigestFunction_MD5 DigestFunction_Value = 3 + // The Microsoft "VSO-Hash" paged SHA256 digest function. + // See https://github.com/microsoft/BuildXL/blob/master/Documentation/Specs/PagedHash.md . + DigestFunction_VSO DigestFunction_Value = 4 + // The SHA-384 digest function. + DigestFunction_SHA384 DigestFunction_Value = 5 + // The SHA-512 digest function. + DigestFunction_SHA512 DigestFunction_Value = 6 + // Murmur3 128-bit digest function, x64 variant. Note that this is not a + // cryptographic hash function and its collision properties are not strongly guaranteed. + // See https://github.com/aappleby/smhasher/wiki/MurmurHash3 . + DigestFunction_MURMUR3 DigestFunction_Value = 7 + // The SHA-256 digest function, modified to use a Merkle tree for + // large objects. This permits implementations to store large blobs + // as a decomposed sequence of 2^j sized chunks, where j >= 10, + // while being able to validate integrity at the chunk level. + // + // Furthermore, on systems that do not offer dedicated instructions + // for computing SHA-256 hashes (e.g., the Intel SHA and ARMv8 + // cryptographic extensions), SHA256TREE hashes can be computed more + // efficiently than plain SHA-256 hashes by using generic SIMD + // extensions, such as Intel AVX2 or ARM NEON. + // + // SHA256TREE hashes are computed as follows: + // + // - For blobs that are 1024 bytes or smaller, the hash is computed + // using the regular SHA-256 digest function. + // + // - For blobs that are more than 1024 bytes in size, the hash is + // computed as follows: + // + // 1. The blob is partitioned into a left (leading) and right + // (trailing) blob. These blobs have lengths m and n + // respectively, where m = 2^k and 0 < n <= m. + // + // 2. Hashes of the left and right blob, Hash(left) and + // Hash(right) respectively, are computed by recursively + // applying the SHA256TREE algorithm. + // + // 3. A single invocation is made to the SHA-256 block cipher with + // the following parameters: + // + // M = Hash(left) || Hash(right) + // H = { + // 0xcbbb9d5d, 0x629a292a, 0x9159015a, 0x152fecd8, + // 0x67332667, 0x8eb44a87, 0xdb0c2e0d, 0x47b5481d, + // } + // + // The values of H are the leading fractional parts of the + // square roots of the 9th to the 16th prime number (23 to 53). + // This differs from plain SHA-256, where the first eight prime + // numbers (2 to 19) are used, thereby preventing trivial hash + // collisions between small and large objects. + // + // 4. The hash of the full blob can then be obtained by + // concatenating the outputs of the block cipher: + // + // Hash(blob) = a || b || c || d || e || f || g || h + // + // Addition of the original values of H, as normally done + // through the use of the Davies-Meyer structure, is not + // performed. This isn't necessary, as the block cipher is only + // invoked once. + // + // Test vectors of this digest function can be found in the + // accompanying sha256tree_test_vectors.txt file. + DigestFunction_SHA256TREE DigestFunction_Value = 8 + // The BLAKE3 hash function. + // See https://github.com/BLAKE3-team/BLAKE3. + DigestFunction_BLAKE3 DigestFunction_Value = 9 + // Identical to SHA1, except that "blob ${sizeBytes}\0" is prepended to + // the blob's contents before hashing, where ${sizeBytes} corresponds to + // the decimal size of the original blob. This allows hashes of files to + // be converted from and to the ones used by the Git version control + // system. + DigestFunction_GITSHA1 DigestFunction_Value = 10 +) + +// Enum value maps for DigestFunction_Value. +var ( + DigestFunction_Value_name = map[int32]string{ + 0: "UNKNOWN", + 1: "SHA256", + 2: "SHA1", + 3: "MD5", + 4: "VSO", + 5: "SHA384", + 6: "SHA512", + 7: "MURMUR3", + 8: "SHA256TREE", + 9: "BLAKE3", + 10: "GITSHA1", + } + DigestFunction_Value_value = map[string]int32{ + "UNKNOWN": 0, + "SHA256": 1, + "SHA1": 2, + "MD5": 3, + "VSO": 4, + "SHA384": 5, + "SHA512": 6, + "MURMUR3": 7, + "SHA256TREE": 8, + "BLAKE3": 9, + "GITSHA1": 10, + } +) + +func (x DigestFunction_Value) Enum() *DigestFunction_Value { + p := new(DigestFunction_Value) + *p = x + return p +} + +func (x DigestFunction_Value) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (DigestFunction_Value) Descriptor() protoreflect.EnumDescriptor { + return file_build_bazel_remote_execution_v2_remote_execution_proto_enumTypes[2].Descriptor() +} + +func (DigestFunction_Value) Type() protoreflect.EnumType { + return &file_build_bazel_remote_execution_v2_remote_execution_proto_enumTypes[2] +} + +func (x DigestFunction_Value) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +type ChunkingFunction_Value int32 + +const ( + // No specific algorithm. Servers MUST always accept this value. + // For SplitBlob, the server chooses the algorithm. For SpliceBlob, the + // server only verifies that chunks concatenate to form the expected blob. + ChunkingFunction_UNKNOWN ChunkingFunction_Value = 0 + // The FastCDC chunking algorithm as described in the 2020 paper by + // Wen Xia, et al. See https://ieeexplore.ieee.org/document/9055082 + // for details. + ChunkingFunction_FAST_CDC_2020 ChunkingFunction_Value = 1 + // The RepMaxCDC chunking algorithm as implemented by buildbarn/go-cdc. + // See https://github.com/buildbarn/go-cdc for details. + ChunkingFunction_REP_MAX_CDC ChunkingFunction_Value = 2 +) + +// Enum value maps for ChunkingFunction_Value. +var ( + ChunkingFunction_Value_name = map[int32]string{ + 0: "UNKNOWN", + 1: "FAST_CDC_2020", + 2: "REP_MAX_CDC", + } + ChunkingFunction_Value_value = map[string]int32{ + "UNKNOWN": 0, + "FAST_CDC_2020": 1, + "REP_MAX_CDC": 2, + } +) + +func (x ChunkingFunction_Value) Enum() *ChunkingFunction_Value { + p := new(ChunkingFunction_Value) + *p = x + return p +} + +func (x ChunkingFunction_Value) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ChunkingFunction_Value) Descriptor() protoreflect.EnumDescriptor { + return file_build_bazel_remote_execution_v2_remote_execution_proto_enumTypes[3].Descriptor() +} + +func (ChunkingFunction_Value) Type() protoreflect.EnumType { + return &file_build_bazel_remote_execution_v2_remote_execution_proto_enumTypes[3] +} + +func (x ChunkingFunction_Value) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +type SymlinkAbsolutePathStrategy_Value int32 + +const ( + // Invalid value. + SymlinkAbsolutePathStrategy_UNKNOWN SymlinkAbsolutePathStrategy_Value = 0 + // Server will return an `INVALID_ARGUMENT` on input symlinks with absolute + // targets. + // If an action tries to create an output symlink with an absolute target, a + // `FAILED_PRECONDITION` will be returned. + SymlinkAbsolutePathStrategy_DISALLOWED SymlinkAbsolutePathStrategy_Value = 1 + // Server will allow symlink targets to escape the input root tree, possibly + // resulting in non-hermetic builds. + SymlinkAbsolutePathStrategy_ALLOWED SymlinkAbsolutePathStrategy_Value = 2 +) + +// Enum value maps for SymlinkAbsolutePathStrategy_Value. +var ( + SymlinkAbsolutePathStrategy_Value_name = map[int32]string{ + 0: "UNKNOWN", + 1: "DISALLOWED", + 2: "ALLOWED", + } + SymlinkAbsolutePathStrategy_Value_value = map[string]int32{ + "UNKNOWN": 0, + "DISALLOWED": 1, + "ALLOWED": 2, + } +) + +func (x SymlinkAbsolutePathStrategy_Value) Enum() *SymlinkAbsolutePathStrategy_Value { + p := new(SymlinkAbsolutePathStrategy_Value) + *p = x + return p +} + +func (x SymlinkAbsolutePathStrategy_Value) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (SymlinkAbsolutePathStrategy_Value) Descriptor() protoreflect.EnumDescriptor { + return file_build_bazel_remote_execution_v2_remote_execution_proto_enumTypes[4].Descriptor() +} + +func (SymlinkAbsolutePathStrategy_Value) Type() protoreflect.EnumType { + return &file_build_bazel_remote_execution_v2_remote_execution_proto_enumTypes[4] +} + +func (x SymlinkAbsolutePathStrategy_Value) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +type Compressor_Value int32 + +const ( + // No compression. Servers and clients MUST always support this, and do + // not need to advertise it. + Compressor_IDENTITY Compressor_Value = 0 + // Zstandard compression. + Compressor_ZSTD Compressor_Value = 1 + // RFC 1951 Deflate. This format is identical to what is used by ZIP + // files. Headers such as the one generated by gzip are not + // included. + // + // It is advised to use algorithms such as Zstandard instead, as + // those are faster and/or provide a better compression ratio. + Compressor_DEFLATE Compressor_Value = 2 + // Brotli compression. + Compressor_BROTLI Compressor_Value = 3 +) + +// Enum value maps for Compressor_Value. +var ( + Compressor_Value_name = map[int32]string{ + 0: "IDENTITY", + 1: "ZSTD", + 2: "DEFLATE", + 3: "BROTLI", + } + Compressor_Value_value = map[string]int32{ + "IDENTITY": 0, + "ZSTD": 1, + "DEFLATE": 2, + "BROTLI": 3, + } +) + +func (x Compressor_Value) Enum() *Compressor_Value { + p := new(Compressor_Value) + *p = x + return p +} + +func (x Compressor_Value) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (Compressor_Value) Descriptor() protoreflect.EnumDescriptor { + return file_build_bazel_remote_execution_v2_remote_execution_proto_enumTypes[5].Descriptor() +} + +func (Compressor_Value) Type() protoreflect.EnumType { + return &file_build_bazel_remote_execution_v2_remote_execution_proto_enumTypes[5] +} + +func (x Compressor_Value) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// An `Action` captures all the information about an execution which is required +// to reproduce it. +// +// `Action`s are the core component of the [Execution] service. A single +// `Action` represents a repeatable action that can be performed by the +// execution service. `Action`s can be succinctly identified by the digest of +// their wire format encoding and, once an `Action` has been executed, will be +// cached in the action cache. Future requests can then use the cached result +// rather than needing to run afresh. +// +// When a server completes execution of an +// [Action][build.bazel.remote.execution.v2.Action], it MAY choose to +// cache the [result][build.bazel.remote.execution.v2.ActionResult] in +// the [ActionCache][build.bazel.remote.execution.v2.ActionCache] unless +// `do_not_cache` is `true`. Clients SHOULD expect the server to do so. By +// default, future calls to +// [Execute][build.bazel.remote.execution.v2.Execution.Execute] the same +// `Action` will also serve their results from the cache. Clients must take care +// to understand the caching behaviour. Ideally, all `Action`s will be +// reproducible so that serving a result from cache is always desirable and +// correct. +type Action struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_CommandDigest *Digest `protobuf:"bytes,1,opt,name=command_digest,json=commandDigest,proto3"` + xxx_hidden_InputRootDigest *Digest `protobuf:"bytes,2,opt,name=input_root_digest,json=inputRootDigest,proto3"` + xxx_hidden_Timeout *durationpb.Duration `protobuf:"bytes,6,opt,name=timeout,proto3"` + xxx_hidden_DoNotCache bool `protobuf:"varint,7,opt,name=do_not_cache,json=doNotCache,proto3"` + xxx_hidden_Salt []byte `protobuf:"bytes,9,opt,name=salt,proto3"` + xxx_hidden_Platform *Platform `protobuf:"bytes,10,opt,name=platform,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Action) Reset() { + *x = Action{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Action) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Action) ProtoMessage() {} + +func (x *Action) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *Action) GetCommandDigest() *Digest { + if x != nil { + return x.xxx_hidden_CommandDigest + } + return nil +} + +func (x *Action) GetInputRootDigest() *Digest { + if x != nil { + return x.xxx_hidden_InputRootDigest + } + return nil +} + +func (x *Action) GetTimeout() *durationpb.Duration { + if x != nil { + return x.xxx_hidden_Timeout + } + return nil +} + +func (x *Action) GetDoNotCache() bool { + if x != nil { + return x.xxx_hidden_DoNotCache + } + return false +} + +func (x *Action) GetSalt() []byte { + if x != nil { + return x.xxx_hidden_Salt + } + return nil +} + +func (x *Action) GetPlatform() *Platform { + if x != nil { + return x.xxx_hidden_Platform + } + return nil +} + +func (x *Action) SetCommandDigest(v *Digest) { + x.xxx_hidden_CommandDigest = v +} + +func (x *Action) SetInputRootDigest(v *Digest) { + x.xxx_hidden_InputRootDigest = v +} + +func (x *Action) SetTimeout(v *durationpb.Duration) { + x.xxx_hidden_Timeout = v +} + +func (x *Action) SetDoNotCache(v bool) { + x.xxx_hidden_DoNotCache = v +} + +func (x *Action) SetSalt(v []byte) { + if v == nil { + v = []byte{} + } + x.xxx_hidden_Salt = v +} + +func (x *Action) SetPlatform(v *Platform) { + x.xxx_hidden_Platform = v +} + +func (x *Action) HasCommandDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_CommandDigest != nil +} + +func (x *Action) HasInputRootDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_InputRootDigest != nil +} + +func (x *Action) HasTimeout() bool { + if x == nil { + return false + } + return x.xxx_hidden_Timeout != nil +} + +func (x *Action) HasPlatform() bool { + if x == nil { + return false + } + return x.xxx_hidden_Platform != nil +} + +func (x *Action) ClearCommandDigest() { + x.xxx_hidden_CommandDigest = nil +} + +func (x *Action) ClearInputRootDigest() { + x.xxx_hidden_InputRootDigest = nil +} + +func (x *Action) ClearTimeout() { + x.xxx_hidden_Timeout = nil +} + +func (x *Action) ClearPlatform() { + x.xxx_hidden_Platform = nil +} + +type Action_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The digest of the [Command][build.bazel.remote.execution.v2.Command] + // to run, which MUST be present in the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + CommandDigest *Digest + // The digest of the root + // [Directory][build.bazel.remote.execution.v2.Directory] for the input + // files. The files in the directory tree are available in the correct + // location on the build machine before the command is executed. The root + // directory, as well as every subdirectory and content blob referred to, MUST + // be in the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + InputRootDigest *Digest + // A timeout after which the execution should be killed. If the timeout is + // absent, then the client is specifying that the execution should continue + // as long as the server will let it. The server SHOULD impose a timeout if + // the client does not specify one, however, if the client does specify a + // timeout that is longer than the server's maximum timeout, the server MUST + // reject the request. + // + // The timeout is only intended to cover the "execution" of the specified + // action and not time in queue nor any overheads before or after execution + // such as marshalling inputs/outputs. The server SHOULD avoid including time + // spent the client doesn't have control over, and MAY extend or reduce the + // timeout to account for delays or speedups that occur during execution + // itself (e.g., lazily loading data from the Content Addressable Storage, + // live migration of virtual machines, emulation overhead). + // + // The timeout is a part of the + // [Action][build.bazel.remote.execution.v2.Action] message, and + // therefore two `Actions` with different timeouts are different, even if they + // are otherwise identical. This is because, if they were not, running an + // `Action` with a lower timeout than is required might result in a cache hit + // from an execution run with a longer timeout, hiding the fact that the + // timeout is too short. By encoding it directly in the `Action`, a lower + // timeout will result in a cache miss and the execution timeout will fail + // immediately, rather than whenever the cache entry gets evicted. + Timeout *durationpb.Duration + // If true, then the `Action`'s result cannot be cached, and in-flight + // requests for the same `Action` may not be merged. + DoNotCache bool + // An optional additional salt value used to place this `Action` into a + // separate cache namespace from other instances having the same field + // contents. This salt typically comes from operational configuration + // specific to sources such as repo and service configuration, + // and allows disowning an entire set of ActionResults that might have been + // poisoned by buggy software or tool failures. + Salt []byte + // The optional platform requirements for the execution environment. The + // server MAY choose to execute the action on any worker satisfying the + // requirements, so the client SHOULD ensure that running the action on any + // such worker will have the same result. A detailed lexicon for this can be + // found in the accompanying platform.md. + // New in version 2.2: clients SHOULD set these platform properties as well + // as those in the [Command][build.bazel.remote.execution.v2.Command]. Servers + // SHOULD prefer those set here. + Platform *Platform +} + +func (b0 Action_builder) Build() *Action { + m0 := &Action{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_CommandDigest = b.CommandDigest + x.xxx_hidden_InputRootDigest = b.InputRootDigest + x.xxx_hidden_Timeout = b.Timeout + x.xxx_hidden_DoNotCache = b.DoNotCache + x.xxx_hidden_Salt = b.Salt + x.xxx_hidden_Platform = b.Platform + return m0 +} + +// A `Command` is the actual command executed by a worker running an +// [Action][build.bazel.remote.execution.v2.Action] and specifications of its +// environment. +// +// Except as otherwise required, the environment (such as which system +// libraries or binaries are available, and what filesystems are mounted where) +// is defined by and specific to the implementation of the remote execution API. +type Command struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Arguments []string `protobuf:"bytes,1,rep,name=arguments,proto3"` + xxx_hidden_EnvironmentVariables *[]*Command_EnvironmentVariable `protobuf:"bytes,2,rep,name=environment_variables,json=environmentVariables,proto3"` + xxx_hidden_OutputFiles []string `protobuf:"bytes,3,rep,name=output_files,json=outputFiles,proto3"` + xxx_hidden_OutputDirectories []string `protobuf:"bytes,4,rep,name=output_directories,json=outputDirectories,proto3"` + xxx_hidden_OutputPaths []string `protobuf:"bytes,7,rep,name=output_paths,json=outputPaths,proto3"` + xxx_hidden_Platform *Platform `protobuf:"bytes,5,opt,name=platform,proto3"` + xxx_hidden_WorkingDirectory string `protobuf:"bytes,6,opt,name=working_directory,json=workingDirectory,proto3"` + xxx_hidden_OutputNodeProperties []string `protobuf:"bytes,8,rep,name=output_node_properties,json=outputNodeProperties,proto3"` + xxx_hidden_OutputDirectoryFormat Command_OutputDirectoryFormat `protobuf:"varint,9,opt,name=output_directory_format,json=outputDirectoryFormat,proto3,enum=build.bazel.remote.execution.v2.Command_OutputDirectoryFormat"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Command) Reset() { + *x = Command{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Command) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Command) ProtoMessage() {} + +func (x *Command) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *Command) GetArguments() []string { + if x != nil { + return x.xxx_hidden_Arguments + } + return nil +} + +func (x *Command) GetEnvironmentVariables() []*Command_EnvironmentVariable { + if x != nil { + if x.xxx_hidden_EnvironmentVariables != nil { + return *x.xxx_hidden_EnvironmentVariables + } + } + return nil +} + +// Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. +func (x *Command) GetOutputFiles() []string { + if x != nil { + return x.xxx_hidden_OutputFiles + } + return nil +} + +// Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. +func (x *Command) GetOutputDirectories() []string { + if x != nil { + return x.xxx_hidden_OutputDirectories + } + return nil +} + +func (x *Command) GetOutputPaths() []string { + if x != nil { + return x.xxx_hidden_OutputPaths + } + return nil +} + +// Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. +func (x *Command) GetPlatform() *Platform { + if x != nil { + return x.xxx_hidden_Platform + } + return nil +} + +func (x *Command) GetWorkingDirectory() string { + if x != nil { + return x.xxx_hidden_WorkingDirectory + } + return "" +} + +func (x *Command) GetOutputNodeProperties() []string { + if x != nil { + return x.xxx_hidden_OutputNodeProperties + } + return nil +} + +func (x *Command) GetOutputDirectoryFormat() Command_OutputDirectoryFormat { + if x != nil { + return x.xxx_hidden_OutputDirectoryFormat + } + return Command_TREE_ONLY +} + +func (x *Command) SetArguments(v []string) { + x.xxx_hidden_Arguments = v +} + +func (x *Command) SetEnvironmentVariables(v []*Command_EnvironmentVariable) { + x.xxx_hidden_EnvironmentVariables = &v +} + +// Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. +func (x *Command) SetOutputFiles(v []string) { + x.xxx_hidden_OutputFiles = v +} + +// Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. +func (x *Command) SetOutputDirectories(v []string) { + x.xxx_hidden_OutputDirectories = v +} + +func (x *Command) SetOutputPaths(v []string) { + x.xxx_hidden_OutputPaths = v +} + +// Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. +func (x *Command) SetPlatform(v *Platform) { + x.xxx_hidden_Platform = v +} + +func (x *Command) SetWorkingDirectory(v string) { + x.xxx_hidden_WorkingDirectory = v +} + +func (x *Command) SetOutputNodeProperties(v []string) { + x.xxx_hidden_OutputNodeProperties = v +} + +func (x *Command) SetOutputDirectoryFormat(v Command_OutputDirectoryFormat) { + x.xxx_hidden_OutputDirectoryFormat = v +} + +// Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. +func (x *Command) HasPlatform() bool { + if x == nil { + return false + } + return x.xxx_hidden_Platform != nil +} + +// Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. +func (x *Command) ClearPlatform() { + x.xxx_hidden_Platform = nil +} + +type Command_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The arguments to the command. + // + // The first argument specifies the command to run, which may be either an + // absolute path, a path relative to the working directory, or an unqualified + // path (without path separators) which will be resolved using the operating + // system's equivalent of the PATH environment variable. Path separators + // native to the operating system running on the worker SHOULD be used. If the + // `environment_variables` list contains an entry for the PATH environment + // variable, it SHOULD be respected. If not, the resolution process is + // implementation-defined. + // + // Changed in v2.3. v2.2 and older require that no PATH lookups are performed, + // and that relative paths are resolved relative to the input root. This + // behavior can, however, not be relied upon, as most implementations already + // followed the rules described above. + Arguments []string + // The environment variables to set when running the program. The worker may + // provide its own default environment variables; these defaults can be + // overridden using this field. Additional variables can also be specified. + // + // In order to ensure that equivalent + // [Command][build.bazel.remote.execution.v2.Command]s always hash to the same + // value, the environment variables MUST be lexicographically sorted by name. + // Sorting of strings is done by code point, equivalently, by the UTF-8 bytes. + EnvironmentVariables []*Command_EnvironmentVariable + // A list of the output files that the client expects to retrieve from the + // action. Only the listed files, as well as directories listed in + // `output_directories`, will be returned to the client as output. + // Other files or directories that may be created during command execution + // are discarded. + // + // The paths are relative to the working directory of the action execution. + // The paths are specified using a single forward slash (`/`) as a path + // separator, even if the execution platform natively uses a different + // separator. The path MUST NOT include a trailing slash, nor a leading slash, + // being a relative path. + // + // In order to ensure consistent hashing of the same Action, the output paths + // MUST be sorted lexicographically by code point (or, equivalently, by UTF-8 + // bytes). + // + // An output file cannot be duplicated, be a parent of another output file, or + // have the same path as any of the listed output directories. + // + // Directories leading up to the output files are created by the worker prior + // to execution, even if they are not explicitly part of the input root. + // + // DEPRECATED since v2.1: Use `output_paths` instead. + // + // Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. + OutputFiles []string + // A list of the output directories that the client expects to retrieve from + // the action. Only the listed directories will be returned (an entire + // directory structure will be returned as a + // [Tree][build.bazel.remote.execution.v2.Tree] message digest, see + // [OutputDirectory][build.bazel.remote.execution.v2.OutputDirectory]), as + // well as files listed in `output_files`. Other files or directories that + // may be created during command execution are discarded. + // + // The paths are relative to the working directory of the action execution. + // The paths are specified using a single forward slash (`/`) as a path + // separator, even if the execution platform natively uses a different + // separator. The path MUST NOT include a trailing slash, nor a leading slash, + // being a relative path. The special value of empty string is allowed, + // although not recommended, and can be used to capture the entire working + // directory tree, including inputs. + // + // In order to ensure consistent hashing of the same Action, the output paths + // MUST be sorted lexicographically by code point (or, equivalently, by UTF-8 + // bytes). + // + // An output directory cannot be duplicated or have the same path as any of + // the listed output files. An output directory is allowed to be a parent of + // another output directory. + // + // Directories leading up to the output directories (but not the output + // directories themselves) are created by the worker prior to execution, even + // if they are not explicitly part of the input root. + // + // DEPRECATED since 2.1: Use `output_paths` instead. + // + // Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. + OutputDirectories []string + // A list of the output paths that the client expects to retrieve from the + // action. Only the listed paths will be returned to the client as output. + // The type of the output (file or directory) is not specified, and will be + // determined by the server after action execution. If the resulting path is + // a file, it will be returned in an + // [OutputFile][build.bazel.remote.execution.v2.OutputFile] typed field. + // If the path is a directory, the entire directory structure will be returned + // as a [Tree][build.bazel.remote.execution.v2.Tree] message digest, see + // [OutputDirectory][build.bazel.remote.execution.v2.OutputDirectory] + // Other files or directories that may be created during command execution + // are discarded. + // + // The paths are relative to the working directory of the action execution. + // The paths are specified using a single forward slash (`/`) as a path + // separator, even if the execution platform natively uses a different + // separator. The path MUST NOT include a trailing slash, nor a leading slash, + // being a relative path. + // + // In order to ensure consistent hashing of the same Action, the output paths + // MUST be deduplicated and sorted lexicographically by code point (or, + // equivalently, by UTF-8 bytes). + // + // Directories leading up to the output paths are created by the worker prior + // to execution, even if they are not explicitly part of the input root. + // + // New in v2.1: this field supersedes the DEPRECATED `output_files` and + // `output_directories` fields. If `output_paths` is used, `output_files` and + // `output_directories` will be ignored! + OutputPaths []string + // The platform requirements for the execution environment. The server MAY + // choose to execute the action on any worker satisfying the requirements, so + // the client SHOULD ensure that running the action on any such worker will + // have the same result. A detailed lexicon for this can be found in the + // accompanying platform.md. + // DEPRECATED as of v2.2: platform properties are now specified directly in + // the action. See documentation note in the + // [Action][build.bazel.remote.execution.v2.Action] for migration. + // + // Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. + Platform *Platform + // The working directory, relative to the input root, for the command to run + // in. It must be a directory which exists in the input tree. If it is left + // empty, then the action is run in the input root. + WorkingDirectory string + // A list of keys for node properties the client expects to retrieve for + // output files and directories. Keys are either names of string-based + // [NodeProperty][build.bazel.remote.execution.v2.NodeProperty] or + // names of fields in [NodeProperties][build.bazel.remote.execution.v2.NodeProperties]. + // In order to ensure that equivalent `Action`s always hash to the same + // value, the node properties MUST be lexicographically sorted by name. + // Sorting of strings is done by code point, equivalently, by the UTF-8 bytes. + // + // The interpretation of string-based properties is server-dependent. If a + // property is not recognized by the server, the server will return an + // `INVALID_ARGUMENT`. + OutputNodeProperties []string + // The format that the worker should use to store the contents of + // output directories. + // + // In case this field is set to a value that is not supported by the + // worker, the worker SHOULD interpret this field as TREE_ONLY. The + // worker MAY store output directories in formats that are a superset + // of what was requested (e.g., interpreting DIRECTORY_ONLY as + // TREE_AND_DIRECTORY). + OutputDirectoryFormat Command_OutputDirectoryFormat +} + +func (b0 Command_builder) Build() *Command { + m0 := &Command{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Arguments = b.Arguments + x.xxx_hidden_EnvironmentVariables = &b.EnvironmentVariables + x.xxx_hidden_OutputFiles = b.OutputFiles + x.xxx_hidden_OutputDirectories = b.OutputDirectories + x.xxx_hidden_OutputPaths = b.OutputPaths + x.xxx_hidden_Platform = b.Platform + x.xxx_hidden_WorkingDirectory = b.WorkingDirectory + x.xxx_hidden_OutputNodeProperties = b.OutputNodeProperties + x.xxx_hidden_OutputDirectoryFormat = b.OutputDirectoryFormat + return m0 +} + +// A `Platform` is a set of requirements, such as hardware, operating system, or +// compiler toolchain, for an +// [Action][build.bazel.remote.execution.v2.Action]'s execution +// environment. A `Platform` is represented as a series of key-value pairs +// representing the properties that are required of the platform. +type Platform struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Properties *[]*Platform_Property `protobuf:"bytes,1,rep,name=properties,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Platform) Reset() { + *x = Platform{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Platform) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Platform) ProtoMessage() {} + +func (x *Platform) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *Platform) GetProperties() []*Platform_Property { + if x != nil { + if x.xxx_hidden_Properties != nil { + return *x.xxx_hidden_Properties + } + } + return nil +} + +func (x *Platform) SetProperties(v []*Platform_Property) { + x.xxx_hidden_Properties = &v +} + +type Platform_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The properties that make up this platform. In order to ensure that + // equivalent `Platform`s always hash to the same value, the properties MUST + // be lexicographically sorted by name, and then by value. Sorting of strings + // is done by code point, equivalently, by the UTF-8 bytes. + Properties []*Platform_Property +} + +func (b0 Platform_builder) Build() *Platform { + m0 := &Platform{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Properties = &b.Properties + return m0 +} + +// A `Directory` represents a directory node in a file tree, containing zero or +// more children [FileNodes][build.bazel.remote.execution.v2.FileNode], +// [DirectoryNodes][build.bazel.remote.execution.v2.DirectoryNode] and +// [SymlinkNodes][build.bazel.remote.execution.v2.SymlinkNode]. +// Each `Node` contains its name in the directory, either the digest of its +// content (either a file blob or a `Directory` proto) or a symlink target, as +// well as possibly some metadata about the file or directory. +// +// In order to ensure that two equivalent directory trees hash to the same +// value, the following restrictions MUST be obeyed when constructing +// a `Directory`: +// +// - Every child in the directory must have a path of exactly one segment. +// Multiple levels of directory hierarchy may not be collapsed. +// - Each child in the directory must have a unique path segment (file name). +// Note that while the API itself is case-sensitive, the environment where +// the Action is executed may or may not be case-sensitive. That is, it is +// legal to call the API with a Directory that has both "Foo" and "foo" as +// children, but the Action may be rejected by the remote system upon +// execution. +// - The files, directories and symlinks in the directory must each be sorted +// in lexicographical order by path. The path strings must be sorted by code +// point, equivalently, by UTF-8 bytes. +// - The [NodeProperties][build.bazel.remote.execution.v2.NodeProperty] of files, +// directories, and symlinks must be sorted in lexicographical order by +// property name. +// +// A `Directory` that obeys the restrictions is said to be in canonical form. +// +// As an example, the following could be used for a file named `bar` and a +// directory named `foo` with an executable file named `baz` (hashes shortened +// for readability): +// +// ```json +// // (Directory proto) +// +// { +// files: [ +// { +// name: "bar", +// digest: { +// hash: "4a73bc9d03...", +// size: 65534 +// }, +// node_properties: [ +// { +// "name": "MTime", +// "value": "2017-01-15T01:30:15.01Z" +// } +// ] +// } +// ], +// directories: [ +// { +// name: "foo", +// digest: { +// hash: "4cf2eda940...", +// size: 43 +// } +// } +// ] +// } +// +// // (Directory proto with hash "4cf2eda940..." and size 43) +// +// { +// files: [ +// { +// name: "baz", +// digest: { +// hash: "b2c941073e...", +// size: 1294, +// }, +// is_executable: true +// } +// ] +// } +// +// ``` +type Directory struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Files *[]*FileNode `protobuf:"bytes,1,rep,name=files,proto3"` + xxx_hidden_Directories *[]*DirectoryNode `protobuf:"bytes,2,rep,name=directories,proto3"` + xxx_hidden_Symlinks *[]*SymlinkNode `protobuf:"bytes,3,rep,name=symlinks,proto3"` + xxx_hidden_NodeProperties *NodeProperties `protobuf:"bytes,5,opt,name=node_properties,json=nodeProperties,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Directory) Reset() { + *x = Directory{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Directory) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Directory) ProtoMessage() {} + +func (x *Directory) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *Directory) GetFiles() []*FileNode { + if x != nil { + if x.xxx_hidden_Files != nil { + return *x.xxx_hidden_Files + } + } + return nil +} + +func (x *Directory) GetDirectories() []*DirectoryNode { + if x != nil { + if x.xxx_hidden_Directories != nil { + return *x.xxx_hidden_Directories + } + } + return nil +} + +func (x *Directory) GetSymlinks() []*SymlinkNode { + if x != nil { + if x.xxx_hidden_Symlinks != nil { + return *x.xxx_hidden_Symlinks + } + } + return nil +} + +func (x *Directory) GetNodeProperties() *NodeProperties { + if x != nil { + return x.xxx_hidden_NodeProperties + } + return nil +} + +func (x *Directory) SetFiles(v []*FileNode) { + x.xxx_hidden_Files = &v +} + +func (x *Directory) SetDirectories(v []*DirectoryNode) { + x.xxx_hidden_Directories = &v +} + +func (x *Directory) SetSymlinks(v []*SymlinkNode) { + x.xxx_hidden_Symlinks = &v +} + +func (x *Directory) SetNodeProperties(v *NodeProperties) { + x.xxx_hidden_NodeProperties = v +} + +func (x *Directory) HasNodeProperties() bool { + if x == nil { + return false + } + return x.xxx_hidden_NodeProperties != nil +} + +func (x *Directory) ClearNodeProperties() { + x.xxx_hidden_NodeProperties = nil +} + +type Directory_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The files in the directory. + Files []*FileNode + // The subdirectories in the directory. + Directories []*DirectoryNode + // The symlinks in the directory. + Symlinks []*SymlinkNode + NodeProperties *NodeProperties +} + +func (b0 Directory_builder) Build() *Directory { + m0 := &Directory{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Files = &b.Files + x.xxx_hidden_Directories = &b.Directories + x.xxx_hidden_Symlinks = &b.Symlinks + x.xxx_hidden_NodeProperties = b.NodeProperties + return m0 +} + +// A single property for [FileNodes][build.bazel.remote.execution.v2.FileNode], +// [DirectoryNodes][build.bazel.remote.execution.v2.DirectoryNode], and +// [SymlinkNodes][build.bazel.remote.execution.v2.SymlinkNode]. The server is +// responsible for specifying the property `name`s that it accepts. If +// permitted by the server, the same `name` may occur multiple times. +type NodeProperty struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Name string `protobuf:"bytes,1,opt,name=name,proto3"` + xxx_hidden_Value string `protobuf:"bytes,2,opt,name=value,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *NodeProperty) Reset() { + *x = NodeProperty{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *NodeProperty) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*NodeProperty) ProtoMessage() {} + +func (x *NodeProperty) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *NodeProperty) GetName() string { + if x != nil { + return x.xxx_hidden_Name + } + return "" +} + +func (x *NodeProperty) GetValue() string { + if x != nil { + return x.xxx_hidden_Value + } + return "" +} + +func (x *NodeProperty) SetName(v string) { + x.xxx_hidden_Name = v +} + +func (x *NodeProperty) SetValue(v string) { + x.xxx_hidden_Value = v +} + +type NodeProperty_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The property name. + Name string + // The property value. + Value string +} + +func (b0 NodeProperty_builder) Build() *NodeProperty { + m0 := &NodeProperty{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Name = b.Name + x.xxx_hidden_Value = b.Value + return m0 +} + +// Node properties for [FileNodes][build.bazel.remote.execution.v2.FileNode], +// [DirectoryNodes][build.bazel.remote.execution.v2.DirectoryNode], and +// [SymlinkNodes][build.bazel.remote.execution.v2.SymlinkNode]. The server is +// responsible for specifying the properties that it accepts. +type NodeProperties struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Properties *[]*NodeProperty `protobuf:"bytes,1,rep,name=properties,proto3"` + xxx_hidden_Mtime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=mtime,proto3"` + xxx_hidden_UnixMode *wrapperspb.UInt32Value `protobuf:"bytes,3,opt,name=unix_mode,json=unixMode,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *NodeProperties) Reset() { + *x = NodeProperties{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *NodeProperties) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*NodeProperties) ProtoMessage() {} + +func (x *NodeProperties) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *NodeProperties) GetProperties() []*NodeProperty { + if x != nil { + if x.xxx_hidden_Properties != nil { + return *x.xxx_hidden_Properties + } + } + return nil +} + +func (x *NodeProperties) GetMtime() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_Mtime + } + return nil +} + +func (x *NodeProperties) GetUnixMode() *wrapperspb.UInt32Value { + if x != nil { + return x.xxx_hidden_UnixMode + } + return nil +} + +func (x *NodeProperties) SetProperties(v []*NodeProperty) { + x.xxx_hidden_Properties = &v +} + +func (x *NodeProperties) SetMtime(v *timestamppb.Timestamp) { + x.xxx_hidden_Mtime = v +} + +func (x *NodeProperties) SetUnixMode(v *wrapperspb.UInt32Value) { + x.xxx_hidden_UnixMode = v +} + +func (x *NodeProperties) HasMtime() bool { + if x == nil { + return false + } + return x.xxx_hidden_Mtime != nil +} + +func (x *NodeProperties) HasUnixMode() bool { + if x == nil { + return false + } + return x.xxx_hidden_UnixMode != nil +} + +func (x *NodeProperties) ClearMtime() { + x.xxx_hidden_Mtime = nil +} + +func (x *NodeProperties) ClearUnixMode() { + x.xxx_hidden_UnixMode = nil +} + +type NodeProperties_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // A list of string-based + // [NodeProperties][build.bazel.remote.execution.v2.NodeProperty]. + Properties []*NodeProperty + // The file's last modification timestamp. + Mtime *timestamppb.Timestamp + // The UNIX file mode, e.g., 0755. + UnixMode *wrapperspb.UInt32Value +} + +func (b0 NodeProperties_builder) Build() *NodeProperties { + m0 := &NodeProperties{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Properties = &b.Properties + x.xxx_hidden_Mtime = b.Mtime + x.xxx_hidden_UnixMode = b.UnixMode + return m0 +} + +// A `FileNode` represents a single file and associated metadata. +type FileNode struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Name string `protobuf:"bytes,1,opt,name=name,proto3"` + xxx_hidden_Digest *Digest `protobuf:"bytes,2,opt,name=digest,proto3"` + xxx_hidden_IsExecutable bool `protobuf:"varint,4,opt,name=is_executable,json=isExecutable,proto3"` + xxx_hidden_NodeProperties *NodeProperties `protobuf:"bytes,6,opt,name=node_properties,json=nodeProperties,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FileNode) Reset() { + *x = FileNode{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FileNode) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FileNode) ProtoMessage() {} + +func (x *FileNode) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[6] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *FileNode) GetName() string { + if x != nil { + return x.xxx_hidden_Name + } + return "" +} + +func (x *FileNode) GetDigest() *Digest { + if x != nil { + return x.xxx_hidden_Digest + } + return nil +} + +func (x *FileNode) GetIsExecutable() bool { + if x != nil { + return x.xxx_hidden_IsExecutable + } + return false +} + +func (x *FileNode) GetNodeProperties() *NodeProperties { + if x != nil { + return x.xxx_hidden_NodeProperties + } + return nil +} + +func (x *FileNode) SetName(v string) { + x.xxx_hidden_Name = v +} + +func (x *FileNode) SetDigest(v *Digest) { + x.xxx_hidden_Digest = v +} + +func (x *FileNode) SetIsExecutable(v bool) { + x.xxx_hidden_IsExecutable = v +} + +func (x *FileNode) SetNodeProperties(v *NodeProperties) { + x.xxx_hidden_NodeProperties = v +} + +func (x *FileNode) HasDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_Digest != nil +} + +func (x *FileNode) HasNodeProperties() bool { + if x == nil { + return false + } + return x.xxx_hidden_NodeProperties != nil +} + +func (x *FileNode) ClearDigest() { + x.xxx_hidden_Digest = nil +} + +func (x *FileNode) ClearNodeProperties() { + x.xxx_hidden_NodeProperties = nil +} + +type FileNode_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The name of the file. + Name string + // The digest of the file's content. + Digest *Digest + // True if file is executable, false otherwise. + IsExecutable bool + NodeProperties *NodeProperties +} + +func (b0 FileNode_builder) Build() *FileNode { + m0 := &FileNode{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Name = b.Name + x.xxx_hidden_Digest = b.Digest + x.xxx_hidden_IsExecutable = b.IsExecutable + x.xxx_hidden_NodeProperties = b.NodeProperties + return m0 +} + +// A `DirectoryNode` represents a child of a +// [Directory][build.bazel.remote.execution.v2.Directory] which is itself +// a `Directory` and its associated metadata. +type DirectoryNode struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Name string `protobuf:"bytes,1,opt,name=name,proto3"` + xxx_hidden_Digest *Digest `protobuf:"bytes,2,opt,name=digest,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DirectoryNode) Reset() { + *x = DirectoryNode{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DirectoryNode) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DirectoryNode) ProtoMessage() {} + +func (x *DirectoryNode) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[7] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *DirectoryNode) GetName() string { + if x != nil { + return x.xxx_hidden_Name + } + return "" +} + +func (x *DirectoryNode) GetDigest() *Digest { + if x != nil { + return x.xxx_hidden_Digest + } + return nil +} + +func (x *DirectoryNode) SetName(v string) { + x.xxx_hidden_Name = v +} + +func (x *DirectoryNode) SetDigest(v *Digest) { + x.xxx_hidden_Digest = v +} + +func (x *DirectoryNode) HasDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_Digest != nil +} + +func (x *DirectoryNode) ClearDigest() { + x.xxx_hidden_Digest = nil +} + +type DirectoryNode_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The name of the directory. + Name string + // The digest of the + // [Directory][build.bazel.remote.execution.v2.Directory] object + // represented. See [Digest][build.bazel.remote.execution.v2.Digest] + // for information about how to take the digest of a proto message. + Digest *Digest +} + +func (b0 DirectoryNode_builder) Build() *DirectoryNode { + m0 := &DirectoryNode{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Name = b.Name + x.xxx_hidden_Digest = b.Digest + return m0 +} + +// A `SymlinkNode` represents a symbolic link. +type SymlinkNode struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Name string `protobuf:"bytes,1,opt,name=name,proto3"` + xxx_hidden_Target string `protobuf:"bytes,2,opt,name=target,proto3"` + xxx_hidden_NodeProperties *NodeProperties `protobuf:"bytes,4,opt,name=node_properties,json=nodeProperties,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SymlinkNode) Reset() { + *x = SymlinkNode{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SymlinkNode) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SymlinkNode) ProtoMessage() {} + +func (x *SymlinkNode) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *SymlinkNode) GetName() string { + if x != nil { + return x.xxx_hidden_Name + } + return "" +} + +func (x *SymlinkNode) GetTarget() string { + if x != nil { + return x.xxx_hidden_Target + } + return "" +} + +func (x *SymlinkNode) GetNodeProperties() *NodeProperties { + if x != nil { + return x.xxx_hidden_NodeProperties + } + return nil +} + +func (x *SymlinkNode) SetName(v string) { + x.xxx_hidden_Name = v +} + +func (x *SymlinkNode) SetTarget(v string) { + x.xxx_hidden_Target = v +} + +func (x *SymlinkNode) SetNodeProperties(v *NodeProperties) { + x.xxx_hidden_NodeProperties = v +} + +func (x *SymlinkNode) HasNodeProperties() bool { + if x == nil { + return false + } + return x.xxx_hidden_NodeProperties != nil +} + +func (x *SymlinkNode) ClearNodeProperties() { + x.xxx_hidden_NodeProperties = nil +} + +type SymlinkNode_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The name of the symlink. + Name string + // The target path of the symlink. The path separator is a forward slash `/`. + // The target path can be relative to the parent directory of the symlink or + // it can be an absolute path starting with `/`. Support for absolute paths + // can be checked using the [Capabilities][build.bazel.remote.execution.v2.Capabilities] + // API. `..` components are allowed anywhere in the target path as logical + // canonicalization may lead to different behavior in the presence of + // directory symlinks (e.g. `foo/../bar` may not be the same as `bar`). + // To reduce potential cache misses, canonicalization is still recommended + // where this is possible without impacting correctness. + Target string + NodeProperties *NodeProperties +} + +func (b0 SymlinkNode_builder) Build() *SymlinkNode { + m0 := &SymlinkNode{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Name = b.Name + x.xxx_hidden_Target = b.Target + x.xxx_hidden_NodeProperties = b.NodeProperties + return m0 +} + +// A content digest. A digest for a given blob consists of the size of the blob +// and its hash. The hash algorithm to use is defined by the server. +// +// The size is considered to be an integral part of the digest and cannot be +// separated. That is, even if the `hash` field is correctly specified but +// `size_bytes` is not, the server MUST reject the request. +// +// The reason for including the size in the digest is as follows: in a great +// many cases, the server needs to know the size of the blob it is about to work +// with prior to starting an operation with it, such as flattening Merkle tree +// structures or streaming it to a worker. Technically, the server could +// implement a separate metadata store, but this results in a significantly more +// complicated implementation as opposed to having the client specify the size +// up-front (or storing the size along with the digest in every message where +// digests are embedded). This does mean that the API leaks some implementation +// details of (what we consider to be) a reasonable server implementation, but +// we consider this to be a worthwhile tradeoff. +// +// When a `Digest` is used to refer to a proto message, it always refers to the +// message in binary encoded form. To ensure consistent hashing, clients and +// servers MUST ensure that they serialize messages according to the following +// rules, even if there are alternate valid encodings for the same message: +// +// * Fields are serialized in tag order. +// * There are no unknown fields. +// * There are no duplicate fields. +// * Fields are serialized according to the default semantics for their type. +// +// Most protocol buffer implementations will always follow these rules when +// serializing, but care should be taken to avoid shortcuts. For instance, +// concatenating two messages to merge them may produce duplicate fields. +type Digest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Hash string `protobuf:"bytes,1,opt,name=hash,proto3"` + xxx_hidden_SizeBytes int64 `protobuf:"varint,2,opt,name=size_bytes,json=sizeBytes,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Digest) Reset() { + *x = Digest{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Digest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Digest) ProtoMessage() {} + +func (x *Digest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *Digest) GetHash() string { + if x != nil { + return x.xxx_hidden_Hash + } + return "" +} + +func (x *Digest) GetSizeBytes() int64 { + if x != nil { + return x.xxx_hidden_SizeBytes + } + return 0 +} + +func (x *Digest) SetHash(v string) { + x.xxx_hidden_Hash = v +} + +func (x *Digest) SetSizeBytes(v int64) { + x.xxx_hidden_SizeBytes = v +} + +type Digest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The hash, represented as a lowercase hexadecimal string, padded with + // leading zeroes up to the hash function length. + Hash string + // The size of the blob, in bytes. + SizeBytes int64 +} + +func (b0 Digest_builder) Build() *Digest { + m0 := &Digest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Hash = b.Hash + x.xxx_hidden_SizeBytes = b.SizeBytes + return m0 +} + +// ExecutedActionMetadata contains details about a completed execution. +type ExecutedActionMetadata struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Worker string `protobuf:"bytes,1,opt,name=worker,proto3"` + xxx_hidden_QueuedTimestamp *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=queued_timestamp,json=queuedTimestamp,proto3"` + xxx_hidden_WorkerStartTimestamp *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=worker_start_timestamp,json=workerStartTimestamp,proto3"` + xxx_hidden_WorkerCompletedTimestamp *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=worker_completed_timestamp,json=workerCompletedTimestamp,proto3"` + xxx_hidden_InputFetchStartTimestamp *timestamppb.Timestamp `protobuf:"bytes,5,opt,name=input_fetch_start_timestamp,json=inputFetchStartTimestamp,proto3"` + xxx_hidden_InputFetchCompletedTimestamp *timestamppb.Timestamp `protobuf:"bytes,6,opt,name=input_fetch_completed_timestamp,json=inputFetchCompletedTimestamp,proto3"` + xxx_hidden_ExecutionStartTimestamp *timestamppb.Timestamp `protobuf:"bytes,7,opt,name=execution_start_timestamp,json=executionStartTimestamp,proto3"` + xxx_hidden_ExecutionCompletedTimestamp *timestamppb.Timestamp `protobuf:"bytes,8,opt,name=execution_completed_timestamp,json=executionCompletedTimestamp,proto3"` + xxx_hidden_VirtualExecutionDuration *durationpb.Duration `protobuf:"bytes,12,opt,name=virtual_execution_duration,json=virtualExecutionDuration,proto3"` + xxx_hidden_OutputUploadStartTimestamp *timestamppb.Timestamp `protobuf:"bytes,9,opt,name=output_upload_start_timestamp,json=outputUploadStartTimestamp,proto3"` + xxx_hidden_OutputUploadCompletedTimestamp *timestamppb.Timestamp `protobuf:"bytes,10,opt,name=output_upload_completed_timestamp,json=outputUploadCompletedTimestamp,proto3"` + xxx_hidden_AuxiliaryMetadata *[]*anypb.Any `protobuf:"bytes,11,rep,name=auxiliary_metadata,json=auxiliaryMetadata,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ExecutedActionMetadata) Reset() { + *x = ExecutedActionMetadata{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ExecutedActionMetadata) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExecutedActionMetadata) ProtoMessage() {} + +func (x *ExecutedActionMetadata) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *ExecutedActionMetadata) GetWorker() string { + if x != nil { + return x.xxx_hidden_Worker + } + return "" +} + +func (x *ExecutedActionMetadata) GetQueuedTimestamp() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_QueuedTimestamp + } + return nil +} + +func (x *ExecutedActionMetadata) GetWorkerStartTimestamp() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_WorkerStartTimestamp + } + return nil +} + +func (x *ExecutedActionMetadata) GetWorkerCompletedTimestamp() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_WorkerCompletedTimestamp + } + return nil +} + +func (x *ExecutedActionMetadata) GetInputFetchStartTimestamp() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_InputFetchStartTimestamp + } + return nil +} + +func (x *ExecutedActionMetadata) GetInputFetchCompletedTimestamp() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_InputFetchCompletedTimestamp + } + return nil +} + +func (x *ExecutedActionMetadata) GetExecutionStartTimestamp() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_ExecutionStartTimestamp + } + return nil +} + +func (x *ExecutedActionMetadata) GetExecutionCompletedTimestamp() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_ExecutionCompletedTimestamp + } + return nil +} + +func (x *ExecutedActionMetadata) GetVirtualExecutionDuration() *durationpb.Duration { + if x != nil { + return x.xxx_hidden_VirtualExecutionDuration + } + return nil +} + +func (x *ExecutedActionMetadata) GetOutputUploadStartTimestamp() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_OutputUploadStartTimestamp + } + return nil +} + +func (x *ExecutedActionMetadata) GetOutputUploadCompletedTimestamp() *timestamppb.Timestamp { + if x != nil { + return x.xxx_hidden_OutputUploadCompletedTimestamp + } + return nil +} + +func (x *ExecutedActionMetadata) GetAuxiliaryMetadata() []*anypb.Any { + if x != nil { + if x.xxx_hidden_AuxiliaryMetadata != nil { + return *x.xxx_hidden_AuxiliaryMetadata + } + } + return nil +} + +func (x *ExecutedActionMetadata) SetWorker(v string) { + x.xxx_hidden_Worker = v +} + +func (x *ExecutedActionMetadata) SetQueuedTimestamp(v *timestamppb.Timestamp) { + x.xxx_hidden_QueuedTimestamp = v +} + +func (x *ExecutedActionMetadata) SetWorkerStartTimestamp(v *timestamppb.Timestamp) { + x.xxx_hidden_WorkerStartTimestamp = v +} + +func (x *ExecutedActionMetadata) SetWorkerCompletedTimestamp(v *timestamppb.Timestamp) { + x.xxx_hidden_WorkerCompletedTimestamp = v +} + +func (x *ExecutedActionMetadata) SetInputFetchStartTimestamp(v *timestamppb.Timestamp) { + x.xxx_hidden_InputFetchStartTimestamp = v +} + +func (x *ExecutedActionMetadata) SetInputFetchCompletedTimestamp(v *timestamppb.Timestamp) { + x.xxx_hidden_InputFetchCompletedTimestamp = v +} + +func (x *ExecutedActionMetadata) SetExecutionStartTimestamp(v *timestamppb.Timestamp) { + x.xxx_hidden_ExecutionStartTimestamp = v +} + +func (x *ExecutedActionMetadata) SetExecutionCompletedTimestamp(v *timestamppb.Timestamp) { + x.xxx_hidden_ExecutionCompletedTimestamp = v +} + +func (x *ExecutedActionMetadata) SetVirtualExecutionDuration(v *durationpb.Duration) { + x.xxx_hidden_VirtualExecutionDuration = v +} + +func (x *ExecutedActionMetadata) SetOutputUploadStartTimestamp(v *timestamppb.Timestamp) { + x.xxx_hidden_OutputUploadStartTimestamp = v +} + +func (x *ExecutedActionMetadata) SetOutputUploadCompletedTimestamp(v *timestamppb.Timestamp) { + x.xxx_hidden_OutputUploadCompletedTimestamp = v +} + +func (x *ExecutedActionMetadata) SetAuxiliaryMetadata(v []*anypb.Any) { + x.xxx_hidden_AuxiliaryMetadata = &v +} + +func (x *ExecutedActionMetadata) HasQueuedTimestamp() bool { + if x == nil { + return false + } + return x.xxx_hidden_QueuedTimestamp != nil +} + +func (x *ExecutedActionMetadata) HasWorkerStartTimestamp() bool { + if x == nil { + return false + } + return x.xxx_hidden_WorkerStartTimestamp != nil +} + +func (x *ExecutedActionMetadata) HasWorkerCompletedTimestamp() bool { + if x == nil { + return false + } + return x.xxx_hidden_WorkerCompletedTimestamp != nil +} + +func (x *ExecutedActionMetadata) HasInputFetchStartTimestamp() bool { + if x == nil { + return false + } + return x.xxx_hidden_InputFetchStartTimestamp != nil +} + +func (x *ExecutedActionMetadata) HasInputFetchCompletedTimestamp() bool { + if x == nil { + return false + } + return x.xxx_hidden_InputFetchCompletedTimestamp != nil +} + +func (x *ExecutedActionMetadata) HasExecutionStartTimestamp() bool { + if x == nil { + return false + } + return x.xxx_hidden_ExecutionStartTimestamp != nil +} + +func (x *ExecutedActionMetadata) HasExecutionCompletedTimestamp() bool { + if x == nil { + return false + } + return x.xxx_hidden_ExecutionCompletedTimestamp != nil +} + +func (x *ExecutedActionMetadata) HasVirtualExecutionDuration() bool { + if x == nil { + return false + } + return x.xxx_hidden_VirtualExecutionDuration != nil +} + +func (x *ExecutedActionMetadata) HasOutputUploadStartTimestamp() bool { + if x == nil { + return false + } + return x.xxx_hidden_OutputUploadStartTimestamp != nil +} + +func (x *ExecutedActionMetadata) HasOutputUploadCompletedTimestamp() bool { + if x == nil { + return false + } + return x.xxx_hidden_OutputUploadCompletedTimestamp != nil +} + +func (x *ExecutedActionMetadata) ClearQueuedTimestamp() { + x.xxx_hidden_QueuedTimestamp = nil +} + +func (x *ExecutedActionMetadata) ClearWorkerStartTimestamp() { + x.xxx_hidden_WorkerStartTimestamp = nil +} + +func (x *ExecutedActionMetadata) ClearWorkerCompletedTimestamp() { + x.xxx_hidden_WorkerCompletedTimestamp = nil +} + +func (x *ExecutedActionMetadata) ClearInputFetchStartTimestamp() { + x.xxx_hidden_InputFetchStartTimestamp = nil +} + +func (x *ExecutedActionMetadata) ClearInputFetchCompletedTimestamp() { + x.xxx_hidden_InputFetchCompletedTimestamp = nil +} + +func (x *ExecutedActionMetadata) ClearExecutionStartTimestamp() { + x.xxx_hidden_ExecutionStartTimestamp = nil +} + +func (x *ExecutedActionMetadata) ClearExecutionCompletedTimestamp() { + x.xxx_hidden_ExecutionCompletedTimestamp = nil +} + +func (x *ExecutedActionMetadata) ClearVirtualExecutionDuration() { + x.xxx_hidden_VirtualExecutionDuration = nil +} + +func (x *ExecutedActionMetadata) ClearOutputUploadStartTimestamp() { + x.xxx_hidden_OutputUploadStartTimestamp = nil +} + +func (x *ExecutedActionMetadata) ClearOutputUploadCompletedTimestamp() { + x.xxx_hidden_OutputUploadCompletedTimestamp = nil +} + +type ExecutedActionMetadata_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The name of the worker which ran the execution. + Worker string + // When was the action added to the queue. + QueuedTimestamp *timestamppb.Timestamp + // When the worker received the action. + WorkerStartTimestamp *timestamppb.Timestamp + // When the worker completed the action, including all stages. + WorkerCompletedTimestamp *timestamppb.Timestamp + // When the worker started fetching action inputs. + InputFetchStartTimestamp *timestamppb.Timestamp + // When the worker finished fetching action inputs. + InputFetchCompletedTimestamp *timestamppb.Timestamp + // When the worker started executing the action command. + ExecutionStartTimestamp *timestamppb.Timestamp + // When the worker completed executing the action command. + ExecutionCompletedTimestamp *timestamppb.Timestamp + // New in v2.3: the amount of time the worker spent executing the action + // command, potentially computed using a worker-specific virtual clock. + // + // The virtual execution duration is only intended to cover the "execution" of + // the specified action and not time in queue nor any overheads before or + // after execution such as marshalling inputs/outputs. The server SHOULD avoid + // including time spent the client doesn't have control over, and MAY extend + // or reduce the execution duration to account for delays or speedups that + // occur during execution itself (e.g., lazily loading data from the Content + // Addressable Storage, live migration of virtual machines, emulation + // overhead). + // + // The method of timekeeping used to compute the virtual execution duration + // MUST be consistent with what is used to enforce the + // [Action][build.bazel.remote.execution.v2.Action]'s `timeout`. There is no + // relationship between the virtual execution duration and the values of + // `execution_start_timestamp` and `execution_completed_timestamp`. + VirtualExecutionDuration *durationpb.Duration + // When the worker started uploading action outputs. + OutputUploadStartTimestamp *timestamppb.Timestamp + // When the worker finished uploading action outputs. + OutputUploadCompletedTimestamp *timestamppb.Timestamp + // Details that are specific to the kind of worker used. For example, + // on POSIX-like systems this could contain a message with + // getrusage(2) statistics. + AuxiliaryMetadata []*anypb.Any +} + +func (b0 ExecutedActionMetadata_builder) Build() *ExecutedActionMetadata { + m0 := &ExecutedActionMetadata{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Worker = b.Worker + x.xxx_hidden_QueuedTimestamp = b.QueuedTimestamp + x.xxx_hidden_WorkerStartTimestamp = b.WorkerStartTimestamp + x.xxx_hidden_WorkerCompletedTimestamp = b.WorkerCompletedTimestamp + x.xxx_hidden_InputFetchStartTimestamp = b.InputFetchStartTimestamp + x.xxx_hidden_InputFetchCompletedTimestamp = b.InputFetchCompletedTimestamp + x.xxx_hidden_ExecutionStartTimestamp = b.ExecutionStartTimestamp + x.xxx_hidden_ExecutionCompletedTimestamp = b.ExecutionCompletedTimestamp + x.xxx_hidden_VirtualExecutionDuration = b.VirtualExecutionDuration + x.xxx_hidden_OutputUploadStartTimestamp = b.OutputUploadStartTimestamp + x.xxx_hidden_OutputUploadCompletedTimestamp = b.OutputUploadCompletedTimestamp + x.xxx_hidden_AuxiliaryMetadata = &b.AuxiliaryMetadata + return m0 +} + +// An ActionResult represents the result of an +// [Action][build.bazel.remote.execution.v2.Action] being run. +// +// It is advised that at least one field (for example +// `ActionResult.execution_metadata.Worker`) have a non-default value, to +// ensure that the serialized value is non-empty, which can then be used +// as a basic data sanity check. +type ActionResult struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_OutputFiles *[]*OutputFile `protobuf:"bytes,2,rep,name=output_files,json=outputFiles,proto3"` + xxx_hidden_OutputFileSymlinks *[]*OutputSymlink `protobuf:"bytes,10,rep,name=output_file_symlinks,json=outputFileSymlinks,proto3"` + xxx_hidden_OutputSymlinks *[]*OutputSymlink `protobuf:"bytes,12,rep,name=output_symlinks,json=outputSymlinks,proto3"` + xxx_hidden_OutputDirectories *[]*OutputDirectory `protobuf:"bytes,3,rep,name=output_directories,json=outputDirectories,proto3"` + xxx_hidden_OutputDirectorySymlinks *[]*OutputSymlink `protobuf:"bytes,11,rep,name=output_directory_symlinks,json=outputDirectorySymlinks,proto3"` + xxx_hidden_ExitCode int32 `protobuf:"varint,4,opt,name=exit_code,json=exitCode,proto3"` + xxx_hidden_StdoutRaw []byte `protobuf:"bytes,5,opt,name=stdout_raw,json=stdoutRaw,proto3"` + xxx_hidden_StdoutDigest *Digest `protobuf:"bytes,6,opt,name=stdout_digest,json=stdoutDigest,proto3"` + xxx_hidden_StderrRaw []byte `protobuf:"bytes,7,opt,name=stderr_raw,json=stderrRaw,proto3"` + xxx_hidden_StderrDigest *Digest `protobuf:"bytes,8,opt,name=stderr_digest,json=stderrDigest,proto3"` + xxx_hidden_ExecutionMetadata *ExecutedActionMetadata `protobuf:"bytes,9,opt,name=execution_metadata,json=executionMetadata,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ActionResult) Reset() { + *x = ActionResult{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ActionResult) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ActionResult) ProtoMessage() {} + +func (x *ActionResult) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[11] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *ActionResult) GetOutputFiles() []*OutputFile { + if x != nil { + if x.xxx_hidden_OutputFiles != nil { + return *x.xxx_hidden_OutputFiles + } + } + return nil +} + +// Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. +func (x *ActionResult) GetOutputFileSymlinks() []*OutputSymlink { + if x != nil { + if x.xxx_hidden_OutputFileSymlinks != nil { + return *x.xxx_hidden_OutputFileSymlinks + } + } + return nil +} + +func (x *ActionResult) GetOutputSymlinks() []*OutputSymlink { + if x != nil { + if x.xxx_hidden_OutputSymlinks != nil { + return *x.xxx_hidden_OutputSymlinks + } + } + return nil +} + +func (x *ActionResult) GetOutputDirectories() []*OutputDirectory { + if x != nil { + if x.xxx_hidden_OutputDirectories != nil { + return *x.xxx_hidden_OutputDirectories + } + } + return nil +} + +// Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. +func (x *ActionResult) GetOutputDirectorySymlinks() []*OutputSymlink { + if x != nil { + if x.xxx_hidden_OutputDirectorySymlinks != nil { + return *x.xxx_hidden_OutputDirectorySymlinks + } + } + return nil +} + +func (x *ActionResult) GetExitCode() int32 { + if x != nil { + return x.xxx_hidden_ExitCode + } + return 0 +} + +func (x *ActionResult) GetStdoutRaw() []byte { + if x != nil { + return x.xxx_hidden_StdoutRaw + } + return nil +} + +func (x *ActionResult) GetStdoutDigest() *Digest { + if x != nil { + return x.xxx_hidden_StdoutDigest + } + return nil +} + +func (x *ActionResult) GetStderrRaw() []byte { + if x != nil { + return x.xxx_hidden_StderrRaw + } + return nil +} + +func (x *ActionResult) GetStderrDigest() *Digest { + if x != nil { + return x.xxx_hidden_StderrDigest + } + return nil +} + +func (x *ActionResult) GetExecutionMetadata() *ExecutedActionMetadata { + if x != nil { + return x.xxx_hidden_ExecutionMetadata + } + return nil +} + +func (x *ActionResult) SetOutputFiles(v []*OutputFile) { + x.xxx_hidden_OutputFiles = &v +} + +// Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. +func (x *ActionResult) SetOutputFileSymlinks(v []*OutputSymlink) { + x.xxx_hidden_OutputFileSymlinks = &v +} + +func (x *ActionResult) SetOutputSymlinks(v []*OutputSymlink) { + x.xxx_hidden_OutputSymlinks = &v +} + +func (x *ActionResult) SetOutputDirectories(v []*OutputDirectory) { + x.xxx_hidden_OutputDirectories = &v +} + +// Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. +func (x *ActionResult) SetOutputDirectorySymlinks(v []*OutputSymlink) { + x.xxx_hidden_OutputDirectorySymlinks = &v +} + +func (x *ActionResult) SetExitCode(v int32) { + x.xxx_hidden_ExitCode = v +} + +func (x *ActionResult) SetStdoutRaw(v []byte) { + if v == nil { + v = []byte{} + } + x.xxx_hidden_StdoutRaw = v +} + +func (x *ActionResult) SetStdoutDigest(v *Digest) { + x.xxx_hidden_StdoutDigest = v +} + +func (x *ActionResult) SetStderrRaw(v []byte) { + if v == nil { + v = []byte{} + } + x.xxx_hidden_StderrRaw = v +} + +func (x *ActionResult) SetStderrDigest(v *Digest) { + x.xxx_hidden_StderrDigest = v +} + +func (x *ActionResult) SetExecutionMetadata(v *ExecutedActionMetadata) { + x.xxx_hidden_ExecutionMetadata = v +} + +func (x *ActionResult) HasStdoutDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_StdoutDigest != nil +} + +func (x *ActionResult) HasStderrDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_StderrDigest != nil +} + +func (x *ActionResult) HasExecutionMetadata() bool { + if x == nil { + return false + } + return x.xxx_hidden_ExecutionMetadata != nil +} + +func (x *ActionResult) ClearStdoutDigest() { + x.xxx_hidden_StdoutDigest = nil +} + +func (x *ActionResult) ClearStderrDigest() { + x.xxx_hidden_StderrDigest = nil +} + +func (x *ActionResult) ClearExecutionMetadata() { + x.xxx_hidden_ExecutionMetadata = nil +} + +type ActionResult_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The output files of the action. For each output file requested in the + // `output_files` or `output_paths` field of the Action, if the corresponding + // file existed after the action completed, a single entry will be present + // either in this field, or the `output_file_symlinks` field if the file was + // a symbolic link to another file (`output_symlinks` field after v2.1). + // + // If an output listed in `output_files` was found, but was a directory rather + // than a regular file, the server will return a FAILED_PRECONDITION. + // If the action does not produce the requested output, then that output + // will be omitted from the list. The server is free to arrange the output + // list as desired; clients MUST NOT assume that the output list is sorted. + OutputFiles []*OutputFile + // The output files of the action that are symbolic links to other files. Those + // may be links to other output files, or input files, or even absolute paths + // outside of the working directory, if the server supports + // [SymlinkAbsolutePathStrategy.ALLOWED][build.bazel.remote.execution.v2.CacheCapabilities.SymlinkAbsolutePathStrategy]. + // For each output file requested in the `output_files` or `output_paths` + // field of the Action, if the corresponding file existed after + // the action completed, a single entry will be present either in this field, + // or in the `output_files` field, if the file was not a symbolic link. + // + // If an output symbolic link of the same name as listed in `output_files` of + // the Command was found, but its target type was not a regular file, the + // server will return a FAILED_PRECONDITION. + // If the action does not produce the requested output, then that output + // will be omitted from the list. The server is free to arrange the output + // list as desired; clients MUST NOT assume that the output list is sorted. + // + // DEPRECATED as of v2.1. Servers that wish to be compatible with v2.0 API + // should still populate this field in addition to `output_symlinks`. + // + // Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. + OutputFileSymlinks []*OutputSymlink + // New in v2.1: this field will only be populated if the command + // `output_paths` field was used, and not the pre v2.1 `output_files` or + // `output_directories` fields. + // The output paths of the action that are symbolic links to other paths. Those + // may be links to other outputs, or inputs, or even absolute paths + // outside of the working directory, if the server supports + // [SymlinkAbsolutePathStrategy.ALLOWED][build.bazel.remote.execution.v2.CacheCapabilities.SymlinkAbsolutePathStrategy]. + // A single entry for each output requested in `output_paths` + // field of the Action, if the corresponding path existed after + // the action completed and was a symbolic link. + // + // If the action does not produce a requested output, then that output + // will be omitted from the list. The server is free to arrange the output + // list as desired; clients MUST NOT assume that the output list is sorted. + OutputSymlinks []*OutputSymlink + // The output directories of the action. For each output directory requested + // in the `output_directories` or `output_paths` field of the Action, if the + // corresponding directory existed after the action completed, a single entry + // will be present in the output list, which will contain the digest of a + // [Tree][build.bazel.remote.execution.v2.Tree] message containing the + // directory tree, and the path equal exactly to the corresponding Action + // output_directories member. + // + // As an example, suppose the Action had an output directory `a/b/dir` and the + // execution produced the following contents in `a/b/dir`: a file named `bar` + // and a directory named `foo` with an executable file named `baz`. Then, + // output_directory will contain (hashes shortened for readability): + // + // ```json + // // OutputDirectory proto: + // + // { + // path: "a/b/dir" + // tree_digest: { + // hash: "4a73bc9d03...", + // size: 55 + // } + // } + // + // // Tree proto with hash "4a73bc9d03..." and size 55: + // + // { + // root: { + // files: [ + // { + // name: "bar", + // digest: { + // hash: "4a73bc9d03...", + // size: 65534 + // } + // } + // ], + // directories: [ + // { + // name: "foo", + // digest: { + // hash: "4cf2eda940...", + // size: 43 + // } + // } + // ] + // } + // children : { + // // (Directory proto with hash "4cf2eda940..." and size 43) + // files: [ + // { + // name: "baz", + // digest: { + // hash: "b2c941073e...", + // size: 1294, + // }, + // is_executable: true + // } + // ] + // } + // } + // + // ``` + // If an output of the same name as listed in `output_files` of + // the Command was found in `output_directories`, but was not a directory, the + // server will return a FAILED_PRECONDITION. + OutputDirectories []*OutputDirectory + // The output directories of the action that are symbolic links to other + // directories. Those may be links to other output directories, or input + // directories, or even absolute paths outside of the working directory, + // if the server supports + // [SymlinkAbsolutePathStrategy.ALLOWED][build.bazel.remote.execution.v2.CacheCapabilities.SymlinkAbsolutePathStrategy]. + // For each output directory requested in the `output_directories` field of + // the Action, if the directory existed after the action completed, a + // single entry will be present either in this field, or in the + // `output_directories` field, if the directory was not a symbolic link. + // + // If an output of the same name was found, but was a symbolic link to a file + // instead of a directory, the server will return a FAILED_PRECONDITION. + // If the action does not produce the requested output, then that output + // will be omitted from the list. The server is free to arrange the output + // list as desired; clients MUST NOT assume that the output list is sorted. + // + // DEPRECATED as of v2.1. Servers that wish to be compatible with v2.0 API + // should still populate this field in addition to `output_symlinks`. + // + // Deprecated: Marked as deprecated in build/bazel/remote/execution/v2/remote_execution.proto. + OutputDirectorySymlinks []*OutputSymlink + // The exit code of the command. + ExitCode int32 + // The standard output buffer of the action. The server SHOULD NOT inline + // stdout unless requested by the client in the + // [GetActionResultRequest][build.bazel.remote.execution.v2.GetActionResultRequest] + // message. The server MAY omit inlining, even if requested, and MUST do so if inlining + // would cause the response to exceed message size limits. + // Clients SHOULD NOT populate this field when uploading to the cache. + StdoutRaw []byte + // The digest for a blob containing the standard output of the action, which + // can be retrieved from the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + StdoutDigest *Digest + // The standard error buffer of the action. The server SHOULD NOT inline + // stderr unless requested by the client in the + // [GetActionResultRequest][build.bazel.remote.execution.v2.GetActionResultRequest] + // message. The server MAY omit inlining, even if requested, and MUST do so if inlining + // would cause the response to exceed message size limits. + // Clients SHOULD NOT populate this field when uploading to the cache. + StderrRaw []byte + // The digest for a blob containing the standard error of the action, which + // can be retrieved from the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + StderrDigest *Digest + // The details of the execution that originally produced this result. + ExecutionMetadata *ExecutedActionMetadata +} + +func (b0 ActionResult_builder) Build() *ActionResult { + m0 := &ActionResult{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_OutputFiles = &b.OutputFiles + x.xxx_hidden_OutputFileSymlinks = &b.OutputFileSymlinks + x.xxx_hidden_OutputSymlinks = &b.OutputSymlinks + x.xxx_hidden_OutputDirectories = &b.OutputDirectories + x.xxx_hidden_OutputDirectorySymlinks = &b.OutputDirectorySymlinks + x.xxx_hidden_ExitCode = b.ExitCode + x.xxx_hidden_StdoutRaw = b.StdoutRaw + x.xxx_hidden_StdoutDigest = b.StdoutDigest + x.xxx_hidden_StderrRaw = b.StderrRaw + x.xxx_hidden_StderrDigest = b.StderrDigest + x.xxx_hidden_ExecutionMetadata = b.ExecutionMetadata + return m0 +} + +// An `OutputFile` is similar to a +// [FileNode][build.bazel.remote.execution.v2.FileNode], but it is used as an +// output in an `ActionResult`. It allows a full file path rather than +// only a name. +type OutputFile struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Path string `protobuf:"bytes,1,opt,name=path,proto3"` + xxx_hidden_Digest *Digest `protobuf:"bytes,2,opt,name=digest,proto3"` + xxx_hidden_IsExecutable bool `protobuf:"varint,4,opt,name=is_executable,json=isExecutable,proto3"` + xxx_hidden_Contents []byte `protobuf:"bytes,5,opt,name=contents,proto3"` + xxx_hidden_NodeProperties *NodeProperties `protobuf:"bytes,7,opt,name=node_properties,json=nodeProperties,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *OutputFile) Reset() { + *x = OutputFile{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *OutputFile) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OutputFile) ProtoMessage() {} + +func (x *OutputFile) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[12] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *OutputFile) GetPath() string { + if x != nil { + return x.xxx_hidden_Path + } + return "" +} + +func (x *OutputFile) GetDigest() *Digest { + if x != nil { + return x.xxx_hidden_Digest + } + return nil +} + +func (x *OutputFile) GetIsExecutable() bool { + if x != nil { + return x.xxx_hidden_IsExecutable + } + return false +} + +func (x *OutputFile) GetContents() []byte { + if x != nil { + return x.xxx_hidden_Contents + } + return nil +} + +func (x *OutputFile) GetNodeProperties() *NodeProperties { + if x != nil { + return x.xxx_hidden_NodeProperties + } + return nil +} + +func (x *OutputFile) SetPath(v string) { + x.xxx_hidden_Path = v +} + +func (x *OutputFile) SetDigest(v *Digest) { + x.xxx_hidden_Digest = v +} + +func (x *OutputFile) SetIsExecutable(v bool) { + x.xxx_hidden_IsExecutable = v +} + +func (x *OutputFile) SetContents(v []byte) { + if v == nil { + v = []byte{} + } + x.xxx_hidden_Contents = v +} + +func (x *OutputFile) SetNodeProperties(v *NodeProperties) { + x.xxx_hidden_NodeProperties = v +} + +func (x *OutputFile) HasDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_Digest != nil +} + +func (x *OutputFile) HasNodeProperties() bool { + if x == nil { + return false + } + return x.xxx_hidden_NodeProperties != nil +} + +func (x *OutputFile) ClearDigest() { + x.xxx_hidden_Digest = nil +} + +func (x *OutputFile) ClearNodeProperties() { + x.xxx_hidden_NodeProperties = nil +} + +type OutputFile_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The full path of the file relative to the working directory, including the + // filename. The path separator is a forward slash `/`. Since this is a + // relative path, it MUST NOT begin with a leading forward slash. + Path string + // The digest of the file's content. + Digest *Digest + // True if file is executable, false otherwise. + IsExecutable bool + // The contents of the file if inlining was requested. The server SHOULD NOT inline + // file contents unless requested by the client in the + // [GetActionResultRequest][build.bazel.remote.execution.v2.GetActionResultRequest] + // message. The server MAY omit inlining, even if requested, and MUST do so if inlining + // would cause the response to exceed message size limits. + // Clients SHOULD NOT populate this field when uploading to the cache. + Contents []byte + NodeProperties *NodeProperties +} + +func (b0 OutputFile_builder) Build() *OutputFile { + m0 := &OutputFile{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Path = b.Path + x.xxx_hidden_Digest = b.Digest + x.xxx_hidden_IsExecutable = b.IsExecutable + x.xxx_hidden_Contents = b.Contents + x.xxx_hidden_NodeProperties = b.NodeProperties + return m0 +} + +// A `Tree` contains all the +// [Directory][build.bazel.remote.execution.v2.Directory] protos in a +// single directory Merkle tree, compressed into one message. +type Tree struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Root *Directory `protobuf:"bytes,1,opt,name=root,proto3"` + xxx_hidden_Children *[]*Directory `protobuf:"bytes,2,rep,name=children,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Tree) Reset() { + *x = Tree{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Tree) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Tree) ProtoMessage() {} + +func (x *Tree) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[13] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *Tree) GetRoot() *Directory { + if x != nil { + return x.xxx_hidden_Root + } + return nil +} + +func (x *Tree) GetChildren() []*Directory { + if x != nil { + if x.xxx_hidden_Children != nil { + return *x.xxx_hidden_Children + } + } + return nil +} + +func (x *Tree) SetRoot(v *Directory) { + x.xxx_hidden_Root = v +} + +func (x *Tree) SetChildren(v []*Directory) { + x.xxx_hidden_Children = &v +} + +func (x *Tree) HasRoot() bool { + if x == nil { + return false + } + return x.xxx_hidden_Root != nil +} + +func (x *Tree) ClearRoot() { + x.xxx_hidden_Root = nil +} + +type Tree_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The root directory in the tree. + Root *Directory + // All the child directories: the directories referred to by the root and, + // recursively, all its children. In order to reconstruct the directory tree, + // the client must take the digests of each of the child directories and then + // build up a tree starting from the `root`. + // Servers SHOULD ensure that these are ordered consistently such that two + // actions producing equivalent output directories on the same server + // implementation also produce Tree messages with matching digests. + Children []*Directory +} + +func (b0 Tree_builder) Build() *Tree { + m0 := &Tree{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Root = b.Root + x.xxx_hidden_Children = &b.Children + return m0 +} + +// An `OutputDirectory` is the output in an `ActionResult` corresponding to a +// directory's full contents rather than a single file. +type OutputDirectory struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Path string `protobuf:"bytes,1,opt,name=path,proto3"` + xxx_hidden_TreeDigest *Digest `protobuf:"bytes,3,opt,name=tree_digest,json=treeDigest,proto3"` + xxx_hidden_IsTopologicallySorted bool `protobuf:"varint,4,opt,name=is_topologically_sorted,json=isTopologicallySorted,proto3"` + xxx_hidden_RootDirectoryDigest *Digest `protobuf:"bytes,5,opt,name=root_directory_digest,json=rootDirectoryDigest,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *OutputDirectory) Reset() { + *x = OutputDirectory{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *OutputDirectory) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OutputDirectory) ProtoMessage() {} + +func (x *OutputDirectory) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[14] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *OutputDirectory) GetPath() string { + if x != nil { + return x.xxx_hidden_Path + } + return "" +} + +func (x *OutputDirectory) GetTreeDigest() *Digest { + if x != nil { + return x.xxx_hidden_TreeDigest + } + return nil +} + +func (x *OutputDirectory) GetIsTopologicallySorted() bool { + if x != nil { + return x.xxx_hidden_IsTopologicallySorted + } + return false +} + +func (x *OutputDirectory) GetRootDirectoryDigest() *Digest { + if x != nil { + return x.xxx_hidden_RootDirectoryDigest + } + return nil +} + +func (x *OutputDirectory) SetPath(v string) { + x.xxx_hidden_Path = v +} + +func (x *OutputDirectory) SetTreeDigest(v *Digest) { + x.xxx_hidden_TreeDigest = v +} + +func (x *OutputDirectory) SetIsTopologicallySorted(v bool) { + x.xxx_hidden_IsTopologicallySorted = v +} + +func (x *OutputDirectory) SetRootDirectoryDigest(v *Digest) { + x.xxx_hidden_RootDirectoryDigest = v +} + +func (x *OutputDirectory) HasTreeDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_TreeDigest != nil +} + +func (x *OutputDirectory) HasRootDirectoryDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_RootDirectoryDigest != nil +} + +func (x *OutputDirectory) ClearTreeDigest() { + x.xxx_hidden_TreeDigest = nil +} + +func (x *OutputDirectory) ClearRootDirectoryDigest() { + x.xxx_hidden_RootDirectoryDigest = nil +} + +type OutputDirectory_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The full path of the directory relative to the working directory. The path + // separator is a forward slash `/`. Since this is a relative path, it MUST + // NOT begin with a leading forward slash. The empty string value is allowed, + // and it denotes the entire working directory. + Path string + // The digest of the encoded + // [Tree][build.bazel.remote.execution.v2.Tree] proto containing the + // directory's contents. + TreeDigest *Digest + // If set, consumers MAY make the following assumptions about the + // directories contained in the Tree, so that it may be + // instantiated on a local file system by scanning through it + // sequentially: + // + // - All directories with the same binary representation are stored + // exactly once. + // - All directories, apart from the root directory, are referenced by + // at least one parent directory. + // - Directories are stored in topological order, with parents being + // stored before the child. The root directory is thus the first to + // be stored. + // + // Additionally, the Tree MUST be encoded as a stream of records, + // where each record has the following format: + // + // - A tag byte, having one of the following two values: + // - (1 << 3) | 2 == 0x0a: First record (the root directory). + // - (2 << 3) | 2 == 0x12: Any subsequent records (child directories). + // - The size of the directory, encoded as a base 128 varint. + // - The contents of the directory, encoded as a binary serialized + // Protobuf message. + // + // This encoding is a subset of the Protobuf wire format of the Tree + // message. As it is only permitted to store data associated with + // field numbers 1 and 2, the tag MUST be encoded as a single byte. + // More details on the Protobuf wire format can be found here: + // https://developers.google.com/protocol-buffers/docs/encoding + // + // It is recommended that implementations using this feature construct + // Tree objects manually using the specification given above, as + // opposed to using a Protobuf library to marshal a full Tree message. + // As individual Directory messages already need to be marshaled to + // compute their digests, constructing the Tree object manually avoids + // redundant marshaling. + IsTopologicallySorted bool + // The digest of the encoded + // [Directory][build.bazel.remote.execution.v2.Directory] proto + // containing the contents of the directory's root. + // + // If both `tree_digest` and `root_directory_digest` are set, this + // field MUST match the digest of the root directory contained in the + // Tree message. + RootDirectoryDigest *Digest +} + +func (b0 OutputDirectory_builder) Build() *OutputDirectory { + m0 := &OutputDirectory{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Path = b.Path + x.xxx_hidden_TreeDigest = b.TreeDigest + x.xxx_hidden_IsTopologicallySorted = b.IsTopologicallySorted + x.xxx_hidden_RootDirectoryDigest = b.RootDirectoryDigest + return m0 +} + +// An `OutputSymlink` is similar to a +// [Symlink][build.bazel.remote.execution.v2.SymlinkNode], but it is used as an +// output in an `ActionResult`. +// +// `OutputSymlink` is binary-compatible with `SymlinkNode`. +type OutputSymlink struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Path string `protobuf:"bytes,1,opt,name=path,proto3"` + xxx_hidden_Target string `protobuf:"bytes,2,opt,name=target,proto3"` + xxx_hidden_NodeProperties *NodeProperties `protobuf:"bytes,4,opt,name=node_properties,json=nodeProperties,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *OutputSymlink) Reset() { + *x = OutputSymlink{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *OutputSymlink) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OutputSymlink) ProtoMessage() {} + +func (x *OutputSymlink) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[15] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *OutputSymlink) GetPath() string { + if x != nil { + return x.xxx_hidden_Path + } + return "" +} + +func (x *OutputSymlink) GetTarget() string { + if x != nil { + return x.xxx_hidden_Target + } + return "" +} + +func (x *OutputSymlink) GetNodeProperties() *NodeProperties { + if x != nil { + return x.xxx_hidden_NodeProperties + } + return nil +} + +func (x *OutputSymlink) SetPath(v string) { + x.xxx_hidden_Path = v +} + +func (x *OutputSymlink) SetTarget(v string) { + x.xxx_hidden_Target = v +} + +func (x *OutputSymlink) SetNodeProperties(v *NodeProperties) { + x.xxx_hidden_NodeProperties = v +} + +func (x *OutputSymlink) HasNodeProperties() bool { + if x == nil { + return false + } + return x.xxx_hidden_NodeProperties != nil +} + +func (x *OutputSymlink) ClearNodeProperties() { + x.xxx_hidden_NodeProperties = nil +} + +type OutputSymlink_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The full path of the symlink relative to the working directory, including the + // filename. The path separator is a forward slash `/`. Since this is a + // relative path, it MUST NOT begin with a leading forward slash. + Path string + // The target path of the symlink. The path separator is a forward slash `/`. + // The target path can be relative to the parent directory of the symlink or + // it can be an absolute path starting with `/`. Support for absolute paths + // can be checked using the [Capabilities][build.bazel.remote.execution.v2.Capabilities] + // API. `..` components are allowed anywhere in the target path. + Target string + NodeProperties *NodeProperties +} + +func (b0 OutputSymlink_builder) Build() *OutputSymlink { + m0 := &OutputSymlink{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Path = b.Path + x.xxx_hidden_Target = b.Target + x.xxx_hidden_NodeProperties = b.NodeProperties + return m0 +} + +// An `ExecutionPolicy` can be used to control the scheduling of the action. +type ExecutionPolicy struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Priority int32 `protobuf:"varint,1,opt,name=priority,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ExecutionPolicy) Reset() { + *x = ExecutionPolicy{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ExecutionPolicy) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExecutionPolicy) ProtoMessage() {} + +func (x *ExecutionPolicy) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[16] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *ExecutionPolicy) GetPriority() int32 { + if x != nil { + return x.xxx_hidden_Priority + } + return 0 +} + +func (x *ExecutionPolicy) SetPriority(v int32) { + x.xxx_hidden_Priority = v +} + +type ExecutionPolicy_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The priority (relative importance) of this action. Generally, a lower value + // means that the action should be run sooner than actions having a greater + // priority value, but the interpretation of a given value is server- + // dependent. A priority of 0 means the *default* priority. Priorities may be + // positive or negative, and such actions should run later or sooner than + // actions having the default priority, respectively. The particular semantics + // of this field is up to the server. In particular, every server will have + // their own supported range of priorities, and will decide how these map into + // scheduling policy. + Priority int32 +} + +func (b0 ExecutionPolicy_builder) Build() *ExecutionPolicy { + m0 := &ExecutionPolicy{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Priority = b.Priority + return m0 +} + +// A `ResultsCachePolicy` is used for fine-grained control over how action +// outputs are stored in the CAS and Action Cache. +type ResultsCachePolicy struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Priority int32 `protobuf:"varint,1,opt,name=priority,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ResultsCachePolicy) Reset() { + *x = ResultsCachePolicy{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ResultsCachePolicy) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ResultsCachePolicy) ProtoMessage() {} + +func (x *ResultsCachePolicy) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[17] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *ResultsCachePolicy) GetPriority() int32 { + if x != nil { + return x.xxx_hidden_Priority + } + return 0 +} + +func (x *ResultsCachePolicy) SetPriority(v int32) { + x.xxx_hidden_Priority = v +} + +type ResultsCachePolicy_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The priority (relative importance) of this content in the overall cache. + // Generally, a lower value means a longer retention time or other advantage, + // but the interpretation of a given value is server-dependent. A priority of + // 0 means a *default* value, decided by the server. + // + // The particular semantics of this field is up to the server. In particular, + // every server will have their own supported range of priorities, and will + // decide how these map into retention/eviction policy. + Priority int32 +} + +func (b0 ResultsCachePolicy_builder) Build() *ResultsCachePolicy { + m0 := &ResultsCachePolicy{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Priority = b.Priority + return m0 +} + +// A request message for +// [Execution.Execute][build.bazel.remote.execution.v2.Execution.Execute]. +type ExecuteRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3"` + xxx_hidden_SkipCacheLookup bool `protobuf:"varint,3,opt,name=skip_cache_lookup,json=skipCacheLookup,proto3"` + xxx_hidden_ActionDigest *Digest `protobuf:"bytes,6,opt,name=action_digest,json=actionDigest,proto3"` + xxx_hidden_ExecutionPolicy *ExecutionPolicy `protobuf:"bytes,7,opt,name=execution_policy,json=executionPolicy,proto3"` + xxx_hidden_ResultsCachePolicy *ResultsCachePolicy `protobuf:"bytes,8,opt,name=results_cache_policy,json=resultsCachePolicy,proto3"` + xxx_hidden_DigestFunction DigestFunction_Value `protobuf:"varint,9,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + xxx_hidden_InlineStdout bool `protobuf:"varint,10,opt,name=inline_stdout,json=inlineStdout,proto3"` + xxx_hidden_InlineStderr bool `protobuf:"varint,11,opt,name=inline_stderr,json=inlineStderr,proto3"` + xxx_hidden_InlineOutputFiles []string `protobuf:"bytes,12,rep,name=inline_output_files,json=inlineOutputFiles,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ExecuteRequest) Reset() { + *x = ExecuteRequest{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ExecuteRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExecuteRequest) ProtoMessage() {} + +func (x *ExecuteRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[18] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *ExecuteRequest) GetInstanceName() string { + if x != nil { + return x.xxx_hidden_InstanceName + } + return "" +} + +func (x *ExecuteRequest) GetSkipCacheLookup() bool { + if x != nil { + return x.xxx_hidden_SkipCacheLookup + } + return false +} + +func (x *ExecuteRequest) GetActionDigest() *Digest { + if x != nil { + return x.xxx_hidden_ActionDigest + } + return nil +} + +func (x *ExecuteRequest) GetExecutionPolicy() *ExecutionPolicy { + if x != nil { + return x.xxx_hidden_ExecutionPolicy + } + return nil +} + +func (x *ExecuteRequest) GetResultsCachePolicy() *ResultsCachePolicy { + if x != nil { + return x.xxx_hidden_ResultsCachePolicy + } + return nil +} + +func (x *ExecuteRequest) GetDigestFunction() DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return DigestFunction_UNKNOWN +} + +func (x *ExecuteRequest) GetInlineStdout() bool { + if x != nil { + return x.xxx_hidden_InlineStdout + } + return false +} + +func (x *ExecuteRequest) GetInlineStderr() bool { + if x != nil { + return x.xxx_hidden_InlineStderr + } + return false +} + +func (x *ExecuteRequest) GetInlineOutputFiles() []string { + if x != nil { + return x.xxx_hidden_InlineOutputFiles + } + return nil +} + +func (x *ExecuteRequest) SetInstanceName(v string) { + x.xxx_hidden_InstanceName = v +} + +func (x *ExecuteRequest) SetSkipCacheLookup(v bool) { + x.xxx_hidden_SkipCacheLookup = v +} + +func (x *ExecuteRequest) SetActionDigest(v *Digest) { + x.xxx_hidden_ActionDigest = v +} + +func (x *ExecuteRequest) SetExecutionPolicy(v *ExecutionPolicy) { + x.xxx_hidden_ExecutionPolicy = v +} + +func (x *ExecuteRequest) SetResultsCachePolicy(v *ResultsCachePolicy) { + x.xxx_hidden_ResultsCachePolicy = v +} + +func (x *ExecuteRequest) SetDigestFunction(v DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +func (x *ExecuteRequest) SetInlineStdout(v bool) { + x.xxx_hidden_InlineStdout = v +} + +func (x *ExecuteRequest) SetInlineStderr(v bool) { + x.xxx_hidden_InlineStderr = v +} + +func (x *ExecuteRequest) SetInlineOutputFiles(v []string) { + x.xxx_hidden_InlineOutputFiles = v +} + +func (x *ExecuteRequest) HasActionDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_ActionDigest != nil +} + +func (x *ExecuteRequest) HasExecutionPolicy() bool { + if x == nil { + return false + } + return x.xxx_hidden_ExecutionPolicy != nil +} + +func (x *ExecuteRequest) HasResultsCachePolicy() bool { + if x == nil { + return false + } + return x.xxx_hidden_ResultsCachePolicy != nil +} + +func (x *ExecuteRequest) ClearActionDigest() { + x.xxx_hidden_ActionDigest = nil +} + +func (x *ExecuteRequest) ClearExecutionPolicy() { + x.xxx_hidden_ExecutionPolicy = nil +} + +func (x *ExecuteRequest) ClearResultsCachePolicy() { + x.xxx_hidden_ResultsCachePolicy = nil +} + +type ExecuteRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + InstanceName string + // If true, the action will be executed even if its result is already + // present in the [ActionCache][build.bazel.remote.execution.v2.ActionCache]. + // The execution is still allowed to be merged with other in-flight executions + // of the same action, however - semantically, the service MUST only guarantee + // that the results of an execution with this field set were not visible + // before the corresponding execution request was sent. + // Note that actions from execution requests setting this field set are still + // eligible to be entered into the action cache upon completion, and services + // SHOULD overwrite any existing entries that may exist. This allows + // skip_cache_lookup requests to be used as a mechanism for replacing action + // cache entries that reference outputs no longer available or that are + // poisoned in any way. + // If false, the result may be served from the action cache. + SkipCacheLookup bool + // The digest of the [Action][build.bazel.remote.execution.v2.Action] to + // execute. + ActionDigest *Digest + // An optional policy for execution of the action. + // The server will have a default policy if this is not provided. + ExecutionPolicy *ExecutionPolicy + // An optional policy for the results of this execution in the remote cache. + // The server will have a default policy if this is not provided. + // This may be applied to both the ActionResult and the associated blobs. + ResultsCachePolicy *ResultsCachePolicy + // The digest function that was used to compute the action digest. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the action digest hash and the digest functions announced + // in the server's capabilities. + DigestFunction DigestFunction_Value + // A hint to the server to request inlining stdout in the + // [ActionResult][build.bazel.remote.execution.v2.ActionResult] message. + InlineStdout bool + // A hint to the server to request inlining stderr in the + // [ActionResult][build.bazel.remote.execution.v2.ActionResult] message. + InlineStderr bool + // A hint to the server to inline the contents of the listed output files. + // Each path needs to exactly match one file path in either `output_paths` or + // `output_files` (DEPRECATED since v2.1) in the + // [Command][build.bazel.remote.execution.v2.Command] message. + InlineOutputFiles []string +} + +func (b0 ExecuteRequest_builder) Build() *ExecuteRequest { + m0 := &ExecuteRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_InstanceName = b.InstanceName + x.xxx_hidden_SkipCacheLookup = b.SkipCacheLookup + x.xxx_hidden_ActionDigest = b.ActionDigest + x.xxx_hidden_ExecutionPolicy = b.ExecutionPolicy + x.xxx_hidden_ResultsCachePolicy = b.ResultsCachePolicy + x.xxx_hidden_DigestFunction = b.DigestFunction + x.xxx_hidden_InlineStdout = b.InlineStdout + x.xxx_hidden_InlineStderr = b.InlineStderr + x.xxx_hidden_InlineOutputFiles = b.InlineOutputFiles + return m0 +} + +// A `LogFile` is a log stored in the CAS. +type LogFile struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Digest *Digest `protobuf:"bytes,1,opt,name=digest,proto3"` + xxx_hidden_HumanReadable bool `protobuf:"varint,2,opt,name=human_readable,json=humanReadable,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LogFile) Reset() { + *x = LogFile{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LogFile) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LogFile) ProtoMessage() {} + +func (x *LogFile) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[19] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *LogFile) GetDigest() *Digest { + if x != nil { + return x.xxx_hidden_Digest + } + return nil +} + +func (x *LogFile) GetHumanReadable() bool { + if x != nil { + return x.xxx_hidden_HumanReadable + } + return false +} + +func (x *LogFile) SetDigest(v *Digest) { + x.xxx_hidden_Digest = v +} + +func (x *LogFile) SetHumanReadable(v bool) { + x.xxx_hidden_HumanReadable = v +} + +func (x *LogFile) HasDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_Digest != nil +} + +func (x *LogFile) ClearDigest() { + x.xxx_hidden_Digest = nil +} + +type LogFile_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The digest of the log contents. + Digest *Digest + // This is a hint as to the purpose of the log, and is set to true if the log + // is human-readable text that can be usefully displayed to a user, and false + // otherwise. For instance, if a command-line client wishes to print the + // server logs to the terminal for a failed action, this allows it to avoid + // displaying a binary file. + HumanReadable bool +} + +func (b0 LogFile_builder) Build() *LogFile { + m0 := &LogFile{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Digest = b.Digest + x.xxx_hidden_HumanReadable = b.HumanReadable + return m0 +} + +// The response message for +// [Execution.Execute][build.bazel.remote.execution.v2.Execution.Execute], +// which will be contained in the [response +// field][google.longrunning.Operation.response] of the +// [Operation][google.longrunning.Operation]. +type ExecuteResponse struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Result *ActionResult `protobuf:"bytes,1,opt,name=result,proto3"` + xxx_hidden_CachedResult bool `protobuf:"varint,2,opt,name=cached_result,json=cachedResult,proto3"` + xxx_hidden_Status *status.Status `protobuf:"bytes,3,opt,name=status,proto3"` + xxx_hidden_ServerLogs map[string]*LogFile `protobuf:"bytes,4,rep,name=server_logs,json=serverLogs,proto3" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + xxx_hidden_Message string `protobuf:"bytes,5,opt,name=message,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ExecuteResponse) Reset() { + *x = ExecuteResponse{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ExecuteResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExecuteResponse) ProtoMessage() {} + +func (x *ExecuteResponse) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[20] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *ExecuteResponse) GetResult() *ActionResult { + if x != nil { + return x.xxx_hidden_Result + } + return nil +} + +func (x *ExecuteResponse) GetCachedResult() bool { + if x != nil { + return x.xxx_hidden_CachedResult + } + return false +} + +func (x *ExecuteResponse) GetStatus() *status.Status { + if x != nil { + return x.xxx_hidden_Status + } + return nil +} + +func (x *ExecuteResponse) GetServerLogs() map[string]*LogFile { + if x != nil { + return x.xxx_hidden_ServerLogs + } + return nil +} + +func (x *ExecuteResponse) GetMessage() string { + if x != nil { + return x.xxx_hidden_Message + } + return "" +} + +func (x *ExecuteResponse) SetResult(v *ActionResult) { + x.xxx_hidden_Result = v +} + +func (x *ExecuteResponse) SetCachedResult(v bool) { + x.xxx_hidden_CachedResult = v +} + +func (x *ExecuteResponse) SetStatus(v *status.Status) { + x.xxx_hidden_Status = v +} + +func (x *ExecuteResponse) SetServerLogs(v map[string]*LogFile) { + x.xxx_hidden_ServerLogs = v +} + +func (x *ExecuteResponse) SetMessage(v string) { + x.xxx_hidden_Message = v +} + +func (x *ExecuteResponse) HasResult() bool { + if x == nil { + return false + } + return x.xxx_hidden_Result != nil +} + +func (x *ExecuteResponse) HasStatus() bool { + if x == nil { + return false + } + return x.xxx_hidden_Status != nil +} + +func (x *ExecuteResponse) ClearResult() { + x.xxx_hidden_Result = nil +} + +func (x *ExecuteResponse) ClearStatus() { + x.xxx_hidden_Status = nil +} + +type ExecuteResponse_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The result of the action. + Result *ActionResult + // True if the result was served from cache, false if it was executed. + CachedResult bool + // If the status has a code other than `OK`, it indicates that the action did + // not finish execution. For example, if the operation times out during + // execution, the status will have a `DEADLINE_EXCEEDED` code. Servers MUST + // use this field for errors in execution, rather than the error field on the + // `Operation` object. + // + // If the status code is other than `OK`, then the result MUST NOT be cached. + // For an error status, the `result` field is optional; the server may + // populate the output-, stdout-, and stderr-related fields if it has any + // information available, such as the stdout and stderr of a timed-out action. + Status *status.Status + // An optional list of additional log outputs the server wishes to provide. A + // server can use this to return execution-specific logs however it wishes. + // This is intended primarily to make it easier for users to debug issues that + // may be outside of the actual job execution, such as by identifying the + // worker executing the action or by providing logs from the worker's setup + // phase. The keys SHOULD be human readable so that a client can display them + // to a user. + ServerLogs map[string]*LogFile + // Freeform informational message with details on the execution of the action + // that may be displayed to the user upon failure or when requested explicitly. + Message string +} + +func (b0 ExecuteResponse_builder) Build() *ExecuteResponse { + m0 := &ExecuteResponse{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Result = b.Result + x.xxx_hidden_CachedResult = b.CachedResult + x.xxx_hidden_Status = b.Status + x.xxx_hidden_ServerLogs = b.ServerLogs + x.xxx_hidden_Message = b.Message + return m0 +} + +// The current stage of action execution. +// +// Even though these stages are numbered according to the order in which +// they generally occur, there is no requirement that the remote +// execution system reports events along this order. For example, an +// operation MAY transition from the EXECUTING stage back to QUEUED +// in case the hardware on which the operation executes fails. +// +// If and only if the remote execution system reports that an operation +// has reached the COMPLETED stage, it MUST set the [done +// field][google.longrunning.Operation.done] of the +// [Operation][google.longrunning.Operation] and terminate the stream. +type ExecutionStage struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ExecutionStage) Reset() { + *x = ExecutionStage{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[21] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ExecutionStage) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExecutionStage) ProtoMessage() {} + +func (x *ExecutionStage) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[21] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +type ExecutionStage_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + +} + +func (b0 ExecutionStage_builder) Build() *ExecutionStage { + m0 := &ExecutionStage{} + b, x := &b0, m0 + _, _ = b, x + return m0 +} + +// Metadata about an ongoing +// [execution][build.bazel.remote.execution.v2.Execution.Execute], which +// will be contained in the [metadata +// field][google.longrunning.Operation.metadata] of the +// [Operation][google.longrunning.Operation]. +type ExecuteOperationMetadata struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Stage ExecutionStage_Value `protobuf:"varint,1,opt,name=stage,proto3,enum=build.bazel.remote.execution.v2.ExecutionStage_Value"` + xxx_hidden_ActionDigest *Digest `protobuf:"bytes,2,opt,name=action_digest,json=actionDigest,proto3"` + xxx_hidden_StdoutStreamName string `protobuf:"bytes,3,opt,name=stdout_stream_name,json=stdoutStreamName,proto3"` + xxx_hidden_StderrStreamName string `protobuf:"bytes,4,opt,name=stderr_stream_name,json=stderrStreamName,proto3"` + xxx_hidden_PartialExecutionMetadata *ExecutedActionMetadata `protobuf:"bytes,5,opt,name=partial_execution_metadata,json=partialExecutionMetadata,proto3"` + xxx_hidden_DigestFunction DigestFunction_Value `protobuf:"varint,6,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ExecuteOperationMetadata) Reset() { + *x = ExecuteOperationMetadata{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[22] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ExecuteOperationMetadata) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExecuteOperationMetadata) ProtoMessage() {} + +func (x *ExecuteOperationMetadata) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[22] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *ExecuteOperationMetadata) GetStage() ExecutionStage_Value { + if x != nil { + return x.xxx_hidden_Stage + } + return ExecutionStage_UNKNOWN +} + +func (x *ExecuteOperationMetadata) GetActionDigest() *Digest { + if x != nil { + return x.xxx_hidden_ActionDigest + } + return nil +} + +func (x *ExecuteOperationMetadata) GetStdoutStreamName() string { + if x != nil { + return x.xxx_hidden_StdoutStreamName + } + return "" +} + +func (x *ExecuteOperationMetadata) GetStderrStreamName() string { + if x != nil { + return x.xxx_hidden_StderrStreamName + } + return "" +} + +func (x *ExecuteOperationMetadata) GetPartialExecutionMetadata() *ExecutedActionMetadata { + if x != nil { + return x.xxx_hidden_PartialExecutionMetadata + } + return nil +} + +func (x *ExecuteOperationMetadata) GetDigestFunction() DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return DigestFunction_UNKNOWN +} + +func (x *ExecuteOperationMetadata) SetStage(v ExecutionStage_Value) { + x.xxx_hidden_Stage = v +} + +func (x *ExecuteOperationMetadata) SetActionDigest(v *Digest) { + x.xxx_hidden_ActionDigest = v +} + +func (x *ExecuteOperationMetadata) SetStdoutStreamName(v string) { + x.xxx_hidden_StdoutStreamName = v +} + +func (x *ExecuteOperationMetadata) SetStderrStreamName(v string) { + x.xxx_hidden_StderrStreamName = v +} + +func (x *ExecuteOperationMetadata) SetPartialExecutionMetadata(v *ExecutedActionMetadata) { + x.xxx_hidden_PartialExecutionMetadata = v +} + +func (x *ExecuteOperationMetadata) SetDigestFunction(v DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +func (x *ExecuteOperationMetadata) HasActionDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_ActionDigest != nil +} + +func (x *ExecuteOperationMetadata) HasPartialExecutionMetadata() bool { + if x == nil { + return false + } + return x.xxx_hidden_PartialExecutionMetadata != nil +} + +func (x *ExecuteOperationMetadata) ClearActionDigest() { + x.xxx_hidden_ActionDigest = nil +} + +func (x *ExecuteOperationMetadata) ClearPartialExecutionMetadata() { + x.xxx_hidden_PartialExecutionMetadata = nil +} + +type ExecuteOperationMetadata_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The current stage of execution. + Stage ExecutionStage_Value + // The digest of the [Action][build.bazel.remote.execution.v2.Action] + // being executed. + ActionDigest *Digest + // If set, the client can use this resource name with + // [ByteStream.Read][google.bytestream.ByteStream.Read] to stream the + // standard output from the endpoint hosting streamed responses. + StdoutStreamName string + // If set, the client can use this resource name with + // [ByteStream.Read][google.bytestream.ByteStream.Read] to stream the + // standard error from the endpoint hosting streamed responses. + StderrStreamName string + // The client can read this field to view details about the ongoing + // execution. + PartialExecutionMetadata *ExecutedActionMetadata + // The digest function that was used to compute the action digest. + // + // If the digest function used is one of BLAKE3, MD5, MURMUR3, SHA1, + // SHA256, SHA256TREE, SHA384, SHA512, or VSO, the server MAY leave + // this field unset. In that case the client SHOULD infer the digest + // function using the length of the action digest hash and the digest + // functions announced in the server's capabilities. + DigestFunction DigestFunction_Value +} + +func (b0 ExecuteOperationMetadata_builder) Build() *ExecuteOperationMetadata { + m0 := &ExecuteOperationMetadata{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Stage = b.Stage + x.xxx_hidden_ActionDigest = b.ActionDigest + x.xxx_hidden_StdoutStreamName = b.StdoutStreamName + x.xxx_hidden_StderrStreamName = b.StderrStreamName + x.xxx_hidden_PartialExecutionMetadata = b.PartialExecutionMetadata + x.xxx_hidden_DigestFunction = b.DigestFunction + return m0 +} + +// A request message for +// [WaitExecution][build.bazel.remote.execution.v2.Execution.WaitExecution]. +type WaitExecutionRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Name string `protobuf:"bytes,1,opt,name=name,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WaitExecutionRequest) Reset() { + *x = WaitExecutionRequest{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[23] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WaitExecutionRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WaitExecutionRequest) ProtoMessage() {} + +func (x *WaitExecutionRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[23] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *WaitExecutionRequest) GetName() string { + if x != nil { + return x.xxx_hidden_Name + } + return "" +} + +func (x *WaitExecutionRequest) SetName(v string) { + x.xxx_hidden_Name = v +} + +type WaitExecutionRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The name of the [Operation][google.longrunning.Operation] + // returned by [Execute][build.bazel.remote.execution.v2.Execution.Execute]. + Name string +} + +func (b0 WaitExecutionRequest_builder) Build() *WaitExecutionRequest { + m0 := &WaitExecutionRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Name = b.Name + return m0 +} + +// A request message for +// [ActionCache.GetActionResult][build.bazel.remote.execution.v2.ActionCache.GetActionResult]. +type GetActionResultRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3"` + xxx_hidden_ActionDigest *Digest `protobuf:"bytes,2,opt,name=action_digest,json=actionDigest,proto3"` + xxx_hidden_InlineStdout bool `protobuf:"varint,3,opt,name=inline_stdout,json=inlineStdout,proto3"` + xxx_hidden_InlineStderr bool `protobuf:"varint,4,opt,name=inline_stderr,json=inlineStderr,proto3"` + xxx_hidden_InlineOutputFiles []string `protobuf:"bytes,5,rep,name=inline_output_files,json=inlineOutputFiles,proto3"` + xxx_hidden_DigestFunction DigestFunction_Value `protobuf:"varint,6,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetActionResultRequest) Reset() { + *x = GetActionResultRequest{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[24] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetActionResultRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetActionResultRequest) ProtoMessage() {} + +func (x *GetActionResultRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[24] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *GetActionResultRequest) GetInstanceName() string { + if x != nil { + return x.xxx_hidden_InstanceName + } + return "" +} + +func (x *GetActionResultRequest) GetActionDigest() *Digest { + if x != nil { + return x.xxx_hidden_ActionDigest + } + return nil +} + +func (x *GetActionResultRequest) GetInlineStdout() bool { + if x != nil { + return x.xxx_hidden_InlineStdout + } + return false +} + +func (x *GetActionResultRequest) GetInlineStderr() bool { + if x != nil { + return x.xxx_hidden_InlineStderr + } + return false +} + +func (x *GetActionResultRequest) GetInlineOutputFiles() []string { + if x != nil { + return x.xxx_hidden_InlineOutputFiles + } + return nil +} + +func (x *GetActionResultRequest) GetDigestFunction() DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return DigestFunction_UNKNOWN +} + +func (x *GetActionResultRequest) SetInstanceName(v string) { + x.xxx_hidden_InstanceName = v +} + +func (x *GetActionResultRequest) SetActionDigest(v *Digest) { + x.xxx_hidden_ActionDigest = v +} + +func (x *GetActionResultRequest) SetInlineStdout(v bool) { + x.xxx_hidden_InlineStdout = v +} + +func (x *GetActionResultRequest) SetInlineStderr(v bool) { + x.xxx_hidden_InlineStderr = v +} + +func (x *GetActionResultRequest) SetInlineOutputFiles(v []string) { + x.xxx_hidden_InlineOutputFiles = v +} + +func (x *GetActionResultRequest) SetDigestFunction(v DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +func (x *GetActionResultRequest) HasActionDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_ActionDigest != nil +} + +func (x *GetActionResultRequest) ClearActionDigest() { + x.xxx_hidden_ActionDigest = nil +} + +type GetActionResultRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + InstanceName string + // The digest of the [Action][build.bazel.remote.execution.v2.Action] + // whose result is requested. + ActionDigest *Digest + // A hint to the server to request inlining stdout in the + // [ActionResult][build.bazel.remote.execution.v2.ActionResult] message. + InlineStdout bool + // A hint to the server to request inlining stderr in the + // [ActionResult][build.bazel.remote.execution.v2.ActionResult] message. + InlineStderr bool + // A hint to the server to inline the contents of the listed output files. + // Each path needs to exactly match one file path in either `output_paths` or + // `output_files` (DEPRECATED since v2.1) in the + // [Command][build.bazel.remote.execution.v2.Command] message. + InlineOutputFiles []string + // The digest function that was used to compute the action digest. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the action digest hash and the digest functions announced + // in the server's capabilities. + DigestFunction DigestFunction_Value +} + +func (b0 GetActionResultRequest_builder) Build() *GetActionResultRequest { + m0 := &GetActionResultRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_InstanceName = b.InstanceName + x.xxx_hidden_ActionDigest = b.ActionDigest + x.xxx_hidden_InlineStdout = b.InlineStdout + x.xxx_hidden_InlineStderr = b.InlineStderr + x.xxx_hidden_InlineOutputFiles = b.InlineOutputFiles + x.xxx_hidden_DigestFunction = b.DigestFunction + return m0 +} + +// A request message for +// [ActionCache.UpdateActionResult][build.bazel.remote.execution.v2.ActionCache.UpdateActionResult]. +type UpdateActionResultRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3"` + xxx_hidden_ActionDigest *Digest `protobuf:"bytes,2,opt,name=action_digest,json=actionDigest,proto3"` + xxx_hidden_ActionResult *ActionResult `protobuf:"bytes,3,opt,name=action_result,json=actionResult,proto3"` + xxx_hidden_ResultsCachePolicy *ResultsCachePolicy `protobuf:"bytes,4,opt,name=results_cache_policy,json=resultsCachePolicy,proto3"` + xxx_hidden_DigestFunction DigestFunction_Value `protobuf:"varint,5,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateActionResultRequest) Reset() { + *x = UpdateActionResultRequest{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[25] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateActionResultRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateActionResultRequest) ProtoMessage() {} + +func (x *UpdateActionResultRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[25] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *UpdateActionResultRequest) GetInstanceName() string { + if x != nil { + return x.xxx_hidden_InstanceName + } + return "" +} + +func (x *UpdateActionResultRequest) GetActionDigest() *Digest { + if x != nil { + return x.xxx_hidden_ActionDigest + } + return nil +} + +func (x *UpdateActionResultRequest) GetActionResult() *ActionResult { + if x != nil { + return x.xxx_hidden_ActionResult + } + return nil +} + +func (x *UpdateActionResultRequest) GetResultsCachePolicy() *ResultsCachePolicy { + if x != nil { + return x.xxx_hidden_ResultsCachePolicy + } + return nil +} + +func (x *UpdateActionResultRequest) GetDigestFunction() DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return DigestFunction_UNKNOWN +} + +func (x *UpdateActionResultRequest) SetInstanceName(v string) { + x.xxx_hidden_InstanceName = v +} + +func (x *UpdateActionResultRequest) SetActionDigest(v *Digest) { + x.xxx_hidden_ActionDigest = v +} + +func (x *UpdateActionResultRequest) SetActionResult(v *ActionResult) { + x.xxx_hidden_ActionResult = v +} + +func (x *UpdateActionResultRequest) SetResultsCachePolicy(v *ResultsCachePolicy) { + x.xxx_hidden_ResultsCachePolicy = v +} + +func (x *UpdateActionResultRequest) SetDigestFunction(v DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +func (x *UpdateActionResultRequest) HasActionDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_ActionDigest != nil +} + +func (x *UpdateActionResultRequest) HasActionResult() bool { + if x == nil { + return false + } + return x.xxx_hidden_ActionResult != nil +} + +func (x *UpdateActionResultRequest) HasResultsCachePolicy() bool { + if x == nil { + return false + } + return x.xxx_hidden_ResultsCachePolicy != nil +} + +func (x *UpdateActionResultRequest) ClearActionDigest() { + x.xxx_hidden_ActionDigest = nil +} + +func (x *UpdateActionResultRequest) ClearActionResult() { + x.xxx_hidden_ActionResult = nil +} + +func (x *UpdateActionResultRequest) ClearResultsCachePolicy() { + x.xxx_hidden_ResultsCachePolicy = nil +} + +type UpdateActionResultRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + InstanceName string + // The digest of the [Action][build.bazel.remote.execution.v2.Action] + // whose result is being uploaded. + ActionDigest *Digest + // The [ActionResult][build.bazel.remote.execution.v2.ActionResult] + // to store in the cache. + ActionResult *ActionResult + // An optional policy for the results of this execution in the remote cache. + // The server will have a default policy if this is not provided. + // This may be applied to both the ActionResult and the associated blobs. + ResultsCachePolicy *ResultsCachePolicy + // The digest function that was used to compute the action digest. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the action digest hash and the digest functions announced + // in the server's capabilities. + DigestFunction DigestFunction_Value +} + +func (b0 UpdateActionResultRequest_builder) Build() *UpdateActionResultRequest { + m0 := &UpdateActionResultRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_InstanceName = b.InstanceName + x.xxx_hidden_ActionDigest = b.ActionDigest + x.xxx_hidden_ActionResult = b.ActionResult + x.xxx_hidden_ResultsCachePolicy = b.ResultsCachePolicy + x.xxx_hidden_DigestFunction = b.DigestFunction + return m0 +} + +// A request message for +// [ContentAddressableStorage.FindMissingBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.FindMissingBlobs]. +type FindMissingBlobsRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3"` + xxx_hidden_BlobDigests *[]*Digest `protobuf:"bytes,2,rep,name=blob_digests,json=blobDigests,proto3"` + xxx_hidden_DigestFunction DigestFunction_Value `protobuf:"varint,3,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FindMissingBlobsRequest) Reset() { + *x = FindMissingBlobsRequest{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[26] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FindMissingBlobsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FindMissingBlobsRequest) ProtoMessage() {} + +func (x *FindMissingBlobsRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[26] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *FindMissingBlobsRequest) GetInstanceName() string { + if x != nil { + return x.xxx_hidden_InstanceName + } + return "" +} + +func (x *FindMissingBlobsRequest) GetBlobDigests() []*Digest { + if x != nil { + if x.xxx_hidden_BlobDigests != nil { + return *x.xxx_hidden_BlobDigests + } + } + return nil +} + +func (x *FindMissingBlobsRequest) GetDigestFunction() DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return DigestFunction_UNKNOWN +} + +func (x *FindMissingBlobsRequest) SetInstanceName(v string) { + x.xxx_hidden_InstanceName = v +} + +func (x *FindMissingBlobsRequest) SetBlobDigests(v []*Digest) { + x.xxx_hidden_BlobDigests = &v +} + +func (x *FindMissingBlobsRequest) SetDigestFunction(v DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +type FindMissingBlobsRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + InstanceName string + // A list of the blobs to check. All digests MUST use the same digest + // function. + BlobDigests []*Digest + // The digest function of the blobs whose existence is checked. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the blob digest hashes and the digest functions announced + // in the server's capabilities. + DigestFunction DigestFunction_Value +} + +func (b0 FindMissingBlobsRequest_builder) Build() *FindMissingBlobsRequest { + m0 := &FindMissingBlobsRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_InstanceName = b.InstanceName + x.xxx_hidden_BlobDigests = &b.BlobDigests + x.xxx_hidden_DigestFunction = b.DigestFunction + return m0 +} + +// A response message for +// [ContentAddressableStorage.FindMissingBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.FindMissingBlobs]. +type FindMissingBlobsResponse struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_MissingBlobDigests *[]*Digest `protobuf:"bytes,2,rep,name=missing_blob_digests,json=missingBlobDigests,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FindMissingBlobsResponse) Reset() { + *x = FindMissingBlobsResponse{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[27] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FindMissingBlobsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FindMissingBlobsResponse) ProtoMessage() {} + +func (x *FindMissingBlobsResponse) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[27] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *FindMissingBlobsResponse) GetMissingBlobDigests() []*Digest { + if x != nil { + if x.xxx_hidden_MissingBlobDigests != nil { + return *x.xxx_hidden_MissingBlobDigests + } + } + return nil +} + +func (x *FindMissingBlobsResponse) SetMissingBlobDigests(v []*Digest) { + x.xxx_hidden_MissingBlobDigests = &v +} + +type FindMissingBlobsResponse_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // A list of the blobs requested *not* present in the storage. + MissingBlobDigests []*Digest +} + +func (b0 FindMissingBlobsResponse_builder) Build() *FindMissingBlobsResponse { + m0 := &FindMissingBlobsResponse{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_MissingBlobDigests = &b.MissingBlobDigests + return m0 +} + +// A request message for +// [ContentAddressableStorage.BatchUpdateBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchUpdateBlobs]. +type BatchUpdateBlobsRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3"` + xxx_hidden_Requests *[]*BatchUpdateBlobsRequest_Request `protobuf:"bytes,2,rep,name=requests,proto3"` + xxx_hidden_DigestFunction DigestFunction_Value `protobuf:"varint,5,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *BatchUpdateBlobsRequest) Reset() { + *x = BatchUpdateBlobsRequest{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[28] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *BatchUpdateBlobsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*BatchUpdateBlobsRequest) ProtoMessage() {} + +func (x *BatchUpdateBlobsRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[28] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *BatchUpdateBlobsRequest) GetInstanceName() string { + if x != nil { + return x.xxx_hidden_InstanceName + } + return "" +} + +func (x *BatchUpdateBlobsRequest) GetRequests() []*BatchUpdateBlobsRequest_Request { + if x != nil { + if x.xxx_hidden_Requests != nil { + return *x.xxx_hidden_Requests + } + } + return nil +} + +func (x *BatchUpdateBlobsRequest) GetDigestFunction() DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return DigestFunction_UNKNOWN +} + +func (x *BatchUpdateBlobsRequest) SetInstanceName(v string) { + x.xxx_hidden_InstanceName = v +} + +func (x *BatchUpdateBlobsRequest) SetRequests(v []*BatchUpdateBlobsRequest_Request) { + x.xxx_hidden_Requests = &v +} + +func (x *BatchUpdateBlobsRequest) SetDigestFunction(v DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +type BatchUpdateBlobsRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + InstanceName string + // The individual upload requests. + Requests []*BatchUpdateBlobsRequest_Request + // The digest function that was used to compute the digests of the + // blobs being uploaded. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the blob digest hashes and the digest functions announced + // in the server's capabilities. + DigestFunction DigestFunction_Value +} + +func (b0 BatchUpdateBlobsRequest_builder) Build() *BatchUpdateBlobsRequest { + m0 := &BatchUpdateBlobsRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_InstanceName = b.InstanceName + x.xxx_hidden_Requests = &b.Requests + x.xxx_hidden_DigestFunction = b.DigestFunction + return m0 +} + +// A response message for +// [ContentAddressableStorage.BatchUpdateBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchUpdateBlobs]. +type BatchUpdateBlobsResponse struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Responses *[]*BatchUpdateBlobsResponse_Response `protobuf:"bytes,1,rep,name=responses,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *BatchUpdateBlobsResponse) Reset() { + *x = BatchUpdateBlobsResponse{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[29] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *BatchUpdateBlobsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*BatchUpdateBlobsResponse) ProtoMessage() {} + +func (x *BatchUpdateBlobsResponse) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[29] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *BatchUpdateBlobsResponse) GetResponses() []*BatchUpdateBlobsResponse_Response { + if x != nil { + if x.xxx_hidden_Responses != nil { + return *x.xxx_hidden_Responses + } + } + return nil +} + +func (x *BatchUpdateBlobsResponse) SetResponses(v []*BatchUpdateBlobsResponse_Response) { + x.xxx_hidden_Responses = &v +} + +type BatchUpdateBlobsResponse_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The responses to the requests. + Responses []*BatchUpdateBlobsResponse_Response +} + +func (b0 BatchUpdateBlobsResponse_builder) Build() *BatchUpdateBlobsResponse { + m0 := &BatchUpdateBlobsResponse{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Responses = &b.Responses + return m0 +} + +// A request message for +// [ContentAddressableStorage.BatchReadBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchReadBlobs]. +type BatchReadBlobsRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3"` + xxx_hidden_Digests *[]*Digest `protobuf:"bytes,2,rep,name=digests,proto3"` + xxx_hidden_AcceptableCompressors []Compressor_Value `protobuf:"varint,3,rep,packed,name=acceptable_compressors,json=acceptableCompressors,proto3,enum=build.bazel.remote.execution.v2.Compressor_Value"` + xxx_hidden_DigestFunction DigestFunction_Value `protobuf:"varint,4,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *BatchReadBlobsRequest) Reset() { + *x = BatchReadBlobsRequest{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[30] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *BatchReadBlobsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*BatchReadBlobsRequest) ProtoMessage() {} + +func (x *BatchReadBlobsRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[30] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *BatchReadBlobsRequest) GetInstanceName() string { + if x != nil { + return x.xxx_hidden_InstanceName + } + return "" +} + +func (x *BatchReadBlobsRequest) GetDigests() []*Digest { + if x != nil { + if x.xxx_hidden_Digests != nil { + return *x.xxx_hidden_Digests + } + } + return nil +} + +func (x *BatchReadBlobsRequest) GetAcceptableCompressors() []Compressor_Value { + if x != nil { + return x.xxx_hidden_AcceptableCompressors + } + return nil +} + +func (x *BatchReadBlobsRequest) GetDigestFunction() DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return DigestFunction_UNKNOWN +} + +func (x *BatchReadBlobsRequest) SetInstanceName(v string) { + x.xxx_hidden_InstanceName = v +} + +func (x *BatchReadBlobsRequest) SetDigests(v []*Digest) { + x.xxx_hidden_Digests = &v +} + +func (x *BatchReadBlobsRequest) SetAcceptableCompressors(v []Compressor_Value) { + x.xxx_hidden_AcceptableCompressors = v +} + +func (x *BatchReadBlobsRequest) SetDigestFunction(v DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +type BatchReadBlobsRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + InstanceName string + // The individual blob digests. All digests MUST use the same digest + // function. + Digests []*Digest + // A list of acceptable encodings for the returned inlined data, in no + // particular order. `IDENTITY` is always allowed even if not specified here. + AcceptableCompressors []Compressor_Value + // The digest function of the blobs being requested. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the blob digest hashes and the digest functions announced + // in the server's capabilities. + DigestFunction DigestFunction_Value +} + +func (b0 BatchReadBlobsRequest_builder) Build() *BatchReadBlobsRequest { + m0 := &BatchReadBlobsRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_InstanceName = b.InstanceName + x.xxx_hidden_Digests = &b.Digests + x.xxx_hidden_AcceptableCompressors = b.AcceptableCompressors + x.xxx_hidden_DigestFunction = b.DigestFunction + return m0 +} + +// A response message for +// [ContentAddressableStorage.BatchReadBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchReadBlobs]. +type BatchReadBlobsResponse struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Responses *[]*BatchReadBlobsResponse_Response `protobuf:"bytes,1,rep,name=responses,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *BatchReadBlobsResponse) Reset() { + *x = BatchReadBlobsResponse{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[31] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *BatchReadBlobsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*BatchReadBlobsResponse) ProtoMessage() {} + +func (x *BatchReadBlobsResponse) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[31] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *BatchReadBlobsResponse) GetResponses() []*BatchReadBlobsResponse_Response { + if x != nil { + if x.xxx_hidden_Responses != nil { + return *x.xxx_hidden_Responses + } + } + return nil +} + +func (x *BatchReadBlobsResponse) SetResponses(v []*BatchReadBlobsResponse_Response) { + x.xxx_hidden_Responses = &v +} + +type BatchReadBlobsResponse_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The responses to the requests. + Responses []*BatchReadBlobsResponse_Response +} + +func (b0 BatchReadBlobsResponse_builder) Build() *BatchReadBlobsResponse { + m0 := &BatchReadBlobsResponse{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Responses = &b.Responses + return m0 +} + +// A request message for +// [ContentAddressableStorage.GetTree][build.bazel.remote.execution.v2.ContentAddressableStorage.GetTree]. +type GetTreeRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3"` + xxx_hidden_RootDigest *Digest `protobuf:"bytes,2,opt,name=root_digest,json=rootDigest,proto3"` + xxx_hidden_PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3"` + xxx_hidden_PageToken string `protobuf:"bytes,4,opt,name=page_token,json=pageToken,proto3"` + xxx_hidden_DigestFunction DigestFunction_Value `protobuf:"varint,5,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetTreeRequest) Reset() { + *x = GetTreeRequest{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[32] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetTreeRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetTreeRequest) ProtoMessage() {} + +func (x *GetTreeRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[32] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *GetTreeRequest) GetInstanceName() string { + if x != nil { + return x.xxx_hidden_InstanceName + } + return "" +} + +func (x *GetTreeRequest) GetRootDigest() *Digest { + if x != nil { + return x.xxx_hidden_RootDigest + } + return nil +} + +func (x *GetTreeRequest) GetPageSize() int32 { + if x != nil { + return x.xxx_hidden_PageSize + } + return 0 +} + +func (x *GetTreeRequest) GetPageToken() string { + if x != nil { + return x.xxx_hidden_PageToken + } + return "" +} + +func (x *GetTreeRequest) GetDigestFunction() DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return DigestFunction_UNKNOWN +} + +func (x *GetTreeRequest) SetInstanceName(v string) { + x.xxx_hidden_InstanceName = v +} + +func (x *GetTreeRequest) SetRootDigest(v *Digest) { + x.xxx_hidden_RootDigest = v +} + +func (x *GetTreeRequest) SetPageSize(v int32) { + x.xxx_hidden_PageSize = v +} + +func (x *GetTreeRequest) SetPageToken(v string) { + x.xxx_hidden_PageToken = v +} + +func (x *GetTreeRequest) SetDigestFunction(v DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +func (x *GetTreeRequest) HasRootDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_RootDigest != nil +} + +func (x *GetTreeRequest) ClearRootDigest() { + x.xxx_hidden_RootDigest = nil +} + +type GetTreeRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + InstanceName string + // The digest of the root, which must be an encoded + // [Directory][build.bazel.remote.execution.v2.Directory] message + // stored in the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + RootDigest *Digest + // A maximum page size to request. If present, the server will request no more + // than this many items. Regardless of whether a page size is specified, the + // server may place its own limit on the number of items to be returned and + // require the client to retrieve more items using a subsequent request. + PageSize int32 + // A page token, which must be a value received in a previous + // [GetTreeResponse][build.bazel.remote.execution.v2.GetTreeResponse]. + // If present, the server will use that token as an offset, returning only + // that page and the ones that succeed it. + PageToken string + // The digest function that was used to compute the digest of the root + // directory. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the root digest hash and the digest functions announced + // in the server's capabilities. + DigestFunction DigestFunction_Value +} + +func (b0 GetTreeRequest_builder) Build() *GetTreeRequest { + m0 := &GetTreeRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_InstanceName = b.InstanceName + x.xxx_hidden_RootDigest = b.RootDigest + x.xxx_hidden_PageSize = b.PageSize + x.xxx_hidden_PageToken = b.PageToken + x.xxx_hidden_DigestFunction = b.DigestFunction + return m0 +} + +// A response message for +// [ContentAddressableStorage.GetTree][build.bazel.remote.execution.v2.ContentAddressableStorage.GetTree]. +type GetTreeResponse struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Directories *[]*Directory `protobuf:"bytes,1,rep,name=directories,proto3"` + xxx_hidden_NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetTreeResponse) Reset() { + *x = GetTreeResponse{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[33] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetTreeResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetTreeResponse) ProtoMessage() {} + +func (x *GetTreeResponse) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[33] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *GetTreeResponse) GetDirectories() []*Directory { + if x != nil { + if x.xxx_hidden_Directories != nil { + return *x.xxx_hidden_Directories + } + } + return nil +} + +func (x *GetTreeResponse) GetNextPageToken() string { + if x != nil { + return x.xxx_hidden_NextPageToken + } + return "" +} + +func (x *GetTreeResponse) SetDirectories(v []*Directory) { + x.xxx_hidden_Directories = &v +} + +func (x *GetTreeResponse) SetNextPageToken(v string) { + x.xxx_hidden_NextPageToken = v +} + +type GetTreeResponse_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The directories descended from the requested root. + Directories []*Directory + // If present, signifies that there are more results which the client can + // retrieve by passing this as the page_token in a subsequent + // [request][build.bazel.remote.execution.v2.GetTreeRequest]. + // If empty, signifies that this is the last page of results. + NextPageToken string +} + +func (b0 GetTreeResponse_builder) Build() *GetTreeResponse { + m0 := &GetTreeResponse{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Directories = &b.Directories + x.xxx_hidden_NextPageToken = b.NextPageToken + return m0 +} + +// A request message for +// [ContentAddressableStorage.SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob]. +type SplitBlobRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3"` + xxx_hidden_BlobDigest *Digest `protobuf:"bytes,2,opt,name=blob_digest,json=blobDigest,proto3"` + xxx_hidden_DigestFunction DigestFunction_Value `protobuf:"varint,3,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + xxx_hidden_ChunkingFunction ChunkingFunction_Value `protobuf:"varint,4,opt,name=chunking_function,json=chunkingFunction,proto3,enum=build.bazel.remote.execution.v2.ChunkingFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SplitBlobRequest) Reset() { + *x = SplitBlobRequest{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[34] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SplitBlobRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SplitBlobRequest) ProtoMessage() {} + +func (x *SplitBlobRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[34] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *SplitBlobRequest) GetInstanceName() string { + if x != nil { + return x.xxx_hidden_InstanceName + } + return "" +} + +func (x *SplitBlobRequest) GetBlobDigest() *Digest { + if x != nil { + return x.xxx_hidden_BlobDigest + } + return nil +} + +func (x *SplitBlobRequest) GetDigestFunction() DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return DigestFunction_UNKNOWN +} + +func (x *SplitBlobRequest) GetChunkingFunction() ChunkingFunction_Value { + if x != nil { + return x.xxx_hidden_ChunkingFunction + } + return ChunkingFunction_UNKNOWN +} + +func (x *SplitBlobRequest) SetInstanceName(v string) { + x.xxx_hidden_InstanceName = v +} + +func (x *SplitBlobRequest) SetBlobDigest(v *Digest) { + x.xxx_hidden_BlobDigest = v +} + +func (x *SplitBlobRequest) SetDigestFunction(v DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +func (x *SplitBlobRequest) SetChunkingFunction(v ChunkingFunction_Value) { + x.xxx_hidden_ChunkingFunction = v +} + +func (x *SplitBlobRequest) HasBlobDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_BlobDigest != nil +} + +func (x *SplitBlobRequest) ClearBlobDigest() { + x.xxx_hidden_BlobDigest = nil +} + +type SplitBlobRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + InstanceName string + // The digest of the blob to be split. + BlobDigest *Digest + // The digest function of the blob to be split. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the blob digest hashes and the digest functions announced + // in the server's capabilities. + DigestFunction DigestFunction_Value + // The chunking function that the client prefers to use. + // + // The server MAY use a different chunking function. + ChunkingFunction ChunkingFunction_Value +} + +func (b0 SplitBlobRequest_builder) Build() *SplitBlobRequest { + m0 := &SplitBlobRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_InstanceName = b.InstanceName + x.xxx_hidden_BlobDigest = b.BlobDigest + x.xxx_hidden_DigestFunction = b.DigestFunction + x.xxx_hidden_ChunkingFunction = b.ChunkingFunction + return m0 +} + +// A response message for +// [ContentAddressableStorage.SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob]. +type SplitBlobResponse struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_ChunkDigests *[]*Digest `protobuf:"bytes,1,rep,name=chunk_digests,json=chunkDigests,proto3"` + xxx_hidden_ChunkingFunction ChunkingFunction_Value `protobuf:"varint,2,opt,name=chunking_function,json=chunkingFunction,proto3,enum=build.bazel.remote.execution.v2.ChunkingFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SplitBlobResponse) Reset() { + *x = SplitBlobResponse{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[35] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SplitBlobResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SplitBlobResponse) ProtoMessage() {} + +func (x *SplitBlobResponse) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[35] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *SplitBlobResponse) GetChunkDigests() []*Digest { + if x != nil { + if x.xxx_hidden_ChunkDigests != nil { + return *x.xxx_hidden_ChunkDigests + } + } + return nil +} + +func (x *SplitBlobResponse) GetChunkingFunction() ChunkingFunction_Value { + if x != nil { + return x.xxx_hidden_ChunkingFunction + } + return ChunkingFunction_UNKNOWN +} + +func (x *SplitBlobResponse) SetChunkDigests(v []*Digest) { + x.xxx_hidden_ChunkDigests = &v +} + +func (x *SplitBlobResponse) SetChunkingFunction(v ChunkingFunction_Value) { + x.xxx_hidden_ChunkingFunction = v +} + +type SplitBlobResponse_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The ordered list of digests of the chunks into which the blob was split. + // The original blob is assembled by concatenating the chunk data according to + // the order of the digests given by this list. + // + // The server MUST use the same digest function as the one explicitly or + // implicitly (through hash length) specified in the split request. + ChunkDigests []*Digest + // The chunking function used to split the blob. + ChunkingFunction ChunkingFunction_Value +} + +func (b0 SplitBlobResponse_builder) Build() *SplitBlobResponse { + m0 := &SplitBlobResponse{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_ChunkDigests = &b.ChunkDigests + x.xxx_hidden_ChunkingFunction = b.ChunkingFunction + return m0 +} + +// A request message for +// [ContentAddressableStorage.SpliceBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SpliceBlob]. +type SpliceBlobRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3"` + xxx_hidden_BlobDigest *Digest `protobuf:"bytes,2,opt,name=blob_digest,json=blobDigest,proto3"` + xxx_hidden_ChunkDigests *[]*Digest `protobuf:"bytes,3,rep,name=chunk_digests,json=chunkDigests,proto3"` + xxx_hidden_DigestFunction DigestFunction_Value `protobuf:"varint,4,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + xxx_hidden_ChunkingFunction ChunkingFunction_Value `protobuf:"varint,5,opt,name=chunking_function,json=chunkingFunction,proto3,enum=build.bazel.remote.execution.v2.ChunkingFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SpliceBlobRequest) Reset() { + *x = SpliceBlobRequest{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[36] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SpliceBlobRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SpliceBlobRequest) ProtoMessage() {} + +func (x *SpliceBlobRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[36] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *SpliceBlobRequest) GetInstanceName() string { + if x != nil { + return x.xxx_hidden_InstanceName + } + return "" +} + +func (x *SpliceBlobRequest) GetBlobDigest() *Digest { + if x != nil { + return x.xxx_hidden_BlobDigest + } + return nil +} + +func (x *SpliceBlobRequest) GetChunkDigests() []*Digest { + if x != nil { + if x.xxx_hidden_ChunkDigests != nil { + return *x.xxx_hidden_ChunkDigests + } + } + return nil +} + +func (x *SpliceBlobRequest) GetDigestFunction() DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return DigestFunction_UNKNOWN +} + +func (x *SpliceBlobRequest) GetChunkingFunction() ChunkingFunction_Value { + if x != nil { + return x.xxx_hidden_ChunkingFunction + } + return ChunkingFunction_UNKNOWN +} + +func (x *SpliceBlobRequest) SetInstanceName(v string) { + x.xxx_hidden_InstanceName = v +} + +func (x *SpliceBlobRequest) SetBlobDigest(v *Digest) { + x.xxx_hidden_BlobDigest = v +} + +func (x *SpliceBlobRequest) SetChunkDigests(v []*Digest) { + x.xxx_hidden_ChunkDigests = &v +} + +func (x *SpliceBlobRequest) SetDigestFunction(v DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +func (x *SpliceBlobRequest) SetChunkingFunction(v ChunkingFunction_Value) { + x.xxx_hidden_ChunkingFunction = v +} + +func (x *SpliceBlobRequest) HasBlobDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_BlobDigest != nil +} + +func (x *SpliceBlobRequest) ClearBlobDigest() { + x.xxx_hidden_BlobDigest = nil +} + +type SpliceBlobRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + InstanceName string + // Expected digest of the spliced blob. The client MUST set this field due + // to the following reasons: + // 1. It allows the server to perform an early existence check of the blob + // or existing chunks that assemble the blob before spending the splicing + // effort, as described in the [ContentAddressableStorage.SpliceBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SpliceBlob] + // documentation. + // 2. It allows servers with different storage backends to dispatch the + // request to the correct storage backend based on the size and/or the + // hash of the blob. + // 3. If chunking information already exists for the blob, it allows + // the server to keep the existing chunking information or replace it with + // new chunking information. + BlobDigest *Digest + // The ordered list of digests of the chunks which need to be concatenated to + // assemble the original blob. + ChunkDigests []*Digest + // The digest function of all chunks to be concatenated and of the blob to be + // spliced. The server MUST use the same digest function for both cases. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, SHA384, + // SHA512, or VSO, the client MAY leave this field unset. In that case the + // server SHOULD infer the digest function using the length of the blob digest + // hashes and the digest functions announced in the server's capabilities. + DigestFunction DigestFunction_Value + // The chunking function that the client used to split the blob. + ChunkingFunction ChunkingFunction_Value +} + +func (b0 SpliceBlobRequest_builder) Build() *SpliceBlobRequest { + m0 := &SpliceBlobRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_InstanceName = b.InstanceName + x.xxx_hidden_BlobDigest = b.BlobDigest + x.xxx_hidden_ChunkDigests = &b.ChunkDigests + x.xxx_hidden_DigestFunction = b.DigestFunction + x.xxx_hidden_ChunkingFunction = b.ChunkingFunction + return m0 +} + +// A response message for +// [ContentAddressableStorage.SpliceBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SpliceBlob]. +type SpliceBlobResponse struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_BlobDigest *Digest `protobuf:"bytes,1,opt,name=blob_digest,json=blobDigest,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SpliceBlobResponse) Reset() { + *x = SpliceBlobResponse{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[37] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SpliceBlobResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SpliceBlobResponse) ProtoMessage() {} + +func (x *SpliceBlobResponse) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[37] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *SpliceBlobResponse) GetBlobDigest() *Digest { + if x != nil { + return x.xxx_hidden_BlobDigest + } + return nil +} + +func (x *SpliceBlobResponse) SetBlobDigest(v *Digest) { + x.xxx_hidden_BlobDigest = v +} + +func (x *SpliceBlobResponse) HasBlobDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_BlobDigest != nil +} + +func (x *SpliceBlobResponse) ClearBlobDigest() { + x.xxx_hidden_BlobDigest = nil +} + +type SpliceBlobResponse_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // Computed digest of the spliced blob. + // + // The server MUST use the same digest function as the one explicitly or + // implicitly (through hash length) specified in the splice request. + BlobDigest *Digest +} + +func (b0 SpliceBlobResponse_builder) Build() *SpliceBlobResponse { + m0 := &SpliceBlobResponse{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_BlobDigest = b.BlobDigest + return m0 +} + +// A request message for +// [Capabilities.GetCapabilities][build.bazel.remote.execution.v2.Capabilities.GetCapabilities]. +type GetCapabilitiesRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetCapabilitiesRequest) Reset() { + *x = GetCapabilitiesRequest{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[38] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetCapabilitiesRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetCapabilitiesRequest) ProtoMessage() {} + +func (x *GetCapabilitiesRequest) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[38] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *GetCapabilitiesRequest) GetInstanceName() string { + if x != nil { + return x.xxx_hidden_InstanceName + } + return "" +} + +func (x *GetCapabilitiesRequest) SetInstanceName(v string) { + x.xxx_hidden_InstanceName = v +} + +type GetCapabilitiesRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + InstanceName string +} + +func (b0 GetCapabilitiesRequest_builder) Build() *GetCapabilitiesRequest { + m0 := &GetCapabilitiesRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_InstanceName = b.InstanceName + return m0 +} + +// A response message for +// [Capabilities.GetCapabilities][build.bazel.remote.execution.v2.Capabilities.GetCapabilities]. +type ServerCapabilities struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_CacheCapabilities *CacheCapabilities `protobuf:"bytes,1,opt,name=cache_capabilities,json=cacheCapabilities,proto3"` + xxx_hidden_ExecutionCapabilities *ExecutionCapabilities `protobuf:"bytes,2,opt,name=execution_capabilities,json=executionCapabilities,proto3"` + xxx_hidden_DeprecatedApiVersion *semver.SemVer `protobuf:"bytes,3,opt,name=deprecated_api_version,json=deprecatedApiVersion,proto3"` + xxx_hidden_LowApiVersion *semver.SemVer `protobuf:"bytes,4,opt,name=low_api_version,json=lowApiVersion,proto3"` + xxx_hidden_HighApiVersion *semver.SemVer `protobuf:"bytes,5,opt,name=high_api_version,json=highApiVersion,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ServerCapabilities) Reset() { + *x = ServerCapabilities{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[39] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ServerCapabilities) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ServerCapabilities) ProtoMessage() {} + +func (x *ServerCapabilities) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[39] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *ServerCapabilities) GetCacheCapabilities() *CacheCapabilities { + if x != nil { + return x.xxx_hidden_CacheCapabilities + } + return nil +} + +func (x *ServerCapabilities) GetExecutionCapabilities() *ExecutionCapabilities { + if x != nil { + return x.xxx_hidden_ExecutionCapabilities + } + return nil +} + +func (x *ServerCapabilities) GetDeprecatedApiVersion() *semver.SemVer { + if x != nil { + return x.xxx_hidden_DeprecatedApiVersion + } + return nil +} + +func (x *ServerCapabilities) GetLowApiVersion() *semver.SemVer { + if x != nil { + return x.xxx_hidden_LowApiVersion + } + return nil +} + +func (x *ServerCapabilities) GetHighApiVersion() *semver.SemVer { + if x != nil { + return x.xxx_hidden_HighApiVersion + } + return nil +} + +func (x *ServerCapabilities) SetCacheCapabilities(v *CacheCapabilities) { + x.xxx_hidden_CacheCapabilities = v +} + +func (x *ServerCapabilities) SetExecutionCapabilities(v *ExecutionCapabilities) { + x.xxx_hidden_ExecutionCapabilities = v +} + +func (x *ServerCapabilities) SetDeprecatedApiVersion(v *semver.SemVer) { + x.xxx_hidden_DeprecatedApiVersion = v +} + +func (x *ServerCapabilities) SetLowApiVersion(v *semver.SemVer) { + x.xxx_hidden_LowApiVersion = v +} + +func (x *ServerCapabilities) SetHighApiVersion(v *semver.SemVer) { + x.xxx_hidden_HighApiVersion = v +} + +func (x *ServerCapabilities) HasCacheCapabilities() bool { + if x == nil { + return false + } + return x.xxx_hidden_CacheCapabilities != nil +} + +func (x *ServerCapabilities) HasExecutionCapabilities() bool { + if x == nil { + return false + } + return x.xxx_hidden_ExecutionCapabilities != nil +} + +func (x *ServerCapabilities) HasDeprecatedApiVersion() bool { + if x == nil { + return false + } + return x.xxx_hidden_DeprecatedApiVersion != nil +} + +func (x *ServerCapabilities) HasLowApiVersion() bool { + if x == nil { + return false + } + return x.xxx_hidden_LowApiVersion != nil +} + +func (x *ServerCapabilities) HasHighApiVersion() bool { + if x == nil { + return false + } + return x.xxx_hidden_HighApiVersion != nil +} + +func (x *ServerCapabilities) ClearCacheCapabilities() { + x.xxx_hidden_CacheCapabilities = nil +} + +func (x *ServerCapabilities) ClearExecutionCapabilities() { + x.xxx_hidden_ExecutionCapabilities = nil +} + +func (x *ServerCapabilities) ClearDeprecatedApiVersion() { + x.xxx_hidden_DeprecatedApiVersion = nil +} + +func (x *ServerCapabilities) ClearLowApiVersion() { + x.xxx_hidden_LowApiVersion = nil +} + +func (x *ServerCapabilities) ClearHighApiVersion() { + x.xxx_hidden_HighApiVersion = nil +} + +type ServerCapabilities_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // Capabilities of the remote cache system. + CacheCapabilities *CacheCapabilities + // Capabilities of the remote execution system. + ExecutionCapabilities *ExecutionCapabilities + // Earliest RE API version supported, including deprecated versions. + DeprecatedApiVersion *semver.SemVer + // Earliest non-deprecated RE API version supported. + LowApiVersion *semver.SemVer + // Latest RE API version supported. + HighApiVersion *semver.SemVer +} + +func (b0 ServerCapabilities_builder) Build() *ServerCapabilities { + m0 := &ServerCapabilities{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_CacheCapabilities = b.CacheCapabilities + x.xxx_hidden_ExecutionCapabilities = b.ExecutionCapabilities + x.xxx_hidden_DeprecatedApiVersion = b.DeprecatedApiVersion + x.xxx_hidden_LowApiVersion = b.LowApiVersion + x.xxx_hidden_HighApiVersion = b.HighApiVersion + return m0 +} + +// The digest function used for converting values into keys for CAS and Action +// Cache. +type DigestFunction struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DigestFunction) Reset() { + *x = DigestFunction{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[40] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DigestFunction) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DigestFunction) ProtoMessage() {} + +func (x *DigestFunction) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[40] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +type DigestFunction_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + +} + +func (b0 DigestFunction_builder) Build() *DigestFunction { + m0 := &DigestFunction{} + b, x := &b0, m0 + _, _ = b, x + return m0 +} + +// The chunking function is used to split a blob into chunks. +// +// The server advertises support for a chunking function by setting the +// corresponding params field in +// [CacheCapabilities][build.bazel.remote.execution.v2.CacheCapabilities]. +// For example, if fast_cdc_2020_params is set, the server supports FAST_CDC_2020. +// +// For optimal deduplication, clients SHOULD use an advertised chunking function. +// When clients use UNKNOWN, the server chooses an algorithm for SplitBlob and +// simply verifies chunk concatenation for SpliceBlob. +type ChunkingFunction struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ChunkingFunction) Reset() { + *x = ChunkingFunction{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[41] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ChunkingFunction) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChunkingFunction) ProtoMessage() {} + +func (x *ChunkingFunction) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[41] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +type ChunkingFunction_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + +} + +func (b0 ChunkingFunction_builder) Build() *ChunkingFunction { + m0 := &ChunkingFunction{} + b, x := &b0, m0 + _, _ = b, x + return m0 +} + +// Describes the server/instance capabilities for updating the action cache. +type ActionCacheUpdateCapabilities struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_UpdateEnabled bool `protobuf:"varint,1,opt,name=update_enabled,json=updateEnabled,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ActionCacheUpdateCapabilities) Reset() { + *x = ActionCacheUpdateCapabilities{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[42] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ActionCacheUpdateCapabilities) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ActionCacheUpdateCapabilities) ProtoMessage() {} + +func (x *ActionCacheUpdateCapabilities) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[42] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *ActionCacheUpdateCapabilities) GetUpdateEnabled() bool { + if x != nil { + return x.xxx_hidden_UpdateEnabled + } + return false +} + +func (x *ActionCacheUpdateCapabilities) SetUpdateEnabled(v bool) { + x.xxx_hidden_UpdateEnabled = v +} + +type ActionCacheUpdateCapabilities_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + UpdateEnabled bool +} + +func (b0 ActionCacheUpdateCapabilities_builder) Build() *ActionCacheUpdateCapabilities { + m0 := &ActionCacheUpdateCapabilities{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_UpdateEnabled = b.UpdateEnabled + return m0 +} + +// Allowed values for priority in +// [ResultsCachePolicy][build.bazel.remote.execution.v2.ResultsCachePolicy] and +// [ExecutionPolicy][build.bazel.remote.execution.v2.ExecutionPolicy] +// Used for querying both cache and execution valid priority ranges. +type PriorityCapabilities struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Priorities *[]*PriorityCapabilities_PriorityRange `protobuf:"bytes,1,rep,name=priorities,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PriorityCapabilities) Reset() { + *x = PriorityCapabilities{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[43] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PriorityCapabilities) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PriorityCapabilities) ProtoMessage() {} + +func (x *PriorityCapabilities) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[43] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *PriorityCapabilities) GetPriorities() []*PriorityCapabilities_PriorityRange { + if x != nil { + if x.xxx_hidden_Priorities != nil { + return *x.xxx_hidden_Priorities + } + } + return nil +} + +func (x *PriorityCapabilities) SetPriorities(v []*PriorityCapabilities_PriorityRange) { + x.xxx_hidden_Priorities = &v +} + +type PriorityCapabilities_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + Priorities []*PriorityCapabilities_PriorityRange +} + +func (b0 PriorityCapabilities_builder) Build() *PriorityCapabilities { + m0 := &PriorityCapabilities{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Priorities = &b.Priorities + return m0 +} + +// Describes how the server treats absolute symlink targets. +type SymlinkAbsolutePathStrategy struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SymlinkAbsolutePathStrategy) Reset() { + *x = SymlinkAbsolutePathStrategy{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[44] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SymlinkAbsolutePathStrategy) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SymlinkAbsolutePathStrategy) ProtoMessage() {} + +func (x *SymlinkAbsolutePathStrategy) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[44] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +type SymlinkAbsolutePathStrategy_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + +} + +func (b0 SymlinkAbsolutePathStrategy_builder) Build() *SymlinkAbsolutePathStrategy { + m0 := &SymlinkAbsolutePathStrategy{} + b, x := &b0, m0 + _, _ = b, x + return m0 +} + +// Compression formats which may be supported. +type Compressor struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Compressor) Reset() { + *x = Compressor{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[45] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Compressor) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Compressor) ProtoMessage() {} + +func (x *Compressor) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[45] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +type Compressor_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + +} + +func (b0 Compressor_builder) Build() *Compressor { + m0 := &Compressor{} + b, x := &b0, m0 + _, _ = b, x + return m0 +} + +// Capabilities of the remote cache system. +type CacheCapabilities struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_DigestFunctions []DigestFunction_Value `protobuf:"varint,1,rep,packed,name=digest_functions,json=digestFunctions,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + xxx_hidden_ActionCacheUpdateCapabilities *ActionCacheUpdateCapabilities `protobuf:"bytes,2,opt,name=action_cache_update_capabilities,json=actionCacheUpdateCapabilities,proto3"` + xxx_hidden_CachePriorityCapabilities *PriorityCapabilities `protobuf:"bytes,3,opt,name=cache_priority_capabilities,json=cachePriorityCapabilities,proto3"` + xxx_hidden_MaxBatchTotalSizeBytes int64 `protobuf:"varint,4,opt,name=max_batch_total_size_bytes,json=maxBatchTotalSizeBytes,proto3"` + xxx_hidden_SymlinkAbsolutePathStrategy SymlinkAbsolutePathStrategy_Value `protobuf:"varint,5,opt,name=symlink_absolute_path_strategy,json=symlinkAbsolutePathStrategy,proto3,enum=build.bazel.remote.execution.v2.SymlinkAbsolutePathStrategy_Value"` + xxx_hidden_SupportedCompressors []Compressor_Value `protobuf:"varint,6,rep,packed,name=supported_compressors,json=supportedCompressors,proto3,enum=build.bazel.remote.execution.v2.Compressor_Value"` + xxx_hidden_SupportedBatchUpdateCompressors []Compressor_Value `protobuf:"varint,7,rep,packed,name=supported_batch_update_compressors,json=supportedBatchUpdateCompressors,proto3,enum=build.bazel.remote.execution.v2.Compressor_Value"` + xxx_hidden_MaxCasBlobSizeBytes int64 `protobuf:"varint,8,opt,name=max_cas_blob_size_bytes,json=maxCasBlobSizeBytes,proto3"` + xxx_hidden_SplitBlobSupport bool `protobuf:"varint,9,opt,name=split_blob_support,json=splitBlobSupport,proto3"` + xxx_hidden_SpliceBlobSupport bool `protobuf:"varint,10,opt,name=splice_blob_support,json=spliceBlobSupport,proto3"` + xxx_hidden_FastCdc_2020Params *FastCdc2020Params `protobuf:"bytes,11,opt,name=fast_cdc_2020_params,json=fastCdc2020Params,proto3"` + xxx_hidden_RepMaxCdcParams *RepMaxCdcParams `protobuf:"bytes,12,opt,name=rep_max_cdc_params,json=repMaxCdcParams,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CacheCapabilities) Reset() { + *x = CacheCapabilities{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[46] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CacheCapabilities) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CacheCapabilities) ProtoMessage() {} + +func (x *CacheCapabilities) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[46] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *CacheCapabilities) GetDigestFunctions() []DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunctions + } + return nil +} + +func (x *CacheCapabilities) GetActionCacheUpdateCapabilities() *ActionCacheUpdateCapabilities { + if x != nil { + return x.xxx_hidden_ActionCacheUpdateCapabilities + } + return nil +} + +func (x *CacheCapabilities) GetCachePriorityCapabilities() *PriorityCapabilities { + if x != nil { + return x.xxx_hidden_CachePriorityCapabilities + } + return nil +} + +func (x *CacheCapabilities) GetMaxBatchTotalSizeBytes() int64 { + if x != nil { + return x.xxx_hidden_MaxBatchTotalSizeBytes + } + return 0 +} + +func (x *CacheCapabilities) GetSymlinkAbsolutePathStrategy() SymlinkAbsolutePathStrategy_Value { + if x != nil { + return x.xxx_hidden_SymlinkAbsolutePathStrategy + } + return SymlinkAbsolutePathStrategy_UNKNOWN +} + +func (x *CacheCapabilities) GetSupportedCompressors() []Compressor_Value { + if x != nil { + return x.xxx_hidden_SupportedCompressors + } + return nil +} + +func (x *CacheCapabilities) GetSupportedBatchUpdateCompressors() []Compressor_Value { + if x != nil { + return x.xxx_hidden_SupportedBatchUpdateCompressors + } + return nil +} + +func (x *CacheCapabilities) GetMaxCasBlobSizeBytes() int64 { + if x != nil { + return x.xxx_hidden_MaxCasBlobSizeBytes + } + return 0 +} + +func (x *CacheCapabilities) GetSplitBlobSupport() bool { + if x != nil { + return x.xxx_hidden_SplitBlobSupport + } + return false +} + +func (x *CacheCapabilities) GetSpliceBlobSupport() bool { + if x != nil { + return x.xxx_hidden_SpliceBlobSupport + } + return false +} + +func (x *CacheCapabilities) GetFastCdc_2020Params() *FastCdc2020Params { + if x != nil { + return x.xxx_hidden_FastCdc_2020Params + } + return nil +} + +func (x *CacheCapabilities) GetRepMaxCdcParams() *RepMaxCdcParams { + if x != nil { + return x.xxx_hidden_RepMaxCdcParams + } + return nil +} + +func (x *CacheCapabilities) SetDigestFunctions(v []DigestFunction_Value) { + x.xxx_hidden_DigestFunctions = v +} + +func (x *CacheCapabilities) SetActionCacheUpdateCapabilities(v *ActionCacheUpdateCapabilities) { + x.xxx_hidden_ActionCacheUpdateCapabilities = v +} + +func (x *CacheCapabilities) SetCachePriorityCapabilities(v *PriorityCapabilities) { + x.xxx_hidden_CachePriorityCapabilities = v +} + +func (x *CacheCapabilities) SetMaxBatchTotalSizeBytes(v int64) { + x.xxx_hidden_MaxBatchTotalSizeBytes = v +} + +func (x *CacheCapabilities) SetSymlinkAbsolutePathStrategy(v SymlinkAbsolutePathStrategy_Value) { + x.xxx_hidden_SymlinkAbsolutePathStrategy = v +} + +func (x *CacheCapabilities) SetSupportedCompressors(v []Compressor_Value) { + x.xxx_hidden_SupportedCompressors = v +} + +func (x *CacheCapabilities) SetSupportedBatchUpdateCompressors(v []Compressor_Value) { + x.xxx_hidden_SupportedBatchUpdateCompressors = v +} + +func (x *CacheCapabilities) SetMaxCasBlobSizeBytes(v int64) { + x.xxx_hidden_MaxCasBlobSizeBytes = v +} + +func (x *CacheCapabilities) SetSplitBlobSupport(v bool) { + x.xxx_hidden_SplitBlobSupport = v +} + +func (x *CacheCapabilities) SetSpliceBlobSupport(v bool) { + x.xxx_hidden_SpliceBlobSupport = v +} + +func (x *CacheCapabilities) SetFastCdc_2020Params(v *FastCdc2020Params) { + x.xxx_hidden_FastCdc_2020Params = v +} + +func (x *CacheCapabilities) SetRepMaxCdcParams(v *RepMaxCdcParams) { + x.xxx_hidden_RepMaxCdcParams = v +} + +func (x *CacheCapabilities) HasActionCacheUpdateCapabilities() bool { + if x == nil { + return false + } + return x.xxx_hidden_ActionCacheUpdateCapabilities != nil +} + +func (x *CacheCapabilities) HasCachePriorityCapabilities() bool { + if x == nil { + return false + } + return x.xxx_hidden_CachePriorityCapabilities != nil +} + +func (x *CacheCapabilities) HasFastCdc_2020Params() bool { + if x == nil { + return false + } + return x.xxx_hidden_FastCdc_2020Params != nil +} + +func (x *CacheCapabilities) HasRepMaxCdcParams() bool { + if x == nil { + return false + } + return x.xxx_hidden_RepMaxCdcParams != nil +} + +func (x *CacheCapabilities) ClearActionCacheUpdateCapabilities() { + x.xxx_hidden_ActionCacheUpdateCapabilities = nil +} + +func (x *CacheCapabilities) ClearCachePriorityCapabilities() { + x.xxx_hidden_CachePriorityCapabilities = nil +} + +func (x *CacheCapabilities) ClearFastCdc_2020Params() { + x.xxx_hidden_FastCdc_2020Params = nil +} + +func (x *CacheCapabilities) ClearRepMaxCdcParams() { + x.xxx_hidden_RepMaxCdcParams = nil +} + +type CacheCapabilities_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // All the digest functions supported by the remote cache. + // Remote cache may support multiple digest functions simultaneously. + DigestFunctions []DigestFunction_Value + // Capabilities for updating the action cache. + ActionCacheUpdateCapabilities *ActionCacheUpdateCapabilities + // Supported cache priority range for both CAS and ActionCache. + CachePriorityCapabilities *PriorityCapabilities + // Maximum total size of blobs to be uploaded/downloaded using + // batch methods. A value of 0 means no limit is set, although + // in practice there will always be a message size limitation + // of the protocol in use, e.g. GRPC. + MaxBatchTotalSizeBytes int64 + // Whether absolute symlink targets are supported. + SymlinkAbsolutePathStrategy SymlinkAbsolutePathStrategy_Value + // Compressors supported by the "compressed-blobs" bytestream resources. + // Servers MUST support identity/no-compression, even if it is not listed + // here. + // + // Note that this does not imply which if any compressors are supported by + // the server at the gRPC level. + SupportedCompressors []Compressor_Value + // Compressors supported for inlined data in + // [BatchUpdateBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchUpdateBlobs] + // requests. + SupportedBatchUpdateCompressors []Compressor_Value + // The maximum blob size that the server will accept for CAS blob uploads. + // - If it is 0, it means there is no limit set. A client may assume + // arbitrarily large blobs may be uploaded to and downloaded from the cache. + // - If it is larger than 0, implementations SHOULD NOT attempt to upload + // blobs with size larger than the limit. Servers SHOULD reject blob + // uploads over the `max_cas_blob_size_bytes` limit with response code + // `INVALID_ARGUMENT` + // - If the cache implementation returns a given limit, it MAY still serve + // blobs larger than this limit. + MaxCasBlobSizeBytes int64 + // Whether blob splitting is supported for the particular server/instance. If + // yes, the server/instance implements the specified behavior for blob + // splitting and a meaningful result can be expected from the + // [ContentAddressableStorage.SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob] + // operation. + SplitBlobSupport bool + // Whether blob splicing is supported for the particular server/instance. If + // yes, the server/instance implements the specified behavior for blob + // splicing and a meaningful result can be expected from the + // [ContentAddressableStorage.SpliceBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SpliceBlob] + // operation. + SpliceBlobSupport bool + // The parameters for the FastCDC 2020 chunking algorithm. + // If set, the server supports the FastCDC chunking algorithm. + FastCdc_2020Params *FastCdc2020Params + // The parameters for the RepMaxCDC chunking algorithm. + // If set, the server supports the RepMaxCDC chunking algorithm. + RepMaxCdcParams *RepMaxCdcParams +} + +func (b0 CacheCapabilities_builder) Build() *CacheCapabilities { + m0 := &CacheCapabilities{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_DigestFunctions = b.DigestFunctions + x.xxx_hidden_ActionCacheUpdateCapabilities = b.ActionCacheUpdateCapabilities + x.xxx_hidden_CachePriorityCapabilities = b.CachePriorityCapabilities + x.xxx_hidden_MaxBatchTotalSizeBytes = b.MaxBatchTotalSizeBytes + x.xxx_hidden_SymlinkAbsolutePathStrategy = b.SymlinkAbsolutePathStrategy + x.xxx_hidden_SupportedCompressors = b.SupportedCompressors + x.xxx_hidden_SupportedBatchUpdateCompressors = b.SupportedBatchUpdateCompressors + x.xxx_hidden_MaxCasBlobSizeBytes = b.MaxCasBlobSizeBytes + x.xxx_hidden_SplitBlobSupport = b.SplitBlobSupport + x.xxx_hidden_SpliceBlobSupport = b.SpliceBlobSupport + x.xxx_hidden_FastCdc_2020Params = b.FastCdc_2020Params + x.xxx_hidden_RepMaxCdcParams = b.RepMaxCdcParams + return m0 +} + +// Parameters for the FastCDC content-defined chunking algorithm. +// +// Implementations MUST follow the FastCDC 2020 paper by Wen Xia, et al.: +// https://ieeexplore.ieee.org/document/9055082 +// +// Supported implementations: +// - Rust: https://docs.rs/fastcdc/3.2.1/fastcdc/v2020/index.html +// - Go: https://github.com/buildbuddy-io/fastcdc2020 +// +// Test vectors can be found in the accompanying fastcdc2020_test_vectors.txt file. +// +// Implementations MUST use normalization level 2, which has been found +// successful for build artifacts with an average chunk size of 512 KiB. +// +// Key algorithm components from the paper: +// +// GEAR table: 256 64-bit integers for the rolling hash, computed as: +// +// GEAR[i] = high_64_bits(MD5(byte(i))) for i in 0..255 +// +// MASKS table: Bit patterns for chunk boundary detection, derived from +// the C reference implementation. The mask selection based on average +// chunk size SHOULD match the paper. +// +// The minimum and maximum chunk sizes MUST be derived from the average: +// - min_chunk_size = avg_chunk_size_bytes / 4 +// - max_chunk_size = avg_chunk_size_bytes * 4 +// +// Blobs smaller than max_chunk_size (avg_chunk_size_bytes * 4) SHOULD be +// uploaded without chunking. +// +// If any of the advertised parameters are not within the expected range, +// the client SHOULD ignore FastCDC chunking function support. +type FastCdc2020Params struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_AvgChunkSizeBytes uint64 `protobuf:"varint,1,opt,name=avg_chunk_size_bytes,json=avgChunkSizeBytes,proto3"` + xxx_hidden_Seed uint32 `protobuf:"varint,2,opt,name=seed,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FastCdc2020Params) Reset() { + *x = FastCdc2020Params{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[47] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FastCdc2020Params) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FastCdc2020Params) ProtoMessage() {} + +func (x *FastCdc2020Params) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[47] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *FastCdc2020Params) GetAvgChunkSizeBytes() uint64 { + if x != nil { + return x.xxx_hidden_AvgChunkSizeBytes + } + return 0 +} + +func (x *FastCdc2020Params) GetSeed() uint32 { + if x != nil { + return x.xxx_hidden_Seed + } + return 0 +} + +func (x *FastCdc2020Params) SetAvgChunkSizeBytes(v uint64) { + x.xxx_hidden_AvgChunkSizeBytes = v +} + +func (x *FastCdc2020Params) SetSeed(v uint32) { + x.xxx_hidden_Seed = v +} + +type FastCdc2020Params_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The average (expected) chunk size for the FastCDC chunking algorithm. + // The value MUST be between 1 KiB and 1 MiB. The recommended value is + // 524288 (512 KiB). + AvgChunkSizeBytes uint64 + // The seed for the FastCDC mask generation. + // The recommended value is 0. + // + // All clients sharing a cache SHOULD use the same seed to maximize + // chunk reuse. + Seed uint32 +} + +func (b0 FastCdc2020Params_builder) Build() *FastCdc2020Params { + m0 := &FastCdc2020Params{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_AvgChunkSizeBytes = b.AvgChunkSizeBytes + x.xxx_hidden_Seed = b.Seed + return m0 +} + +// Parameters for the RepMaxCDC content-defined chunking algorithm. +// +// Supported implementations: +// - Go: https://github.com/buildbarn/go-cdc +// +// Key algorithm components: +// +// GEAR table: 256 64-bit integers for the rolling hash, computed as: +// +// GEAR[i] = high_64_bits(MD5(byte(i))) for i in 0..255 +// +// The algorithm repeatedly applies chunking until all chunks are in the +// range [min_chunk_size_bytes, 2*min_chunk_size_bytes). Cutting points are +// selected where the Gear rolling hash is maximized within a lookahead +// window of horizon_size_bytes. +// +// If any of the advertised parameters are not within the expected range, +// the client SHOULD ignore RepMaxCDC chunking function support. +type RepMaxCdcParams struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_MinChunkSizeBytes uint64 `protobuf:"varint,1,opt,name=min_chunk_size_bytes,json=minChunkSizeBytes,proto3"` + xxx_hidden_HorizonSizeBytes uint64 `protobuf:"varint,2,opt,name=horizon_size_bytes,json=horizonSizeBytes,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RepMaxCdcParams) Reset() { + *x = RepMaxCdcParams{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[48] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RepMaxCdcParams) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RepMaxCdcParams) ProtoMessage() {} + +func (x *RepMaxCdcParams) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[48] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *RepMaxCdcParams) GetMinChunkSizeBytes() uint64 { + if x != nil { + return x.xxx_hidden_MinChunkSizeBytes + } + return 0 +} + +func (x *RepMaxCdcParams) GetHorizonSizeBytes() uint64 { + if x != nil { + return x.xxx_hidden_HorizonSizeBytes + } + return 0 +} + +func (x *RepMaxCdcParams) SetMinChunkSizeBytes(v uint64) { + x.xxx_hidden_MinChunkSizeBytes = v +} + +func (x *RepMaxCdcParams) SetHorizonSizeBytes(v uint64) { + x.xxx_hidden_HorizonSizeBytes = v +} + +type RepMaxCdcParams_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The minimum chunk size for the RepMaxCDC chunking algorithm. + // The value MUST be at least 64 bytes (the Gear hash window size). + // All chunks will be in the range [min_chunk_size_bytes, 2*min_chunk_size_bytes). + // The recommended value is 262144 (256 KiB). + MinChunkSizeBytes uint64 + // The lookahead window for finding optimal cutting points. + // Larger values improve deduplication quality with diminishing returns. + // Setting to 0 produces uniform chunks of min_chunk_size_bytes. + // The recommended value is 8 * min_chunk_size_bytes. + HorizonSizeBytes uint64 +} + +func (b0 RepMaxCdcParams_builder) Build() *RepMaxCdcParams { + m0 := &RepMaxCdcParams{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_MinChunkSizeBytes = b.MinChunkSizeBytes + x.xxx_hidden_HorizonSizeBytes = b.HorizonSizeBytes + return m0 +} + +// Capabilities of the remote execution system. +type ExecutionCapabilities struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_DigestFunction DigestFunction_Value `protobuf:"varint,1,opt,name=digest_function,json=digestFunction,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + xxx_hidden_ExecEnabled bool `protobuf:"varint,2,opt,name=exec_enabled,json=execEnabled,proto3"` + xxx_hidden_ExecutionPriorityCapabilities *PriorityCapabilities `protobuf:"bytes,3,opt,name=execution_priority_capabilities,json=executionPriorityCapabilities,proto3"` + xxx_hidden_SupportedNodeProperties []string `protobuf:"bytes,4,rep,name=supported_node_properties,json=supportedNodeProperties,proto3"` + xxx_hidden_DigestFunctions []DigestFunction_Value `protobuf:"varint,5,rep,packed,name=digest_functions,json=digestFunctions,proto3,enum=build.bazel.remote.execution.v2.DigestFunction_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ExecutionCapabilities) Reset() { + *x = ExecutionCapabilities{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[49] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ExecutionCapabilities) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExecutionCapabilities) ProtoMessage() {} + +func (x *ExecutionCapabilities) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[49] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *ExecutionCapabilities) GetDigestFunction() DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunction + } + return DigestFunction_UNKNOWN +} + +func (x *ExecutionCapabilities) GetExecEnabled() bool { + if x != nil { + return x.xxx_hidden_ExecEnabled + } + return false +} + +func (x *ExecutionCapabilities) GetExecutionPriorityCapabilities() *PriorityCapabilities { + if x != nil { + return x.xxx_hidden_ExecutionPriorityCapabilities + } + return nil +} + +func (x *ExecutionCapabilities) GetSupportedNodeProperties() []string { + if x != nil { + return x.xxx_hidden_SupportedNodeProperties + } + return nil +} + +func (x *ExecutionCapabilities) GetDigestFunctions() []DigestFunction_Value { + if x != nil { + return x.xxx_hidden_DigestFunctions + } + return nil +} + +func (x *ExecutionCapabilities) SetDigestFunction(v DigestFunction_Value) { + x.xxx_hidden_DigestFunction = v +} + +func (x *ExecutionCapabilities) SetExecEnabled(v bool) { + x.xxx_hidden_ExecEnabled = v +} + +func (x *ExecutionCapabilities) SetExecutionPriorityCapabilities(v *PriorityCapabilities) { + x.xxx_hidden_ExecutionPriorityCapabilities = v +} + +func (x *ExecutionCapabilities) SetSupportedNodeProperties(v []string) { + x.xxx_hidden_SupportedNodeProperties = v +} + +func (x *ExecutionCapabilities) SetDigestFunctions(v []DigestFunction_Value) { + x.xxx_hidden_DigestFunctions = v +} + +func (x *ExecutionCapabilities) HasExecutionPriorityCapabilities() bool { + if x == nil { + return false + } + return x.xxx_hidden_ExecutionPriorityCapabilities != nil +} + +func (x *ExecutionCapabilities) ClearExecutionPriorityCapabilities() { + x.xxx_hidden_ExecutionPriorityCapabilities = nil +} + +type ExecutionCapabilities_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // Legacy field for indicating which digest function is supported by the + // remote execution system. It MUST be set to a value other than UNKNOWN. + // Implementations should consider the repeated digest_functions field + // first, falling back to this singular field if digest_functions is unset. + DigestFunction DigestFunction_Value + // Whether remote execution is enabled for the particular server/instance. + ExecEnabled bool + // Supported execution priority range. + ExecutionPriorityCapabilities *PriorityCapabilities + // Supported node properties. + SupportedNodeProperties []string + // All the digest functions supported by the remote execution system. + // If this field is set, it MUST also contain digest_function. + // + // Even if the remote execution system announces support for multiple + // digest functions, individual execution requests may only reference + // CAS objects using a single digest function. For example, it is not + // permitted to execute actions having both MD5 and SHA-256 hashed + // files in their input root. + // + // The CAS objects referenced by action results generated by the + // remote execution system MUST use the same digest function as the + // one used to construct the action. + DigestFunctions []DigestFunction_Value +} + +func (b0 ExecutionCapabilities_builder) Build() *ExecutionCapabilities { + m0 := &ExecutionCapabilities{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_DigestFunction = b.DigestFunction + x.xxx_hidden_ExecEnabled = b.ExecEnabled + x.xxx_hidden_ExecutionPriorityCapabilities = b.ExecutionPriorityCapabilities + x.xxx_hidden_SupportedNodeProperties = b.SupportedNodeProperties + x.xxx_hidden_DigestFunctions = b.DigestFunctions + return m0 +} + +// Details for the tool used to call the API. +type ToolDetails struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_ToolName string `protobuf:"bytes,1,opt,name=tool_name,json=toolName,proto3"` + xxx_hidden_ToolVersion string `protobuf:"bytes,2,opt,name=tool_version,json=toolVersion,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ToolDetails) Reset() { + *x = ToolDetails{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[50] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ToolDetails) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ToolDetails) ProtoMessage() {} + +func (x *ToolDetails) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[50] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *ToolDetails) GetToolName() string { + if x != nil { + return x.xxx_hidden_ToolName + } + return "" +} + +func (x *ToolDetails) GetToolVersion() string { + if x != nil { + return x.xxx_hidden_ToolVersion + } + return "" +} + +func (x *ToolDetails) SetToolName(v string) { + x.xxx_hidden_ToolName = v +} + +func (x *ToolDetails) SetToolVersion(v string) { + x.xxx_hidden_ToolVersion = v +} + +type ToolDetails_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // Name of the tool, e.g. bazel. + ToolName string + // Version of the tool used for the request, e.g. 5.0.3. + ToolVersion string +} + +func (b0 ToolDetails_builder) Build() *ToolDetails { + m0 := &ToolDetails{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_ToolName = b.ToolName + x.xxx_hidden_ToolVersion = b.ToolVersion + return m0 +} + +// An optional Metadata to attach to any RPC request to tell the server about an +// external context of the request. The server may use this for logging or other +// purposes. To use it, the client attaches the header to the call using the +// canonical proto serialization: +// +// * name: `build.bazel.remote.execution.v2.requestmetadata-bin` +// * contents: the base64 encoded binary `RequestMetadata` message. +// Note: the gRPC library serializes binary headers encoded in base64 by +// default (https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests). +// Therefore, if the gRPC library is used to pass/retrieve this +// metadata, the user may ignore the base64 encoding and assume it is simply +// serialized as a binary message. +type RequestMetadata struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_ToolDetails *ToolDetails `protobuf:"bytes,1,opt,name=tool_details,json=toolDetails,proto3"` + xxx_hidden_ActionId string `protobuf:"bytes,2,opt,name=action_id,json=actionId,proto3"` + xxx_hidden_ToolInvocationId string `protobuf:"bytes,3,opt,name=tool_invocation_id,json=toolInvocationId,proto3"` + xxx_hidden_CorrelatedInvocationsId string `protobuf:"bytes,4,opt,name=correlated_invocations_id,json=correlatedInvocationsId,proto3"` + xxx_hidden_ActionMnemonic string `protobuf:"bytes,5,opt,name=action_mnemonic,json=actionMnemonic,proto3"` + xxx_hidden_TargetId string `protobuf:"bytes,6,opt,name=target_id,json=targetId,proto3"` + xxx_hidden_ConfigurationId string `protobuf:"bytes,7,opt,name=configuration_id,json=configurationId,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RequestMetadata) Reset() { + *x = RequestMetadata{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[51] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RequestMetadata) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RequestMetadata) ProtoMessage() {} + +func (x *RequestMetadata) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[51] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *RequestMetadata) GetToolDetails() *ToolDetails { + if x != nil { + return x.xxx_hidden_ToolDetails + } + return nil +} + +func (x *RequestMetadata) GetActionId() string { + if x != nil { + return x.xxx_hidden_ActionId + } + return "" +} + +func (x *RequestMetadata) GetToolInvocationId() string { + if x != nil { + return x.xxx_hidden_ToolInvocationId + } + return "" +} + +func (x *RequestMetadata) GetCorrelatedInvocationsId() string { + if x != nil { + return x.xxx_hidden_CorrelatedInvocationsId + } + return "" +} + +func (x *RequestMetadata) GetActionMnemonic() string { + if x != nil { + return x.xxx_hidden_ActionMnemonic + } + return "" +} + +func (x *RequestMetadata) GetTargetId() string { + if x != nil { + return x.xxx_hidden_TargetId + } + return "" +} + +func (x *RequestMetadata) GetConfigurationId() string { + if x != nil { + return x.xxx_hidden_ConfigurationId + } + return "" +} + +func (x *RequestMetadata) SetToolDetails(v *ToolDetails) { + x.xxx_hidden_ToolDetails = v +} + +func (x *RequestMetadata) SetActionId(v string) { + x.xxx_hidden_ActionId = v +} + +func (x *RequestMetadata) SetToolInvocationId(v string) { + x.xxx_hidden_ToolInvocationId = v +} + +func (x *RequestMetadata) SetCorrelatedInvocationsId(v string) { + x.xxx_hidden_CorrelatedInvocationsId = v +} + +func (x *RequestMetadata) SetActionMnemonic(v string) { + x.xxx_hidden_ActionMnemonic = v +} + +func (x *RequestMetadata) SetTargetId(v string) { + x.xxx_hidden_TargetId = v +} + +func (x *RequestMetadata) SetConfigurationId(v string) { + x.xxx_hidden_ConfigurationId = v +} + +func (x *RequestMetadata) HasToolDetails() bool { + if x == nil { + return false + } + return x.xxx_hidden_ToolDetails != nil +} + +func (x *RequestMetadata) ClearToolDetails() { + x.xxx_hidden_ToolDetails = nil +} + +type RequestMetadata_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The details for the tool invoking the requests. + ToolDetails *ToolDetails + // An identifier that ties multiple requests to the same action. + // For example, multiple requests to the CAS, Action Cache, and Execution + // API are used in order to compile foo.cc. + ActionId string + // An identifier that ties multiple actions together to a final result. + // For example, multiple actions are required to build and run foo_test. + ToolInvocationId string + // An identifier to tie multiple tool invocations together. For example, + // runs of foo_test, bar_test and baz_test on a post-submit of a given patch. + CorrelatedInvocationsId string + // A brief description of the kind of action, for example, CppCompile or GoLink. + // There is no standard agreed set of values for this, and they are expected to vary between different client tools. + ActionMnemonic string + // An identifier for the target which produced this action. + // No guarantees are made around how many actions may relate to a single target. + TargetId string + // An identifier for the configuration in which the target was built, + // e.g. for differentiating building host tools or different target platforms. + // There is no expectation that this value will have any particular structure, + // or equality across invocations, though some client tools may offer these guarantees. + ConfigurationId string +} + +func (b0 RequestMetadata_builder) Build() *RequestMetadata { + m0 := &RequestMetadata{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_ToolDetails = b.ToolDetails + x.xxx_hidden_ActionId = b.ActionId + x.xxx_hidden_ToolInvocationId = b.ToolInvocationId + x.xxx_hidden_CorrelatedInvocationsId = b.CorrelatedInvocationsId + x.xxx_hidden_ActionMnemonic = b.ActionMnemonic + x.xxx_hidden_TargetId = b.TargetId + x.xxx_hidden_ConfigurationId = b.ConfigurationId + return m0 +} + +// An `EnvironmentVariable` is one variable to set in the running program's +// environment. +type Command_EnvironmentVariable struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Name string `protobuf:"bytes,1,opt,name=name,proto3"` + xxx_hidden_Value string `protobuf:"bytes,2,opt,name=value,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Command_EnvironmentVariable) Reset() { + *x = Command_EnvironmentVariable{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[52] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Command_EnvironmentVariable) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Command_EnvironmentVariable) ProtoMessage() {} + +func (x *Command_EnvironmentVariable) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[52] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *Command_EnvironmentVariable) GetName() string { + if x != nil { + return x.xxx_hidden_Name + } + return "" +} + +func (x *Command_EnvironmentVariable) GetValue() string { + if x != nil { + return x.xxx_hidden_Value + } + return "" +} + +func (x *Command_EnvironmentVariable) SetName(v string) { + x.xxx_hidden_Name = v +} + +func (x *Command_EnvironmentVariable) SetValue(v string) { + x.xxx_hidden_Value = v +} + +type Command_EnvironmentVariable_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The variable name. + Name string + // The variable value. + Value string +} + +func (b0 Command_EnvironmentVariable_builder) Build() *Command_EnvironmentVariable { + m0 := &Command_EnvironmentVariable{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Name = b.Name + x.xxx_hidden_Value = b.Value + return m0 +} + +// A single property for the environment. The server is responsible for +// specifying the property `name`s that it accepts. If an unknown `name` is +// provided in the requirements for an +// [Action][build.bazel.remote.execution.v2.Action], the server SHOULD +// reject the execution request. If permitted by the server, the same `name` +// may occur multiple times. +// +// The server is also responsible for specifying the interpretation of +// property `value`s. For instance, a property describing how much RAM must be +// available may be interpreted as allowing a worker with 16GB to fulfill a +// request for 8GB, while a property describing the OS environment on which +// the action must be performed may require an exact match with the worker's +// OS. +// +// The server MAY use the `value` of one or more properties to determine how +// it sets up the execution environment, such as by making specific system +// files available to the worker. +// +// Both names and values are typically case-sensitive. Note that the platform +// is implicitly part of the action digest, so even tiny changes in the names +// or values (like changing case) may result in different action cache +// entries. +type Platform_Property struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Name string `protobuf:"bytes,1,opt,name=name,proto3"` + xxx_hidden_Value string `protobuf:"bytes,2,opt,name=value,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Platform_Property) Reset() { + *x = Platform_Property{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[53] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Platform_Property) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Platform_Property) ProtoMessage() {} + +func (x *Platform_Property) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[53] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *Platform_Property) GetName() string { + if x != nil { + return x.xxx_hidden_Name + } + return "" +} + +func (x *Platform_Property) GetValue() string { + if x != nil { + return x.xxx_hidden_Value + } + return "" +} + +func (x *Platform_Property) SetName(v string) { + x.xxx_hidden_Name = v +} + +func (x *Platform_Property) SetValue(v string) { + x.xxx_hidden_Value = v +} + +type Platform_Property_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The property name. + Name string + // The property value. + Value string +} + +func (b0 Platform_Property_builder) Build() *Platform_Property { + m0 := &Platform_Property{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Name = b.Name + x.xxx_hidden_Value = b.Value + return m0 +} + +// A request corresponding to a single blob that the client wants to upload. +type BatchUpdateBlobsRequest_Request struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Digest *Digest `protobuf:"bytes,1,opt,name=digest,proto3"` + xxx_hidden_Data []byte `protobuf:"bytes,2,opt,name=data,proto3"` + xxx_hidden_Compressor Compressor_Value `protobuf:"varint,3,opt,name=compressor,proto3,enum=build.bazel.remote.execution.v2.Compressor_Value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *BatchUpdateBlobsRequest_Request) Reset() { + *x = BatchUpdateBlobsRequest_Request{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[55] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *BatchUpdateBlobsRequest_Request) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*BatchUpdateBlobsRequest_Request) ProtoMessage() {} + +func (x *BatchUpdateBlobsRequest_Request) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[55] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *BatchUpdateBlobsRequest_Request) GetDigest() *Digest { + if x != nil { + return x.xxx_hidden_Digest + } + return nil +} + +func (x *BatchUpdateBlobsRequest_Request) GetData() []byte { + if x != nil { + return x.xxx_hidden_Data + } + return nil +} + +func (x *BatchUpdateBlobsRequest_Request) GetCompressor() Compressor_Value { + if x != nil { + return x.xxx_hidden_Compressor + } + return Compressor_IDENTITY +} + +func (x *BatchUpdateBlobsRequest_Request) SetDigest(v *Digest) { + x.xxx_hidden_Digest = v +} + +func (x *BatchUpdateBlobsRequest_Request) SetData(v []byte) { + if v == nil { + v = []byte{} + } + x.xxx_hidden_Data = v +} + +func (x *BatchUpdateBlobsRequest_Request) SetCompressor(v Compressor_Value) { + x.xxx_hidden_Compressor = v +} + +func (x *BatchUpdateBlobsRequest_Request) HasDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_Digest != nil +} + +func (x *BatchUpdateBlobsRequest_Request) ClearDigest() { + x.xxx_hidden_Digest = nil +} + +type BatchUpdateBlobsRequest_Request_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The digest of the blob. This MUST be the digest of `data`. All + // digests MUST use the same digest function. + Digest *Digest + // The raw binary data. + Data []byte + // The format of `data`. Must be `IDENTITY`/unspecified, or one of the + // compressors advertised by the + // [CacheCapabilities.supported_batch_update_compressors][build.bazel.remote.execution.v2.CacheCapabilities.supported_batch_update_compressors] + // field. + Compressor Compressor_Value +} + +func (b0 BatchUpdateBlobsRequest_Request_builder) Build() *BatchUpdateBlobsRequest_Request { + m0 := &BatchUpdateBlobsRequest_Request{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Digest = b.Digest + x.xxx_hidden_Data = b.Data + x.xxx_hidden_Compressor = b.Compressor + return m0 +} + +// A response corresponding to a single blob that the client tried to upload. +type BatchUpdateBlobsResponse_Response struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Digest *Digest `protobuf:"bytes,1,opt,name=digest,proto3"` + xxx_hidden_Status *status.Status `protobuf:"bytes,2,opt,name=status,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *BatchUpdateBlobsResponse_Response) Reset() { + *x = BatchUpdateBlobsResponse_Response{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[56] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *BatchUpdateBlobsResponse_Response) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*BatchUpdateBlobsResponse_Response) ProtoMessage() {} + +func (x *BatchUpdateBlobsResponse_Response) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[56] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *BatchUpdateBlobsResponse_Response) GetDigest() *Digest { + if x != nil { + return x.xxx_hidden_Digest + } + return nil +} + +func (x *BatchUpdateBlobsResponse_Response) GetStatus() *status.Status { + if x != nil { + return x.xxx_hidden_Status + } + return nil +} + +func (x *BatchUpdateBlobsResponse_Response) SetDigest(v *Digest) { + x.xxx_hidden_Digest = v +} + +func (x *BatchUpdateBlobsResponse_Response) SetStatus(v *status.Status) { + x.xxx_hidden_Status = v +} + +func (x *BatchUpdateBlobsResponse_Response) HasDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_Digest != nil +} + +func (x *BatchUpdateBlobsResponse_Response) HasStatus() bool { + if x == nil { + return false + } + return x.xxx_hidden_Status != nil +} + +func (x *BatchUpdateBlobsResponse_Response) ClearDigest() { + x.xxx_hidden_Digest = nil +} + +func (x *BatchUpdateBlobsResponse_Response) ClearStatus() { + x.xxx_hidden_Status = nil +} + +type BatchUpdateBlobsResponse_Response_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The blob digest to which this response corresponds. + Digest *Digest + // The result of attempting to upload that blob. + Status *status.Status +} + +func (b0 BatchUpdateBlobsResponse_Response_builder) Build() *BatchUpdateBlobsResponse_Response { + m0 := &BatchUpdateBlobsResponse_Response{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Digest = b.Digest + x.xxx_hidden_Status = b.Status + return m0 +} + +// A response corresponding to a single blob that the client tried to download. +type BatchReadBlobsResponse_Response struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Digest *Digest `protobuf:"bytes,1,opt,name=digest,proto3"` + xxx_hidden_Data []byte `protobuf:"bytes,2,opt,name=data,proto3"` + xxx_hidden_Compressor Compressor_Value `protobuf:"varint,4,opt,name=compressor,proto3,enum=build.bazel.remote.execution.v2.Compressor_Value"` + xxx_hidden_Status *status.Status `protobuf:"bytes,3,opt,name=status,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *BatchReadBlobsResponse_Response) Reset() { + *x = BatchReadBlobsResponse_Response{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[57] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *BatchReadBlobsResponse_Response) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*BatchReadBlobsResponse_Response) ProtoMessage() {} + +func (x *BatchReadBlobsResponse_Response) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[57] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *BatchReadBlobsResponse_Response) GetDigest() *Digest { + if x != nil { + return x.xxx_hidden_Digest + } + return nil +} + +func (x *BatchReadBlobsResponse_Response) GetData() []byte { + if x != nil { + return x.xxx_hidden_Data + } + return nil +} + +func (x *BatchReadBlobsResponse_Response) GetCompressor() Compressor_Value { + if x != nil { + return x.xxx_hidden_Compressor + } + return Compressor_IDENTITY +} + +func (x *BatchReadBlobsResponse_Response) GetStatus() *status.Status { + if x != nil { + return x.xxx_hidden_Status + } + return nil +} + +func (x *BatchReadBlobsResponse_Response) SetDigest(v *Digest) { + x.xxx_hidden_Digest = v +} + +func (x *BatchReadBlobsResponse_Response) SetData(v []byte) { + if v == nil { + v = []byte{} + } + x.xxx_hidden_Data = v +} + +func (x *BatchReadBlobsResponse_Response) SetCompressor(v Compressor_Value) { + x.xxx_hidden_Compressor = v +} + +func (x *BatchReadBlobsResponse_Response) SetStatus(v *status.Status) { + x.xxx_hidden_Status = v +} + +func (x *BatchReadBlobsResponse_Response) HasDigest() bool { + if x == nil { + return false + } + return x.xxx_hidden_Digest != nil +} + +func (x *BatchReadBlobsResponse_Response) HasStatus() bool { + if x == nil { + return false + } + return x.xxx_hidden_Status != nil +} + +func (x *BatchReadBlobsResponse_Response) ClearDigest() { + x.xxx_hidden_Digest = nil +} + +func (x *BatchReadBlobsResponse_Response) ClearStatus() { + x.xxx_hidden_Status = nil +} + +type BatchReadBlobsResponse_Response_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The digest to which this response corresponds. + Digest *Digest + // The raw binary data. + Data []byte + // The format the data is encoded in. MUST be `IDENTITY`/unspecified, + // or one of the acceptable compressors specified in the `BatchReadBlobsRequest`. + Compressor Compressor_Value + // The result of attempting to download that blob. + Status *status.Status +} + +func (b0 BatchReadBlobsResponse_Response_builder) Build() *BatchReadBlobsResponse_Response { + m0 := &BatchReadBlobsResponse_Response{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Digest = b.Digest + x.xxx_hidden_Data = b.Data + x.xxx_hidden_Compressor = b.Compressor + x.xxx_hidden_Status = b.Status + return m0 +} + +// Supported range of priorities, including boundaries. +type PriorityCapabilities_PriorityRange struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_MinPriority int32 `protobuf:"varint,1,opt,name=min_priority,json=minPriority,proto3"` + xxx_hidden_MaxPriority int32 `protobuf:"varint,2,opt,name=max_priority,json=maxPriority,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PriorityCapabilities_PriorityRange) Reset() { + *x = PriorityCapabilities_PriorityRange{} + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[58] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PriorityCapabilities_PriorityRange) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PriorityCapabilities_PriorityRange) ProtoMessage() {} + +func (x *PriorityCapabilities_PriorityRange) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes[58] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *PriorityCapabilities_PriorityRange) GetMinPriority() int32 { + if x != nil { + return x.xxx_hidden_MinPriority + } + return 0 +} + +func (x *PriorityCapabilities_PriorityRange) GetMaxPriority() int32 { + if x != nil { + return x.xxx_hidden_MaxPriority + } + return 0 +} + +func (x *PriorityCapabilities_PriorityRange) SetMinPriority(v int32) { + x.xxx_hidden_MinPriority = v +} + +func (x *PriorityCapabilities_PriorityRange) SetMaxPriority(v int32) { + x.xxx_hidden_MaxPriority = v +} + +type PriorityCapabilities_PriorityRange_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The minimum numeric value for this priority range, which represents the + // most urgent task or longest retained item. + MinPriority int32 + // The maximum numeric value for this priority range, which represents the + // least urgent task or shortest retained item. + MaxPriority int32 +} + +func (b0 PriorityCapabilities_PriorityRange_builder) Build() *PriorityCapabilities_PriorityRange { + m0 := &PriorityCapabilities_PriorityRange{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_MinPriority = b.MinPriority + x.xxx_hidden_MaxPriority = b.MaxPriority + return m0 +} + +var File_build_bazel_remote_execution_v2_remote_execution_proto protoreflect.FileDescriptor + +const file_build_bazel_remote_execution_v2_remote_execution_proto_rawDesc = "" + + "\n" + + "6build/bazel/remote/execution/v2/remote_execution.proto\x12\x1fbuild.bazel.remote.execution.v2\x1a\x1fbuild/bazel/semver/semver.proto\x1a\x1cgoogle/api/annotations.proto\x1a#google/longrunning/operations.proto\x1a\x19google/protobuf/any.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/wrappers.proto\x1a\x17google/rpc/status.proto\"\xeb\x02\n" + + "\x06Action\x12N\n" + + "\x0ecommand_digest\x18\x01 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\rcommandDigest\x12S\n" + + "\x11input_root_digest\x18\x02 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\x0finputRootDigest\x123\n" + + "\atimeout\x18\x06 \x01(\v2\x19.google.protobuf.DurationR\atimeout\x12 \n" + + "\fdo_not_cache\x18\a \x01(\bR\n" + + "doNotCache\x12\x12\n" + + "\x04salt\x18\t \x01(\fR\x04salt\x12E\n" + + "\bplatform\x18\n" + + " \x01(\v2).build.bazel.remote.execution.v2.PlatformR\bplatformJ\x04\b\x03\x10\x06J\x04\b\b\x10\t\"\xd2\x05\n" + + "\aCommand\x12\x1c\n" + + "\targuments\x18\x01 \x03(\tR\targuments\x12q\n" + + "\x15environment_variables\x18\x02 \x03(\v2<.build.bazel.remote.execution.v2.Command.EnvironmentVariableR\x14environmentVariables\x12%\n" + + "\foutput_files\x18\x03 \x03(\tB\x02\x18\x01R\voutputFiles\x121\n" + + "\x12output_directories\x18\x04 \x03(\tB\x02\x18\x01R\x11outputDirectories\x12!\n" + + "\foutput_paths\x18\a \x03(\tR\voutputPaths\x12I\n" + + "\bplatform\x18\x05 \x01(\v2).build.bazel.remote.execution.v2.PlatformB\x02\x18\x01R\bplatform\x12+\n" + + "\x11working_directory\x18\x06 \x01(\tR\x10workingDirectory\x124\n" + + "\x16output_node_properties\x18\b \x03(\tR\x14outputNodeProperties\x12v\n" + + "\x17output_directory_format\x18\t \x01(\x0e2>.build.bazel.remote.execution.v2.Command.OutputDirectoryFormatR\x15outputDirectoryFormat\x1a?\n" + + "\x13EnvironmentVariable\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" + + "\x05value\x18\x02 \x01(\tR\x05value\"R\n" + + "\x15OutputDirectoryFormat\x12\r\n" + + "\tTREE_ONLY\x10\x00\x12\x12\n" + + "\x0eDIRECTORY_ONLY\x10\x01\x12\x16\n" + + "\x12TREE_AND_DIRECTORY\x10\x02\"\x94\x01\n" + + "\bPlatform\x12R\n" + + "\n" + + "properties\x18\x01 \x03(\v22.build.bazel.remote.execution.v2.Platform.PropertyR\n" + + "properties\x1a4\n" + + "\bProperty\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" + + "\x05value\x18\x02 \x01(\tR\x05value\"\xc8\x02\n" + + "\tDirectory\x12?\n" + + "\x05files\x18\x01 \x03(\v2).build.bazel.remote.execution.v2.FileNodeR\x05files\x12P\n" + + "\vdirectories\x18\x02 \x03(\v2..build.bazel.remote.execution.v2.DirectoryNodeR\vdirectories\x12H\n" + + "\bsymlinks\x18\x03 \x03(\v2,.build.bazel.remote.execution.v2.SymlinkNodeR\bsymlinks\x12X\n" + + "\x0fnode_properties\x18\x05 \x01(\v2/.build.bazel.remote.execution.v2.NodePropertiesR\x0enodePropertiesJ\x04\b\x04\x10\x05\"8\n" + + "\fNodeProperty\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" + + "\x05value\x18\x02 \x01(\tR\x05value\"\xcc\x01\n" + + "\x0eNodeProperties\x12M\n" + + "\n" + + "properties\x18\x01 \x03(\v2-.build.bazel.remote.execution.v2.NodePropertyR\n" + + "properties\x120\n" + + "\x05mtime\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x05mtime\x129\n" + + "\tunix_mode\x18\x03 \x01(\v2\x1c.google.protobuf.UInt32ValueR\bunixMode\"\xea\x01\n" + + "\bFileNode\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12?\n" + + "\x06digest\x18\x02 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\x06digest\x12#\n" + + "\ris_executable\x18\x04 \x01(\bR\fisExecutable\x12X\n" + + "\x0fnode_properties\x18\x06 \x01(\v2/.build.bazel.remote.execution.v2.NodePropertiesR\x0enodePropertiesJ\x04\b\x03\x10\x04J\x04\b\x05\x10\x06\"d\n" + + "\rDirectoryNode\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12?\n" + + "\x06digest\x18\x02 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\x06digest\"\x99\x01\n" + + "\vSymlinkNode\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12\x16\n" + + "\x06target\x18\x02 \x01(\tR\x06target\x12X\n" + + "\x0fnode_properties\x18\x04 \x01(\v2/.build.bazel.remote.execution.v2.NodePropertiesR\x0enodePropertiesJ\x04\b\x03\x10\x04\";\n" + + "\x06Digest\x12\x12\n" + + "\x04hash\x18\x01 \x01(\tR\x04hash\x12\x1d\n" + + "\n" + + "size_bytes\x18\x02 \x01(\x03R\tsizeBytes\"\xfd\a\n" + + "\x16ExecutedActionMetadata\x12\x16\n" + + "\x06worker\x18\x01 \x01(\tR\x06worker\x12E\n" + + "\x10queued_timestamp\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x0fqueuedTimestamp\x12P\n" + + "\x16worker_start_timestamp\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\x14workerStartTimestamp\x12X\n" + + "\x1aworker_completed_timestamp\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\x18workerCompletedTimestamp\x12Y\n" + + "\x1binput_fetch_start_timestamp\x18\x05 \x01(\v2\x1a.google.protobuf.TimestampR\x18inputFetchStartTimestamp\x12a\n" + + "\x1finput_fetch_completed_timestamp\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\x1cinputFetchCompletedTimestamp\x12V\n" + + "\x19execution_start_timestamp\x18\a \x01(\v2\x1a.google.protobuf.TimestampR\x17executionStartTimestamp\x12^\n" + + "\x1dexecution_completed_timestamp\x18\b \x01(\v2\x1a.google.protobuf.TimestampR\x1bexecutionCompletedTimestamp\x12W\n" + + "\x1avirtual_execution_duration\x18\f \x01(\v2\x19.google.protobuf.DurationR\x18virtualExecutionDuration\x12]\n" + + "\x1doutput_upload_start_timestamp\x18\t \x01(\v2\x1a.google.protobuf.TimestampR\x1aoutputUploadStartTimestamp\x12e\n" + + "!output_upload_completed_timestamp\x18\n" + + " \x01(\v2\x1a.google.protobuf.TimestampR\x1eoutputUploadCompletedTimestamp\x12C\n" + + "\x12auxiliary_metadata\x18\v \x03(\v2\x14.google.protobuf.AnyR\x11auxiliaryMetadata\"\xd3\x06\n" + + "\fActionResult\x12N\n" + + "\foutput_files\x18\x02 \x03(\v2+.build.bazel.remote.execution.v2.OutputFileR\voutputFiles\x12d\n" + + "\x14output_file_symlinks\x18\n" + + " \x03(\v2..build.bazel.remote.execution.v2.OutputSymlinkB\x02\x18\x01R\x12outputFileSymlinks\x12W\n" + + "\x0foutput_symlinks\x18\f \x03(\v2..build.bazel.remote.execution.v2.OutputSymlinkR\x0eoutputSymlinks\x12_\n" + + "\x12output_directories\x18\x03 \x03(\v20.build.bazel.remote.execution.v2.OutputDirectoryR\x11outputDirectories\x12n\n" + + "\x19output_directory_symlinks\x18\v \x03(\v2..build.bazel.remote.execution.v2.OutputSymlinkB\x02\x18\x01R\x17outputDirectorySymlinks\x12\x1b\n" + + "\texit_code\x18\x04 \x01(\x05R\bexitCode\x12\x1d\n" + + "\n" + + "stdout_raw\x18\x05 \x01(\fR\tstdoutRaw\x12L\n" + + "\rstdout_digest\x18\x06 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\fstdoutDigest\x12\x1d\n" + + "\n" + + "stderr_raw\x18\a \x01(\fR\tstderrRaw\x12L\n" + + "\rstderr_digest\x18\b \x01(\v2'.build.bazel.remote.execution.v2.DigestR\fstderrDigest\x12f\n" + + "\x12execution_metadata\x18\t \x01(\v27.build.bazel.remote.execution.v2.ExecutedActionMetadataR\x11executionMetadataJ\x04\b\x01\x10\x02\"\x88\x02\n" + + "\n" + + "OutputFile\x12\x12\n" + + "\x04path\x18\x01 \x01(\tR\x04path\x12?\n" + + "\x06digest\x18\x02 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\x06digest\x12#\n" + + "\ris_executable\x18\x04 \x01(\bR\fisExecutable\x12\x1a\n" + + "\bcontents\x18\x05 \x01(\fR\bcontents\x12X\n" + + "\x0fnode_properties\x18\a \x01(\v2/.build.bazel.remote.execution.v2.NodePropertiesR\x0enodePropertiesJ\x04\b\x03\x10\x04J\x04\b\x06\x10\a\"\x8e\x01\n" + + "\x04Tree\x12>\n" + + "\x04root\x18\x01 \x01(\v2*.build.bazel.remote.execution.v2.DirectoryR\x04root\x12F\n" + + "\bchildren\x18\x02 \x03(\v2*.build.bazel.remote.execution.v2.DirectoryR\bchildren\"\x8a\x02\n" + + "\x0fOutputDirectory\x12\x12\n" + + "\x04path\x18\x01 \x01(\tR\x04path\x12H\n" + + "\vtree_digest\x18\x03 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\n" + + "treeDigest\x126\n" + + "\x17is_topologically_sorted\x18\x04 \x01(\bR\x15isTopologicallySorted\x12[\n" + + "\x15root_directory_digest\x18\x05 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\x13rootDirectoryDigestJ\x04\b\x02\x10\x03\"\x9b\x01\n" + + "\rOutputSymlink\x12\x12\n" + + "\x04path\x18\x01 \x01(\tR\x04path\x12\x16\n" + + "\x06target\x18\x02 \x01(\tR\x06target\x12X\n" + + "\x0fnode_properties\x18\x04 \x01(\v2/.build.bazel.remote.execution.v2.NodePropertiesR\x0enodePropertiesJ\x04\b\x03\x10\x04\"-\n" + + "\x0fExecutionPolicy\x12\x1a\n" + + "\bpriority\x18\x01 \x01(\x05R\bpriority\"0\n" + + "\x12ResultsCachePolicy\x12\x1a\n" + + "\bpriority\x18\x01 \x01(\x05R\bpriority\"\xdf\x04\n" + + "\x0eExecuteRequest\x12#\n" + + "\rinstance_name\x18\x01 \x01(\tR\finstanceName\x12*\n" + + "\x11skip_cache_lookup\x18\x03 \x01(\bR\x0fskipCacheLookup\x12L\n" + + "\raction_digest\x18\x06 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\factionDigest\x12[\n" + + "\x10execution_policy\x18\a \x01(\v20.build.bazel.remote.execution.v2.ExecutionPolicyR\x0fexecutionPolicy\x12e\n" + + "\x14results_cache_policy\x18\b \x01(\v23.build.bazel.remote.execution.v2.ResultsCachePolicyR\x12resultsCachePolicy\x12^\n" + + "\x0fdigest_function\x18\t \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\x12#\n" + + "\rinline_stdout\x18\n" + + " \x01(\bR\finlineStdout\x12#\n" + + "\rinline_stderr\x18\v \x01(\bR\finlineStderr\x12.\n" + + "\x13inline_output_files\x18\f \x03(\tR\x11inlineOutputFilesJ\x04\b\x02\x10\x03J\x04\b\x04\x10\x05J\x04\b\x05\x10\x06\"q\n" + + "\aLogFile\x12?\n" + + "\x06digest\x18\x01 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\x06digest\x12%\n" + + "\x0ehuman_readable\x18\x02 \x01(\bR\rhumanReadable\"\x8f\x03\n" + + "\x0fExecuteResponse\x12E\n" + + "\x06result\x18\x01 \x01(\v2-.build.bazel.remote.execution.v2.ActionResultR\x06result\x12#\n" + + "\rcached_result\x18\x02 \x01(\bR\fcachedResult\x12*\n" + + "\x06status\x18\x03 \x01(\v2\x12.google.rpc.StatusR\x06status\x12a\n" + + "\vserver_logs\x18\x04 \x03(\v2@.build.bazel.remote.execution.v2.ExecuteResponse.ServerLogsEntryR\n" + + "serverLogs\x12\x18\n" + + "\amessage\x18\x05 \x01(\tR\amessage\x1ag\n" + + "\x0fServerLogsEntry\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12>\n" + + "\x05value\x18\x02 \x01(\v2(.build.bazel.remote.execution.v2.LogFileR\x05value:\x028\x01\"a\n" + + "\x0eExecutionStage\"O\n" + + "\x05Value\x12\v\n" + + "\aUNKNOWN\x10\x00\x12\x0f\n" + + "\vCACHE_CHECK\x10\x01\x12\n" + + "\n" + + "\x06QUEUED\x10\x02\x12\r\n" + + "\tEXECUTING\x10\x03\x12\r\n" + + "\tCOMPLETED\x10\x04\"\xe8\x03\n" + + "\x18ExecuteOperationMetadata\x12K\n" + + "\x05stage\x18\x01 \x01(\x0e25.build.bazel.remote.execution.v2.ExecutionStage.ValueR\x05stage\x12L\n" + + "\raction_digest\x18\x02 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\factionDigest\x12,\n" + + "\x12stdout_stream_name\x18\x03 \x01(\tR\x10stdoutStreamName\x12,\n" + + "\x12stderr_stream_name\x18\x04 \x01(\tR\x10stderrStreamName\x12u\n" + + "\x1apartial_execution_metadata\x18\x05 \x01(\v27.build.bazel.remote.execution.v2.ExecutedActionMetadataR\x18partialExecutionMetadata\x12^\n" + + "\x0fdigest_function\x18\x06 \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\"*\n" + + "\x14WaitExecutionRequest\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\"\xe5\x02\n" + + "\x16GetActionResultRequest\x12#\n" + + "\rinstance_name\x18\x01 \x01(\tR\finstanceName\x12L\n" + + "\raction_digest\x18\x02 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\factionDigest\x12#\n" + + "\rinline_stdout\x18\x03 \x01(\bR\finlineStdout\x12#\n" + + "\rinline_stderr\x18\x04 \x01(\bR\finlineStderr\x12.\n" + + "\x13inline_output_files\x18\x05 \x03(\tR\x11inlineOutputFiles\x12^\n" + + "\x0fdigest_function\x18\x06 \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\"\xa9\x03\n" + + "\x19UpdateActionResultRequest\x12#\n" + + "\rinstance_name\x18\x01 \x01(\tR\finstanceName\x12L\n" + + "\raction_digest\x18\x02 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\factionDigest\x12R\n" + + "\raction_result\x18\x03 \x01(\v2-.build.bazel.remote.execution.v2.ActionResultR\factionResult\x12e\n" + + "\x14results_cache_policy\x18\x04 \x01(\v23.build.bazel.remote.execution.v2.ResultsCachePolicyR\x12resultsCachePolicy\x12^\n" + + "\x0fdigest_function\x18\x05 \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\"\xea\x01\n" + + "\x17FindMissingBlobsRequest\x12#\n" + + "\rinstance_name\x18\x01 \x01(\tR\finstanceName\x12J\n" + + "\fblob_digests\x18\x02 \x03(\v2'.build.bazel.remote.execution.v2.DigestR\vblobDigests\x12^\n" + + "\x0fdigest_function\x18\x03 \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\"u\n" + + "\x18FindMissingBlobsResponse\x12Y\n" + + "\x14missing_blob_digests\x18\x02 \x03(\v2'.build.bazel.remote.execution.v2.DigestR\x12missingBlobDigests\"\xb0\x03\n" + + "\x17BatchUpdateBlobsRequest\x12#\n" + + "\rinstance_name\x18\x01 \x01(\tR\finstanceName\x12\\\n" + + "\brequests\x18\x02 \x03(\v2@.build.bazel.remote.execution.v2.BatchUpdateBlobsRequest.RequestR\brequests\x12^\n" + + "\x0fdigest_function\x18\x05 \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\x1a\xb1\x01\n" + + "\aRequest\x12?\n" + + "\x06digest\x18\x01 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\x06digest\x12\x12\n" + + "\x04data\x18\x02 \x01(\fR\x04data\x12Q\n" + + "\n" + + "compressor\x18\x03 \x01(\x0e21.build.bazel.remote.execution.v2.Compressor.ValueR\n" + + "compressor\"\xf5\x01\n" + + "\x18BatchUpdateBlobsResponse\x12`\n" + + "\tresponses\x18\x01 \x03(\v2B.build.bazel.remote.execution.v2.BatchUpdateBlobsResponse.ResponseR\tresponses\x1aw\n" + + "\bResponse\x12?\n" + + "\x06digest\x18\x01 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\x06digest\x12*\n" + + "\x06status\x18\x02 \x01(\v2\x12.google.rpc.StatusR\x06status\"\xc9\x02\n" + + "\x15BatchReadBlobsRequest\x12#\n" + + "\rinstance_name\x18\x01 \x01(\tR\finstanceName\x12A\n" + + "\adigests\x18\x02 \x03(\v2'.build.bazel.remote.execution.v2.DigestR\adigests\x12h\n" + + "\x16acceptable_compressors\x18\x03 \x03(\x0e21.build.bazel.remote.execution.v2.Compressor.ValueR\x15acceptableCompressors\x12^\n" + + "\x0fdigest_function\x18\x04 \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\"\xd9\x02\n" + + "\x16BatchReadBlobsResponse\x12^\n" + + "\tresponses\x18\x01 \x03(\v2@.build.bazel.remote.execution.v2.BatchReadBlobsResponse.ResponseR\tresponses\x1a\xde\x01\n" + + "\bResponse\x12?\n" + + "\x06digest\x18\x01 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\x06digest\x12\x12\n" + + "\x04data\x18\x02 \x01(\fR\x04data\x12Q\n" + + "\n" + + "compressor\x18\x04 \x01(\x0e21.build.bazel.remote.execution.v2.Compressor.ValueR\n" + + "compressor\x12*\n" + + "\x06status\x18\x03 \x01(\v2\x12.google.rpc.StatusR\x06status\"\x9b\x02\n" + + "\x0eGetTreeRequest\x12#\n" + + "\rinstance_name\x18\x01 \x01(\tR\finstanceName\x12H\n" + + "\vroot_digest\x18\x02 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\n" + + "rootDigest\x12\x1b\n" + + "\tpage_size\x18\x03 \x01(\x05R\bpageSize\x12\x1d\n" + + "\n" + + "page_token\x18\x04 \x01(\tR\tpageToken\x12^\n" + + "\x0fdigest_function\x18\x05 \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\"\x87\x01\n" + + "\x0fGetTreeResponse\x12L\n" + + "\vdirectories\x18\x01 \x03(\v2*.build.bazel.remote.execution.v2.DirectoryR\vdirectories\x12&\n" + + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\xc7\x02\n" + + "\x10SplitBlobRequest\x12#\n" + + "\rinstance_name\x18\x01 \x01(\tR\finstanceName\x12H\n" + + "\vblob_digest\x18\x02 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\n" + + "blobDigest\x12^\n" + + "\x0fdigest_function\x18\x03 \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\x12d\n" + + "\x11chunking_function\x18\x04 \x01(\x0e27.build.bazel.remote.execution.v2.ChunkingFunction.ValueR\x10chunkingFunction\"\xc7\x01\n" + + "\x11SplitBlobResponse\x12L\n" + + "\rchunk_digests\x18\x01 \x03(\v2'.build.bazel.remote.execution.v2.DigestR\fchunkDigests\x12d\n" + + "\x11chunking_function\x18\x02 \x01(\x0e27.build.bazel.remote.execution.v2.ChunkingFunction.ValueR\x10chunkingFunction\"\x96\x03\n" + + "\x11SpliceBlobRequest\x12#\n" + + "\rinstance_name\x18\x01 \x01(\tR\finstanceName\x12H\n" + + "\vblob_digest\x18\x02 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\n" + + "blobDigest\x12L\n" + + "\rchunk_digests\x18\x03 \x03(\v2'.build.bazel.remote.execution.v2.DigestR\fchunkDigests\x12^\n" + + "\x0fdigest_function\x18\x04 \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\x12d\n" + + "\x11chunking_function\x18\x05 \x01(\x0e27.build.bazel.remote.execution.v2.ChunkingFunction.ValueR\x10chunkingFunction\"^\n" + + "\x12SpliceBlobResponse\x12H\n" + + "\vblob_digest\x18\x01 \x01(\v2'.build.bazel.remote.execution.v2.DigestR\n" + + "blobDigest\"=\n" + + "\x16GetCapabilitiesRequest\x12#\n" + + "\rinstance_name\x18\x01 \x01(\tR\finstanceName\"\xc2\x03\n" + + "\x12ServerCapabilities\x12a\n" + + "\x12cache_capabilities\x18\x01 \x01(\v22.build.bazel.remote.execution.v2.CacheCapabilitiesR\x11cacheCapabilities\x12m\n" + + "\x16execution_capabilities\x18\x02 \x01(\v26.build.bazel.remote.execution.v2.ExecutionCapabilitiesR\x15executionCapabilities\x12P\n" + + "\x16deprecated_api_version\x18\x03 \x01(\v2\x1a.build.bazel.semver.SemVerR\x14deprecatedApiVersion\x12B\n" + + "\x0flow_api_version\x18\x04 \x01(\v2\x1a.build.bazel.semver.SemVerR\rlowApiVersion\x12D\n" + + "\x10high_api_version\x18\x05 \x01(\v2\x1a.build.bazel.semver.SemVerR\x0ehighApiVersion\"\x9d\x01\n" + + "\x0eDigestFunction\"\x8a\x01\n" + + "\x05Value\x12\v\n" + + "\aUNKNOWN\x10\x00\x12\n" + + "\n" + + "\x06SHA256\x10\x01\x12\b\n" + + "\x04SHA1\x10\x02\x12\a\n" + + "\x03MD5\x10\x03\x12\a\n" + + "\x03VSO\x10\x04\x12\n" + + "\n" + + "\x06SHA384\x10\x05\x12\n" + + "\n" + + "\x06SHA512\x10\x06\x12\v\n" + + "\aMURMUR3\x10\a\x12\x0e\n" + + "\n" + + "SHA256TREE\x10\b\x12\n" + + "\n" + + "\x06BLAKE3\x10\t\x12\v\n" + + "\aGITSHA1\x10\n" + + "\"L\n" + + "\x10ChunkingFunction\"8\n" + + "\x05Value\x12\v\n" + + "\aUNKNOWN\x10\x00\x12\x11\n" + + "\rFAST_CDC_2020\x10\x01\x12\x0f\n" + + "\vREP_MAX_CDC\x10\x02\"F\n" + + "\x1dActionCacheUpdateCapabilities\x12%\n" + + "\x0eupdate_enabled\x18\x01 \x01(\bR\rupdateEnabled\"\xd2\x01\n" + + "\x14PriorityCapabilities\x12c\n" + + "\n" + + "priorities\x18\x01 \x03(\v2C.build.bazel.remote.execution.v2.PriorityCapabilities.PriorityRangeR\n" + + "priorities\x1aU\n" + + "\rPriorityRange\x12!\n" + + "\fmin_priority\x18\x01 \x01(\x05R\vminPriority\x12!\n" + + "\fmax_priority\x18\x02 \x01(\x05R\vmaxPriority\"P\n" + + "\x1bSymlinkAbsolutePathStrategy\"1\n" + + "\x05Value\x12\v\n" + + "\aUNKNOWN\x10\x00\x12\x0e\n" + + "\n" + + "DISALLOWED\x10\x01\x12\v\n" + + "\aALLOWED\x10\x02\"F\n" + + "\n" + + "Compressor\"8\n" + + "\x05Value\x12\f\n" + + "\bIDENTITY\x10\x00\x12\b\n" + + "\x04ZSTD\x10\x01\x12\v\n" + + "\aDEFLATE\x10\x02\x12\n" + + "\n" + + "\x06BROTLI\x10\x03\"\xfc\b\n" + + "\x11CacheCapabilities\x12`\n" + + "\x10digest_functions\x18\x01 \x03(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0fdigestFunctions\x12\x87\x01\n" + + " action_cache_update_capabilities\x18\x02 \x01(\v2>.build.bazel.remote.execution.v2.ActionCacheUpdateCapabilitiesR\x1dactionCacheUpdateCapabilities\x12u\n" + + "\x1bcache_priority_capabilities\x18\x03 \x01(\v25.build.bazel.remote.execution.v2.PriorityCapabilitiesR\x19cachePriorityCapabilities\x12:\n" + + "\x1amax_batch_total_size_bytes\x18\x04 \x01(\x03R\x16maxBatchTotalSizeBytes\x12\x87\x01\n" + + "\x1esymlink_absolute_path_strategy\x18\x05 \x01(\x0e2B.build.bazel.remote.execution.v2.SymlinkAbsolutePathStrategy.ValueR\x1bsymlinkAbsolutePathStrategy\x12f\n" + + "\x15supported_compressors\x18\x06 \x03(\x0e21.build.bazel.remote.execution.v2.Compressor.ValueR\x14supportedCompressors\x12~\n" + + "\"supported_batch_update_compressors\x18\a \x03(\x0e21.build.bazel.remote.execution.v2.Compressor.ValueR\x1fsupportedBatchUpdateCompressors\x124\n" + + "\x17max_cas_blob_size_bytes\x18\b \x01(\x03R\x13maxCasBlobSizeBytes\x12,\n" + + "\x12split_blob_support\x18\t \x01(\bR\x10splitBlobSupport\x12.\n" + + "\x13splice_blob_support\x18\n" + + " \x01(\bR\x11spliceBlobSupport\x12c\n" + + "\x14fast_cdc_2020_params\x18\v \x01(\v22.build.bazel.remote.execution.v2.FastCdc2020ParamsR\x11fastCdc2020Params\x12]\n" + + "\x12rep_max_cdc_params\x18\f \x01(\v20.build.bazel.remote.execution.v2.RepMaxCdcParamsR\x0frepMaxCdcParams\"X\n" + + "\x11FastCdc2020Params\x12/\n" + + "\x14avg_chunk_size_bytes\x18\x01 \x01(\x04R\x11avgChunkSizeBytes\x12\x12\n" + + "\x04seed\x18\x02 \x01(\rR\x04seed\"p\n" + + "\x0fRepMaxCdcParams\x12/\n" + + "\x14min_chunk_size_bytes\x18\x01 \x01(\x04R\x11minChunkSizeBytes\x12,\n" + + "\x12horizon_size_bytes\x18\x02 \x01(\x04R\x10horizonSizeBytes\"\xb7\x03\n" + + "\x15ExecutionCapabilities\x12^\n" + + "\x0fdigest_function\x18\x01 \x01(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0edigestFunction\x12!\n" + + "\fexec_enabled\x18\x02 \x01(\bR\vexecEnabled\x12}\n" + + "\x1fexecution_priority_capabilities\x18\x03 \x01(\v25.build.bazel.remote.execution.v2.PriorityCapabilitiesR\x1dexecutionPriorityCapabilities\x12:\n" + + "\x19supported_node_properties\x18\x04 \x03(\tR\x17supportedNodeProperties\x12`\n" + + "\x10digest_functions\x18\x05 \x03(\x0e25.build.bazel.remote.execution.v2.DigestFunction.ValueR\x0fdigestFunctions\"M\n" + + "\vToolDetails\x12\x1b\n" + + "\ttool_name\x18\x01 \x01(\tR\btoolName\x12!\n" + + "\ftool_version\x18\x02 \x01(\tR\vtoolVersion\"\xda\x02\n" + + "\x0fRequestMetadata\x12O\n" + + "\ftool_details\x18\x01 \x01(\v2,.build.bazel.remote.execution.v2.ToolDetailsR\vtoolDetails\x12\x1b\n" + + "\taction_id\x18\x02 \x01(\tR\bactionId\x12,\n" + + "\x12tool_invocation_id\x18\x03 \x01(\tR\x10toolInvocationId\x12:\n" + + "\x19correlated_invocations_id\x18\x04 \x01(\tR\x17correlatedInvocationsId\x12'\n" + + "\x0faction_mnemonic\x18\x05 \x01(\tR\x0eactionMnemonic\x12\x1b\n" + + "\ttarget_id\x18\x06 \x01(\tR\btargetId\x12)\n" + + "\x10configuration_id\x18\a \x01(\tR\x0fconfigurationId2\xb9\x02\n" + + "\tExecution\x12\x8e\x01\n" + + "\aExecute\x12/.build.bazel.remote.execution.v2.ExecuteRequest\x1a\x1d.google.longrunning.Operation\"1\x82\xd3\xe4\x93\x02+:\x01*\"&/v2/{instance_name=**}/actions:execute0\x01\x12\x9a\x01\n" + + "\rWaitExecution\x125.build.bazel.remote.execution.v2.WaitExecutionRequest\x1a\x1d.google.longrunning.Operation\"1\x82\xd3\xe4\x93\x02+:\x01*\"&/v2/{name=operations/**}:waitExecution0\x012\xd6\x03\n" + + "\vActionCache\x12\xd7\x01\n" + + "\x0fGetActionResult\x127.build.bazel.remote.execution.v2.GetActionResultRequest\x1a-.build.bazel.remote.execution.v2.ActionResult\"\\\x82\xd3\xe4\x93\x02V\x12T/v2/{instance_name=**}/actionResults/{action_digest.hash}/{action_digest.size_bytes}\x12\xec\x01\n" + + "\x12UpdateActionResult\x12:.build.bazel.remote.execution.v2.UpdateActionResultRequest\x1a-.build.bazel.remote.execution.v2.ActionResult\"k\x82\xd3\xe4\x93\x02e:\raction_result\x1aT/v2/{instance_name=**}/actionResults/{action_digest.hash}/{action_digest.size_bytes}2\x98\t\n" + + "\x19ContentAddressableStorage\x12\xbc\x01\n" + + "\x10FindMissingBlobs\x128.build.bazel.remote.execution.v2.FindMissingBlobsRequest\x1a9.build.bazel.remote.execution.v2.FindMissingBlobsResponse\"3\x82\xd3\xe4\x93\x02-:\x01*\"(/v2/{instance_name=**}/blobs:findMissing\x12\xbc\x01\n" + + "\x10BatchUpdateBlobs\x128.build.bazel.remote.execution.v2.BatchUpdateBlobsRequest\x1a9.build.bazel.remote.execution.v2.BatchUpdateBlobsResponse\"3\x82\xd3\xe4\x93\x02-:\x01*\"(/v2/{instance_name=**}/blobs:batchUpdate\x12\xb4\x01\n" + + "\x0eBatchReadBlobs\x126.build.bazel.remote.execution.v2.BatchReadBlobsRequest\x1a7.build.bazel.remote.execution.v2.BatchReadBlobsResponse\"1\x82\xd3\xe4\x93\x02+:\x01*\"&/v2/{instance_name=**}/blobs:batchRead\x12\xc8\x01\n" + + "\aGetTree\x12/.build.bazel.remote.execution.v2.GetTreeRequest\x1a0.build.bazel.remote.execution.v2.GetTreeResponse\"X\x82\xd3\xe4\x93\x02R\x12P/v2/{instance_name=**}/blobs/{root_digest.hash}/{root_digest.size_bytes}:getTree0\x01\x12\xce\x01\n" + + "\tSplitBlob\x121.build.bazel.remote.execution.v2.SplitBlobRequest\x1a2.build.bazel.remote.execution.v2.SplitBlobResponse\"Z\x82\xd3\xe4\x93\x02T\x12R/v2/{instance_name=**}/blobs/{blob_digest.hash}/{blob_digest.size_bytes}:splitBlob\x12\xa9\x01\n" + + "\n" + + "SpliceBlob\x122.build.bazel.remote.execution.v2.SpliceBlobRequest\x1a3.build.bazel.remote.execution.v2.SpliceBlobResponse\"2\x82\xd3\xe4\x93\x02,:\x01*\"'/v2/{instance_name=**}/blobs:spliceBlob2\xbd\x01\n" + + "\fCapabilities\x12\xac\x01\n" + + "\x0fGetCapabilities\x127.build.bazel.remote.execution.v2.GetCapabilitiesRequest\x1a3.build.bazel.remote.execution.v2.ServerCapabilities\"+\x82\xd3\xe4\x93\x02%\x12#/v2/{instance_name=**}/capabilitiesB\xb4\x01\n" + + "\x1fbuild.bazel.remote.execution.v2B\x14RemoteExecutionProtoP\x01ZQgithub.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2;remoteexecution\xa2\x02\x03REX\xaa\x02\x1fBuild.Bazel.Remote.Execution.V2b\x06proto3" + +var file_build_bazel_remote_execution_v2_remote_execution_proto_enumTypes = make([]protoimpl.EnumInfo, 6) +var file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes = make([]protoimpl.MessageInfo, 59) +var file_build_bazel_remote_execution_v2_remote_execution_proto_goTypes = []any{ + (Command_OutputDirectoryFormat)(0), // 0: build.bazel.remote.execution.v2.Command.OutputDirectoryFormat + (ExecutionStage_Value)(0), // 1: build.bazel.remote.execution.v2.ExecutionStage.Value + (DigestFunction_Value)(0), // 2: build.bazel.remote.execution.v2.DigestFunction.Value + (ChunkingFunction_Value)(0), // 3: build.bazel.remote.execution.v2.ChunkingFunction.Value + (SymlinkAbsolutePathStrategy_Value)(0), // 4: build.bazel.remote.execution.v2.SymlinkAbsolutePathStrategy.Value + (Compressor_Value)(0), // 5: build.bazel.remote.execution.v2.Compressor.Value + (*Action)(nil), // 6: build.bazel.remote.execution.v2.Action + (*Command)(nil), // 7: build.bazel.remote.execution.v2.Command + (*Platform)(nil), // 8: build.bazel.remote.execution.v2.Platform + (*Directory)(nil), // 9: build.bazel.remote.execution.v2.Directory + (*NodeProperty)(nil), // 10: build.bazel.remote.execution.v2.NodeProperty + (*NodeProperties)(nil), // 11: build.bazel.remote.execution.v2.NodeProperties + (*FileNode)(nil), // 12: build.bazel.remote.execution.v2.FileNode + (*DirectoryNode)(nil), // 13: build.bazel.remote.execution.v2.DirectoryNode + (*SymlinkNode)(nil), // 14: build.bazel.remote.execution.v2.SymlinkNode + (*Digest)(nil), // 15: build.bazel.remote.execution.v2.Digest + (*ExecutedActionMetadata)(nil), // 16: build.bazel.remote.execution.v2.ExecutedActionMetadata + (*ActionResult)(nil), // 17: build.bazel.remote.execution.v2.ActionResult + (*OutputFile)(nil), // 18: build.bazel.remote.execution.v2.OutputFile + (*Tree)(nil), // 19: build.bazel.remote.execution.v2.Tree + (*OutputDirectory)(nil), // 20: build.bazel.remote.execution.v2.OutputDirectory + (*OutputSymlink)(nil), // 21: build.bazel.remote.execution.v2.OutputSymlink + (*ExecutionPolicy)(nil), // 22: build.bazel.remote.execution.v2.ExecutionPolicy + (*ResultsCachePolicy)(nil), // 23: build.bazel.remote.execution.v2.ResultsCachePolicy + (*ExecuteRequest)(nil), // 24: build.bazel.remote.execution.v2.ExecuteRequest + (*LogFile)(nil), // 25: build.bazel.remote.execution.v2.LogFile + (*ExecuteResponse)(nil), // 26: build.bazel.remote.execution.v2.ExecuteResponse + (*ExecutionStage)(nil), // 27: build.bazel.remote.execution.v2.ExecutionStage + (*ExecuteOperationMetadata)(nil), // 28: build.bazel.remote.execution.v2.ExecuteOperationMetadata + (*WaitExecutionRequest)(nil), // 29: build.bazel.remote.execution.v2.WaitExecutionRequest + (*GetActionResultRequest)(nil), // 30: build.bazel.remote.execution.v2.GetActionResultRequest + (*UpdateActionResultRequest)(nil), // 31: build.bazel.remote.execution.v2.UpdateActionResultRequest + (*FindMissingBlobsRequest)(nil), // 32: build.bazel.remote.execution.v2.FindMissingBlobsRequest + (*FindMissingBlobsResponse)(nil), // 33: build.bazel.remote.execution.v2.FindMissingBlobsResponse + (*BatchUpdateBlobsRequest)(nil), // 34: build.bazel.remote.execution.v2.BatchUpdateBlobsRequest + (*BatchUpdateBlobsResponse)(nil), // 35: build.bazel.remote.execution.v2.BatchUpdateBlobsResponse + (*BatchReadBlobsRequest)(nil), // 36: build.bazel.remote.execution.v2.BatchReadBlobsRequest + (*BatchReadBlobsResponse)(nil), // 37: build.bazel.remote.execution.v2.BatchReadBlobsResponse + (*GetTreeRequest)(nil), // 38: build.bazel.remote.execution.v2.GetTreeRequest + (*GetTreeResponse)(nil), // 39: build.bazel.remote.execution.v2.GetTreeResponse + (*SplitBlobRequest)(nil), // 40: build.bazel.remote.execution.v2.SplitBlobRequest + (*SplitBlobResponse)(nil), // 41: build.bazel.remote.execution.v2.SplitBlobResponse + (*SpliceBlobRequest)(nil), // 42: build.bazel.remote.execution.v2.SpliceBlobRequest + (*SpliceBlobResponse)(nil), // 43: build.bazel.remote.execution.v2.SpliceBlobResponse + (*GetCapabilitiesRequest)(nil), // 44: build.bazel.remote.execution.v2.GetCapabilitiesRequest + (*ServerCapabilities)(nil), // 45: build.bazel.remote.execution.v2.ServerCapabilities + (*DigestFunction)(nil), // 46: build.bazel.remote.execution.v2.DigestFunction + (*ChunkingFunction)(nil), // 47: build.bazel.remote.execution.v2.ChunkingFunction + (*ActionCacheUpdateCapabilities)(nil), // 48: build.bazel.remote.execution.v2.ActionCacheUpdateCapabilities + (*PriorityCapabilities)(nil), // 49: build.bazel.remote.execution.v2.PriorityCapabilities + (*SymlinkAbsolutePathStrategy)(nil), // 50: build.bazel.remote.execution.v2.SymlinkAbsolutePathStrategy + (*Compressor)(nil), // 51: build.bazel.remote.execution.v2.Compressor + (*CacheCapabilities)(nil), // 52: build.bazel.remote.execution.v2.CacheCapabilities + (*FastCdc2020Params)(nil), // 53: build.bazel.remote.execution.v2.FastCdc2020Params + (*RepMaxCdcParams)(nil), // 54: build.bazel.remote.execution.v2.RepMaxCdcParams + (*ExecutionCapabilities)(nil), // 55: build.bazel.remote.execution.v2.ExecutionCapabilities + (*ToolDetails)(nil), // 56: build.bazel.remote.execution.v2.ToolDetails + (*RequestMetadata)(nil), // 57: build.bazel.remote.execution.v2.RequestMetadata + (*Command_EnvironmentVariable)(nil), // 58: build.bazel.remote.execution.v2.Command.EnvironmentVariable + (*Platform_Property)(nil), // 59: build.bazel.remote.execution.v2.Platform.Property + nil, // 60: build.bazel.remote.execution.v2.ExecuteResponse.ServerLogsEntry + (*BatchUpdateBlobsRequest_Request)(nil), // 61: build.bazel.remote.execution.v2.BatchUpdateBlobsRequest.Request + (*BatchUpdateBlobsResponse_Response)(nil), // 62: build.bazel.remote.execution.v2.BatchUpdateBlobsResponse.Response + (*BatchReadBlobsResponse_Response)(nil), // 63: build.bazel.remote.execution.v2.BatchReadBlobsResponse.Response + (*PriorityCapabilities_PriorityRange)(nil), // 64: build.bazel.remote.execution.v2.PriorityCapabilities.PriorityRange + (*durationpb.Duration)(nil), // 65: google.protobuf.Duration + (*timestamppb.Timestamp)(nil), // 66: google.protobuf.Timestamp + (*wrapperspb.UInt32Value)(nil), // 67: google.protobuf.UInt32Value + (*anypb.Any)(nil), // 68: google.protobuf.Any + (*status.Status)(nil), // 69: google.rpc.Status + (*semver.SemVer)(nil), // 70: build.bazel.semver.SemVer + (*longrunningpb.Operation)(nil), // 71: google.longrunning.Operation +} +var file_build_bazel_remote_execution_v2_remote_execution_proto_depIdxs = []int32{ + 15, // 0: build.bazel.remote.execution.v2.Action.command_digest:type_name -> build.bazel.remote.execution.v2.Digest + 15, // 1: build.bazel.remote.execution.v2.Action.input_root_digest:type_name -> build.bazel.remote.execution.v2.Digest + 65, // 2: build.bazel.remote.execution.v2.Action.timeout:type_name -> google.protobuf.Duration + 8, // 3: build.bazel.remote.execution.v2.Action.platform:type_name -> build.bazel.remote.execution.v2.Platform + 58, // 4: build.bazel.remote.execution.v2.Command.environment_variables:type_name -> build.bazel.remote.execution.v2.Command.EnvironmentVariable + 8, // 5: build.bazel.remote.execution.v2.Command.platform:type_name -> build.bazel.remote.execution.v2.Platform + 0, // 6: build.bazel.remote.execution.v2.Command.output_directory_format:type_name -> build.bazel.remote.execution.v2.Command.OutputDirectoryFormat + 59, // 7: build.bazel.remote.execution.v2.Platform.properties:type_name -> build.bazel.remote.execution.v2.Platform.Property + 12, // 8: build.bazel.remote.execution.v2.Directory.files:type_name -> build.bazel.remote.execution.v2.FileNode + 13, // 9: build.bazel.remote.execution.v2.Directory.directories:type_name -> build.bazel.remote.execution.v2.DirectoryNode + 14, // 10: build.bazel.remote.execution.v2.Directory.symlinks:type_name -> build.bazel.remote.execution.v2.SymlinkNode + 11, // 11: build.bazel.remote.execution.v2.Directory.node_properties:type_name -> build.bazel.remote.execution.v2.NodeProperties + 10, // 12: build.bazel.remote.execution.v2.NodeProperties.properties:type_name -> build.bazel.remote.execution.v2.NodeProperty + 66, // 13: build.bazel.remote.execution.v2.NodeProperties.mtime:type_name -> google.protobuf.Timestamp + 67, // 14: build.bazel.remote.execution.v2.NodeProperties.unix_mode:type_name -> google.protobuf.UInt32Value + 15, // 15: build.bazel.remote.execution.v2.FileNode.digest:type_name -> build.bazel.remote.execution.v2.Digest + 11, // 16: build.bazel.remote.execution.v2.FileNode.node_properties:type_name -> build.bazel.remote.execution.v2.NodeProperties + 15, // 17: build.bazel.remote.execution.v2.DirectoryNode.digest:type_name -> build.bazel.remote.execution.v2.Digest + 11, // 18: build.bazel.remote.execution.v2.SymlinkNode.node_properties:type_name -> build.bazel.remote.execution.v2.NodeProperties + 66, // 19: build.bazel.remote.execution.v2.ExecutedActionMetadata.queued_timestamp:type_name -> google.protobuf.Timestamp + 66, // 20: build.bazel.remote.execution.v2.ExecutedActionMetadata.worker_start_timestamp:type_name -> google.protobuf.Timestamp + 66, // 21: build.bazel.remote.execution.v2.ExecutedActionMetadata.worker_completed_timestamp:type_name -> google.protobuf.Timestamp + 66, // 22: build.bazel.remote.execution.v2.ExecutedActionMetadata.input_fetch_start_timestamp:type_name -> google.protobuf.Timestamp + 66, // 23: build.bazel.remote.execution.v2.ExecutedActionMetadata.input_fetch_completed_timestamp:type_name -> google.protobuf.Timestamp + 66, // 24: build.bazel.remote.execution.v2.ExecutedActionMetadata.execution_start_timestamp:type_name -> google.protobuf.Timestamp + 66, // 25: build.bazel.remote.execution.v2.ExecutedActionMetadata.execution_completed_timestamp:type_name -> google.protobuf.Timestamp + 65, // 26: build.bazel.remote.execution.v2.ExecutedActionMetadata.virtual_execution_duration:type_name -> google.protobuf.Duration + 66, // 27: build.bazel.remote.execution.v2.ExecutedActionMetadata.output_upload_start_timestamp:type_name -> google.protobuf.Timestamp + 66, // 28: build.bazel.remote.execution.v2.ExecutedActionMetadata.output_upload_completed_timestamp:type_name -> google.protobuf.Timestamp + 68, // 29: build.bazel.remote.execution.v2.ExecutedActionMetadata.auxiliary_metadata:type_name -> google.protobuf.Any + 18, // 30: build.bazel.remote.execution.v2.ActionResult.output_files:type_name -> build.bazel.remote.execution.v2.OutputFile + 21, // 31: build.bazel.remote.execution.v2.ActionResult.output_file_symlinks:type_name -> build.bazel.remote.execution.v2.OutputSymlink + 21, // 32: build.bazel.remote.execution.v2.ActionResult.output_symlinks:type_name -> build.bazel.remote.execution.v2.OutputSymlink + 20, // 33: build.bazel.remote.execution.v2.ActionResult.output_directories:type_name -> build.bazel.remote.execution.v2.OutputDirectory + 21, // 34: build.bazel.remote.execution.v2.ActionResult.output_directory_symlinks:type_name -> build.bazel.remote.execution.v2.OutputSymlink + 15, // 35: build.bazel.remote.execution.v2.ActionResult.stdout_digest:type_name -> build.bazel.remote.execution.v2.Digest + 15, // 36: build.bazel.remote.execution.v2.ActionResult.stderr_digest:type_name -> build.bazel.remote.execution.v2.Digest + 16, // 37: build.bazel.remote.execution.v2.ActionResult.execution_metadata:type_name -> build.bazel.remote.execution.v2.ExecutedActionMetadata + 15, // 38: build.bazel.remote.execution.v2.OutputFile.digest:type_name -> build.bazel.remote.execution.v2.Digest + 11, // 39: build.bazel.remote.execution.v2.OutputFile.node_properties:type_name -> build.bazel.remote.execution.v2.NodeProperties + 9, // 40: build.bazel.remote.execution.v2.Tree.root:type_name -> build.bazel.remote.execution.v2.Directory + 9, // 41: build.bazel.remote.execution.v2.Tree.children:type_name -> build.bazel.remote.execution.v2.Directory + 15, // 42: build.bazel.remote.execution.v2.OutputDirectory.tree_digest:type_name -> build.bazel.remote.execution.v2.Digest + 15, // 43: build.bazel.remote.execution.v2.OutputDirectory.root_directory_digest:type_name -> build.bazel.remote.execution.v2.Digest + 11, // 44: build.bazel.remote.execution.v2.OutputSymlink.node_properties:type_name -> build.bazel.remote.execution.v2.NodeProperties + 15, // 45: build.bazel.remote.execution.v2.ExecuteRequest.action_digest:type_name -> build.bazel.remote.execution.v2.Digest + 22, // 46: build.bazel.remote.execution.v2.ExecuteRequest.execution_policy:type_name -> build.bazel.remote.execution.v2.ExecutionPolicy + 23, // 47: build.bazel.remote.execution.v2.ExecuteRequest.results_cache_policy:type_name -> build.bazel.remote.execution.v2.ResultsCachePolicy + 2, // 48: build.bazel.remote.execution.v2.ExecuteRequest.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 15, // 49: build.bazel.remote.execution.v2.LogFile.digest:type_name -> build.bazel.remote.execution.v2.Digest + 17, // 50: build.bazel.remote.execution.v2.ExecuteResponse.result:type_name -> build.bazel.remote.execution.v2.ActionResult + 69, // 51: build.bazel.remote.execution.v2.ExecuteResponse.status:type_name -> google.rpc.Status + 60, // 52: build.bazel.remote.execution.v2.ExecuteResponse.server_logs:type_name -> build.bazel.remote.execution.v2.ExecuteResponse.ServerLogsEntry + 1, // 53: build.bazel.remote.execution.v2.ExecuteOperationMetadata.stage:type_name -> build.bazel.remote.execution.v2.ExecutionStage.Value + 15, // 54: build.bazel.remote.execution.v2.ExecuteOperationMetadata.action_digest:type_name -> build.bazel.remote.execution.v2.Digest + 16, // 55: build.bazel.remote.execution.v2.ExecuteOperationMetadata.partial_execution_metadata:type_name -> build.bazel.remote.execution.v2.ExecutedActionMetadata + 2, // 56: build.bazel.remote.execution.v2.ExecuteOperationMetadata.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 15, // 57: build.bazel.remote.execution.v2.GetActionResultRequest.action_digest:type_name -> build.bazel.remote.execution.v2.Digest + 2, // 58: build.bazel.remote.execution.v2.GetActionResultRequest.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 15, // 59: build.bazel.remote.execution.v2.UpdateActionResultRequest.action_digest:type_name -> build.bazel.remote.execution.v2.Digest + 17, // 60: build.bazel.remote.execution.v2.UpdateActionResultRequest.action_result:type_name -> build.bazel.remote.execution.v2.ActionResult + 23, // 61: build.bazel.remote.execution.v2.UpdateActionResultRequest.results_cache_policy:type_name -> build.bazel.remote.execution.v2.ResultsCachePolicy + 2, // 62: build.bazel.remote.execution.v2.UpdateActionResultRequest.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 15, // 63: build.bazel.remote.execution.v2.FindMissingBlobsRequest.blob_digests:type_name -> build.bazel.remote.execution.v2.Digest + 2, // 64: build.bazel.remote.execution.v2.FindMissingBlobsRequest.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 15, // 65: build.bazel.remote.execution.v2.FindMissingBlobsResponse.missing_blob_digests:type_name -> build.bazel.remote.execution.v2.Digest + 61, // 66: build.bazel.remote.execution.v2.BatchUpdateBlobsRequest.requests:type_name -> build.bazel.remote.execution.v2.BatchUpdateBlobsRequest.Request + 2, // 67: build.bazel.remote.execution.v2.BatchUpdateBlobsRequest.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 62, // 68: build.bazel.remote.execution.v2.BatchUpdateBlobsResponse.responses:type_name -> build.bazel.remote.execution.v2.BatchUpdateBlobsResponse.Response + 15, // 69: build.bazel.remote.execution.v2.BatchReadBlobsRequest.digests:type_name -> build.bazel.remote.execution.v2.Digest + 5, // 70: build.bazel.remote.execution.v2.BatchReadBlobsRequest.acceptable_compressors:type_name -> build.bazel.remote.execution.v2.Compressor.Value + 2, // 71: build.bazel.remote.execution.v2.BatchReadBlobsRequest.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 63, // 72: build.bazel.remote.execution.v2.BatchReadBlobsResponse.responses:type_name -> build.bazel.remote.execution.v2.BatchReadBlobsResponse.Response + 15, // 73: build.bazel.remote.execution.v2.GetTreeRequest.root_digest:type_name -> build.bazel.remote.execution.v2.Digest + 2, // 74: build.bazel.remote.execution.v2.GetTreeRequest.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 9, // 75: build.bazel.remote.execution.v2.GetTreeResponse.directories:type_name -> build.bazel.remote.execution.v2.Directory + 15, // 76: build.bazel.remote.execution.v2.SplitBlobRequest.blob_digest:type_name -> build.bazel.remote.execution.v2.Digest + 2, // 77: build.bazel.remote.execution.v2.SplitBlobRequest.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 3, // 78: build.bazel.remote.execution.v2.SplitBlobRequest.chunking_function:type_name -> build.bazel.remote.execution.v2.ChunkingFunction.Value + 15, // 79: build.bazel.remote.execution.v2.SplitBlobResponse.chunk_digests:type_name -> build.bazel.remote.execution.v2.Digest + 3, // 80: build.bazel.remote.execution.v2.SplitBlobResponse.chunking_function:type_name -> build.bazel.remote.execution.v2.ChunkingFunction.Value + 15, // 81: build.bazel.remote.execution.v2.SpliceBlobRequest.blob_digest:type_name -> build.bazel.remote.execution.v2.Digest + 15, // 82: build.bazel.remote.execution.v2.SpliceBlobRequest.chunk_digests:type_name -> build.bazel.remote.execution.v2.Digest + 2, // 83: build.bazel.remote.execution.v2.SpliceBlobRequest.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 3, // 84: build.bazel.remote.execution.v2.SpliceBlobRequest.chunking_function:type_name -> build.bazel.remote.execution.v2.ChunkingFunction.Value + 15, // 85: build.bazel.remote.execution.v2.SpliceBlobResponse.blob_digest:type_name -> build.bazel.remote.execution.v2.Digest + 52, // 86: build.bazel.remote.execution.v2.ServerCapabilities.cache_capabilities:type_name -> build.bazel.remote.execution.v2.CacheCapabilities + 55, // 87: build.bazel.remote.execution.v2.ServerCapabilities.execution_capabilities:type_name -> build.bazel.remote.execution.v2.ExecutionCapabilities + 70, // 88: build.bazel.remote.execution.v2.ServerCapabilities.deprecated_api_version:type_name -> build.bazel.semver.SemVer + 70, // 89: build.bazel.remote.execution.v2.ServerCapabilities.low_api_version:type_name -> build.bazel.semver.SemVer + 70, // 90: build.bazel.remote.execution.v2.ServerCapabilities.high_api_version:type_name -> build.bazel.semver.SemVer + 64, // 91: build.bazel.remote.execution.v2.PriorityCapabilities.priorities:type_name -> build.bazel.remote.execution.v2.PriorityCapabilities.PriorityRange + 2, // 92: build.bazel.remote.execution.v2.CacheCapabilities.digest_functions:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 48, // 93: build.bazel.remote.execution.v2.CacheCapabilities.action_cache_update_capabilities:type_name -> build.bazel.remote.execution.v2.ActionCacheUpdateCapabilities + 49, // 94: build.bazel.remote.execution.v2.CacheCapabilities.cache_priority_capabilities:type_name -> build.bazel.remote.execution.v2.PriorityCapabilities + 4, // 95: build.bazel.remote.execution.v2.CacheCapabilities.symlink_absolute_path_strategy:type_name -> build.bazel.remote.execution.v2.SymlinkAbsolutePathStrategy.Value + 5, // 96: build.bazel.remote.execution.v2.CacheCapabilities.supported_compressors:type_name -> build.bazel.remote.execution.v2.Compressor.Value + 5, // 97: build.bazel.remote.execution.v2.CacheCapabilities.supported_batch_update_compressors:type_name -> build.bazel.remote.execution.v2.Compressor.Value + 53, // 98: build.bazel.remote.execution.v2.CacheCapabilities.fast_cdc_2020_params:type_name -> build.bazel.remote.execution.v2.FastCdc2020Params + 54, // 99: build.bazel.remote.execution.v2.CacheCapabilities.rep_max_cdc_params:type_name -> build.bazel.remote.execution.v2.RepMaxCdcParams + 2, // 100: build.bazel.remote.execution.v2.ExecutionCapabilities.digest_function:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 49, // 101: build.bazel.remote.execution.v2.ExecutionCapabilities.execution_priority_capabilities:type_name -> build.bazel.remote.execution.v2.PriorityCapabilities + 2, // 102: build.bazel.remote.execution.v2.ExecutionCapabilities.digest_functions:type_name -> build.bazel.remote.execution.v2.DigestFunction.Value + 56, // 103: build.bazel.remote.execution.v2.RequestMetadata.tool_details:type_name -> build.bazel.remote.execution.v2.ToolDetails + 25, // 104: build.bazel.remote.execution.v2.ExecuteResponse.ServerLogsEntry.value:type_name -> build.bazel.remote.execution.v2.LogFile + 15, // 105: build.bazel.remote.execution.v2.BatchUpdateBlobsRequest.Request.digest:type_name -> build.bazel.remote.execution.v2.Digest + 5, // 106: build.bazel.remote.execution.v2.BatchUpdateBlobsRequest.Request.compressor:type_name -> build.bazel.remote.execution.v2.Compressor.Value + 15, // 107: build.bazel.remote.execution.v2.BatchUpdateBlobsResponse.Response.digest:type_name -> build.bazel.remote.execution.v2.Digest + 69, // 108: build.bazel.remote.execution.v2.BatchUpdateBlobsResponse.Response.status:type_name -> google.rpc.Status + 15, // 109: build.bazel.remote.execution.v2.BatchReadBlobsResponse.Response.digest:type_name -> build.bazel.remote.execution.v2.Digest + 5, // 110: build.bazel.remote.execution.v2.BatchReadBlobsResponse.Response.compressor:type_name -> build.bazel.remote.execution.v2.Compressor.Value + 69, // 111: build.bazel.remote.execution.v2.BatchReadBlobsResponse.Response.status:type_name -> google.rpc.Status + 24, // 112: build.bazel.remote.execution.v2.Execution.Execute:input_type -> build.bazel.remote.execution.v2.ExecuteRequest + 29, // 113: build.bazel.remote.execution.v2.Execution.WaitExecution:input_type -> build.bazel.remote.execution.v2.WaitExecutionRequest + 30, // 114: build.bazel.remote.execution.v2.ActionCache.GetActionResult:input_type -> build.bazel.remote.execution.v2.GetActionResultRequest + 31, // 115: build.bazel.remote.execution.v2.ActionCache.UpdateActionResult:input_type -> build.bazel.remote.execution.v2.UpdateActionResultRequest + 32, // 116: build.bazel.remote.execution.v2.ContentAddressableStorage.FindMissingBlobs:input_type -> build.bazel.remote.execution.v2.FindMissingBlobsRequest + 34, // 117: build.bazel.remote.execution.v2.ContentAddressableStorage.BatchUpdateBlobs:input_type -> build.bazel.remote.execution.v2.BatchUpdateBlobsRequest + 36, // 118: build.bazel.remote.execution.v2.ContentAddressableStorage.BatchReadBlobs:input_type -> build.bazel.remote.execution.v2.BatchReadBlobsRequest + 38, // 119: build.bazel.remote.execution.v2.ContentAddressableStorage.GetTree:input_type -> build.bazel.remote.execution.v2.GetTreeRequest + 40, // 120: build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob:input_type -> build.bazel.remote.execution.v2.SplitBlobRequest + 42, // 121: build.bazel.remote.execution.v2.ContentAddressableStorage.SpliceBlob:input_type -> build.bazel.remote.execution.v2.SpliceBlobRequest + 44, // 122: build.bazel.remote.execution.v2.Capabilities.GetCapabilities:input_type -> build.bazel.remote.execution.v2.GetCapabilitiesRequest + 71, // 123: build.bazel.remote.execution.v2.Execution.Execute:output_type -> google.longrunning.Operation + 71, // 124: build.bazel.remote.execution.v2.Execution.WaitExecution:output_type -> google.longrunning.Operation + 17, // 125: build.bazel.remote.execution.v2.ActionCache.GetActionResult:output_type -> build.bazel.remote.execution.v2.ActionResult + 17, // 126: build.bazel.remote.execution.v2.ActionCache.UpdateActionResult:output_type -> build.bazel.remote.execution.v2.ActionResult + 33, // 127: build.bazel.remote.execution.v2.ContentAddressableStorage.FindMissingBlobs:output_type -> build.bazel.remote.execution.v2.FindMissingBlobsResponse + 35, // 128: build.bazel.remote.execution.v2.ContentAddressableStorage.BatchUpdateBlobs:output_type -> build.bazel.remote.execution.v2.BatchUpdateBlobsResponse + 37, // 129: build.bazel.remote.execution.v2.ContentAddressableStorage.BatchReadBlobs:output_type -> build.bazel.remote.execution.v2.BatchReadBlobsResponse + 39, // 130: build.bazel.remote.execution.v2.ContentAddressableStorage.GetTree:output_type -> build.bazel.remote.execution.v2.GetTreeResponse + 41, // 131: build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob:output_type -> build.bazel.remote.execution.v2.SplitBlobResponse + 43, // 132: build.bazel.remote.execution.v2.ContentAddressableStorage.SpliceBlob:output_type -> build.bazel.remote.execution.v2.SpliceBlobResponse + 45, // 133: build.bazel.remote.execution.v2.Capabilities.GetCapabilities:output_type -> build.bazel.remote.execution.v2.ServerCapabilities + 123, // [123:134] is the sub-list for method output_type + 112, // [112:123] is the sub-list for method input_type + 112, // [112:112] is the sub-list for extension type_name + 112, // [112:112] is the sub-list for extension extendee + 0, // [0:112] is the sub-list for field type_name +} + +func init() { file_build_bazel_remote_execution_v2_remote_execution_proto_init() } +func file_build_bazel_remote_execution_v2_remote_execution_proto_init() { + if File_build_bazel_remote_execution_v2_remote_execution_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_build_bazel_remote_execution_v2_remote_execution_proto_rawDesc), len(file_build_bazel_remote_execution_v2_remote_execution_proto_rawDesc)), + NumEnums: 6, + NumMessages: 59, + NumExtensions: 0, + NumServices: 4, + }, + GoTypes: file_build_bazel_remote_execution_v2_remote_execution_proto_goTypes, + DependencyIndexes: file_build_bazel_remote_execution_v2_remote_execution_proto_depIdxs, + EnumInfos: file_build_bazel_remote_execution_v2_remote_execution_proto_enumTypes, + MessageInfos: file_build_bazel_remote_execution_v2_remote_execution_proto_msgTypes, + }.Build() + File_build_bazel_remote_execution_v2_remote_execution_proto = out.File + file_build_bazel_remote_execution_v2_remote_execution_proto_goTypes = nil + file_build_bazel_remote_execution_v2_remote_execution_proto_depIdxs = nil +} diff --git a/internal/proto/gen/build/bazel/remote/execution/v2/remote_execution_grpc.pb.go b/internal/proto/gen/build/bazel/remote/execution/v2/remote_execution_grpc.pb.go new file mode 100644 index 0000000..5016c7d --- /dev/null +++ b/internal/proto/gen/build/bazel/remote/execution/v2/remote_execution_grpc.pb.go @@ -0,0 +1,1721 @@ +// Copyright 2018 The Bazel Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.5.1 +// - protoc (unknown) +// source: build/bazel/remote/execution/v2/remote_execution.proto + +package remoteexecution + +import ( + longrunningpb "cloud.google.com/go/longrunning/autogen/longrunningpb" + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + Execution_Execute_FullMethodName = "/build.bazel.remote.execution.v2.Execution/Execute" + Execution_WaitExecution_FullMethodName = "/build.bazel.remote.execution.v2.Execution/WaitExecution" +) + +// ExecutionClient is the client API for Execution service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// The Remote Execution API is used to execute an +// [Action][build.bazel.remote.execution.v2.Action] on the remote +// workers. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +type ExecutionClient interface { + // Execute an action remotely. + // + // In order to execute an action, the client must first upload all of the + // inputs, the + // [Command][build.bazel.remote.execution.v2.Command] to run, and the + // [Action][build.bazel.remote.execution.v2.Action] into the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + // It then calls `Execute` with an `action_digest` referring to them. The + // server will run the action and eventually return the result. + // + // The input `Action`'s fields MUST meet the various canonicalization + // requirements specified in the documentation for their types so that it has + // the same digest as other logically equivalent `Action`s. The server MAY + // enforce the requirements and return errors if a non-canonical input is + // received. It MAY also proceed without verifying some or all of the + // requirements, such as for performance reasons. If the server does not + // verify the requirement, then it will treat the `Action` as distinct from + // another logically equivalent action if they hash differently. + // + // Returns a stream of + // [google.longrunning.Operation][google.longrunning.Operation] messages + // describing the resulting execution, with eventual `response` + // [ExecuteResponse][build.bazel.remote.execution.v2.ExecuteResponse]. The + // `metadata` on the operation is of type + // [ExecuteOperationMetadata][build.bazel.remote.execution.v2.ExecuteOperationMetadata]. + // + // If the client remains connected after the first response is returned after + // the server, then updates are streamed as if the client had called + // [WaitExecution][build.bazel.remote.execution.v2.Execution.WaitExecution] + // until the execution completes or the request reaches an error. The + // operation can also be queried using [Operations + // API][google.longrunning.Operations.GetOperation]. + // + // The server NEED NOT implement other methods or functionality of the + // Operations API. + // + // Errors discovered during creation of the `Operation` will be reported + // as gRPC Status errors, while errors that occurred while running the + // action will be reported in the `status` field of the `ExecuteResponse`. The + // server MUST NOT set the `error` field of the `Operation` proto. + // The possible errors include: + // + // - `INVALID_ARGUMENT`: One or more arguments are invalid. + // - `FAILED_PRECONDITION`: One or more errors occurred in setting up the + // action requested, such as a missing input or command or no worker being + // available. The client may be able to fix the errors and retry. + // - `RESOURCE_EXHAUSTED`: There is insufficient quota of some resource to run + // the action. + // - `UNAVAILABLE`: Due to a transient condition, such as all workers being + // occupied (and the server does not support a queue), the action could not + // be started. The client should retry. + // - `INTERNAL`: An internal error occurred in the execution engine or the + // worker. + // - `DEADLINE_EXCEEDED`: The execution timed out. + // - `CANCELLED`: The operation was cancelled by the client. This status is + // only possible if the server implements the Operations API CancelOperation + // method, and it was called for the current execution. + // + // In the case of a missing input or command, the server SHOULD additionally + // send a [PreconditionFailure][google.rpc.PreconditionFailure] error detail + // where, for each requested blob not present in the CAS, there is a + // `Violation` with a `type` of `MISSING` and a `subject` of + // `"blobs/{digest_function/}{hash}/{size}"` indicating the digest of the + // missing blob. The `subject` is formatted the same way as the + // `resource_name` provided to + // [ByteStream.Read][google.bytestream.ByteStream.Read], with the leading + // instance name omitted. `digest_function` MUST thus be omitted if its value + // is one of MD5, MURMUR3, SHA1, SHA256, SHA384, SHA512, or VSO. + // + // The server does not need to guarantee that a call to this method leads to + // at most one execution of the action. The server MAY execute the action + // multiple times, potentially in parallel. These redundant executions MAY + // continue to run, even if the operation is completed. + Execute(ctx context.Context, in *ExecuteRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[longrunningpb.Operation], error) + // Wait for an execution operation to complete. When the client initially + // makes the request, the server immediately responds with the current status + // of the execution. The server will leave the request stream open until the + // operation completes, and then respond with the completed operation. The + // server MAY choose to stream additional updates as execution progresses, + // such as to provide an update as to the state of the execution. + // + // In addition to the cases described for Execute, the WaitExecution method + // may fail as follows: + // + // - `NOT_FOUND`: The operation no longer exists due to any of a transient + // condition, an unknown operation name, or if the server implements the + // Operations API DeleteOperation method and it was called for the current + // execution. The client should call `Execute` to retry. + WaitExecution(ctx context.Context, in *WaitExecutionRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[longrunningpb.Operation], error) +} + +type executionClient struct { + cc grpc.ClientConnInterface +} + +func NewExecutionClient(cc grpc.ClientConnInterface) ExecutionClient { + return &executionClient{cc} +} + +func (c *executionClient) Execute(ctx context.Context, in *ExecuteRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[longrunningpb.Operation], error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + stream, err := c.cc.NewStream(ctx, &Execution_ServiceDesc.Streams[0], Execution_Execute_FullMethodName, cOpts...) + if err != nil { + return nil, err + } + x := &grpc.GenericClientStream[ExecuteRequest, longrunningpb.Operation]{ClientStream: stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Execution_ExecuteClient = grpc.ServerStreamingClient[longrunningpb.Operation] + +func (c *executionClient) WaitExecution(ctx context.Context, in *WaitExecutionRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[longrunningpb.Operation], error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + stream, err := c.cc.NewStream(ctx, &Execution_ServiceDesc.Streams[1], Execution_WaitExecution_FullMethodName, cOpts...) + if err != nil { + return nil, err + } + x := &grpc.GenericClientStream[WaitExecutionRequest, longrunningpb.Operation]{ClientStream: stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Execution_WaitExecutionClient = grpc.ServerStreamingClient[longrunningpb.Operation] + +// ExecutionServer is the server API for Execution service. +// All implementations must embed UnimplementedExecutionServer +// for forward compatibility. +// +// The Remote Execution API is used to execute an +// [Action][build.bazel.remote.execution.v2.Action] on the remote +// workers. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +type ExecutionServer interface { + // Execute an action remotely. + // + // In order to execute an action, the client must first upload all of the + // inputs, the + // [Command][build.bazel.remote.execution.v2.Command] to run, and the + // [Action][build.bazel.remote.execution.v2.Action] into the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + // It then calls `Execute` with an `action_digest` referring to them. The + // server will run the action and eventually return the result. + // + // The input `Action`'s fields MUST meet the various canonicalization + // requirements specified in the documentation for their types so that it has + // the same digest as other logically equivalent `Action`s. The server MAY + // enforce the requirements and return errors if a non-canonical input is + // received. It MAY also proceed without verifying some or all of the + // requirements, such as for performance reasons. If the server does not + // verify the requirement, then it will treat the `Action` as distinct from + // another logically equivalent action if they hash differently. + // + // Returns a stream of + // [google.longrunning.Operation][google.longrunning.Operation] messages + // describing the resulting execution, with eventual `response` + // [ExecuteResponse][build.bazel.remote.execution.v2.ExecuteResponse]. The + // `metadata` on the operation is of type + // [ExecuteOperationMetadata][build.bazel.remote.execution.v2.ExecuteOperationMetadata]. + // + // If the client remains connected after the first response is returned after + // the server, then updates are streamed as if the client had called + // [WaitExecution][build.bazel.remote.execution.v2.Execution.WaitExecution] + // until the execution completes or the request reaches an error. The + // operation can also be queried using [Operations + // API][google.longrunning.Operations.GetOperation]. + // + // The server NEED NOT implement other methods or functionality of the + // Operations API. + // + // Errors discovered during creation of the `Operation` will be reported + // as gRPC Status errors, while errors that occurred while running the + // action will be reported in the `status` field of the `ExecuteResponse`. The + // server MUST NOT set the `error` field of the `Operation` proto. + // The possible errors include: + // + // - `INVALID_ARGUMENT`: One or more arguments are invalid. + // - `FAILED_PRECONDITION`: One or more errors occurred in setting up the + // action requested, such as a missing input or command or no worker being + // available. The client may be able to fix the errors and retry. + // - `RESOURCE_EXHAUSTED`: There is insufficient quota of some resource to run + // the action. + // - `UNAVAILABLE`: Due to a transient condition, such as all workers being + // occupied (and the server does not support a queue), the action could not + // be started. The client should retry. + // - `INTERNAL`: An internal error occurred in the execution engine or the + // worker. + // - `DEADLINE_EXCEEDED`: The execution timed out. + // - `CANCELLED`: The operation was cancelled by the client. This status is + // only possible if the server implements the Operations API CancelOperation + // method, and it was called for the current execution. + // + // In the case of a missing input or command, the server SHOULD additionally + // send a [PreconditionFailure][google.rpc.PreconditionFailure] error detail + // where, for each requested blob not present in the CAS, there is a + // `Violation` with a `type` of `MISSING` and a `subject` of + // `"blobs/{digest_function/}{hash}/{size}"` indicating the digest of the + // missing blob. The `subject` is formatted the same way as the + // `resource_name` provided to + // [ByteStream.Read][google.bytestream.ByteStream.Read], with the leading + // instance name omitted. `digest_function` MUST thus be omitted if its value + // is one of MD5, MURMUR3, SHA1, SHA256, SHA384, SHA512, or VSO. + // + // The server does not need to guarantee that a call to this method leads to + // at most one execution of the action. The server MAY execute the action + // multiple times, potentially in parallel. These redundant executions MAY + // continue to run, even if the operation is completed. + Execute(*ExecuteRequest, grpc.ServerStreamingServer[longrunningpb.Operation]) error + // Wait for an execution operation to complete. When the client initially + // makes the request, the server immediately responds with the current status + // of the execution. The server will leave the request stream open until the + // operation completes, and then respond with the completed operation. The + // server MAY choose to stream additional updates as execution progresses, + // such as to provide an update as to the state of the execution. + // + // In addition to the cases described for Execute, the WaitExecution method + // may fail as follows: + // + // - `NOT_FOUND`: The operation no longer exists due to any of a transient + // condition, an unknown operation name, or if the server implements the + // Operations API DeleteOperation method and it was called for the current + // execution. The client should call `Execute` to retry. + WaitExecution(*WaitExecutionRequest, grpc.ServerStreamingServer[longrunningpb.Operation]) error + mustEmbedUnimplementedExecutionServer() +} + +// UnimplementedExecutionServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedExecutionServer struct{} + +func (UnimplementedExecutionServer) Execute(*ExecuteRequest, grpc.ServerStreamingServer[longrunningpb.Operation]) error { + return status.Errorf(codes.Unimplemented, "method Execute not implemented") +} +func (UnimplementedExecutionServer) WaitExecution(*WaitExecutionRequest, grpc.ServerStreamingServer[longrunningpb.Operation]) error { + return status.Errorf(codes.Unimplemented, "method WaitExecution not implemented") +} +func (UnimplementedExecutionServer) mustEmbedUnimplementedExecutionServer() {} +func (UnimplementedExecutionServer) testEmbeddedByValue() {} + +// UnsafeExecutionServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to ExecutionServer will +// result in compilation errors. +type UnsafeExecutionServer interface { + mustEmbedUnimplementedExecutionServer() +} + +func RegisterExecutionServer(s grpc.ServiceRegistrar, srv ExecutionServer) { + // If the following call pancis, it indicates UnimplementedExecutionServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&Execution_ServiceDesc, srv) +} + +func _Execution_Execute_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(ExecuteRequest) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(ExecutionServer).Execute(m, &grpc.GenericServerStream[ExecuteRequest, longrunningpb.Operation]{ServerStream: stream}) +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Execution_ExecuteServer = grpc.ServerStreamingServer[longrunningpb.Operation] + +func _Execution_WaitExecution_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(WaitExecutionRequest) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(ExecutionServer).WaitExecution(m, &grpc.GenericServerStream[WaitExecutionRequest, longrunningpb.Operation]{ServerStream: stream}) +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type Execution_WaitExecutionServer = grpc.ServerStreamingServer[longrunningpb.Operation] + +// Execution_ServiceDesc is the grpc.ServiceDesc for Execution service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Execution_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "build.bazel.remote.execution.v2.Execution", + HandlerType: (*ExecutionServer)(nil), + Methods: []grpc.MethodDesc{}, + Streams: []grpc.StreamDesc{ + { + StreamName: "Execute", + Handler: _Execution_Execute_Handler, + ServerStreams: true, + }, + { + StreamName: "WaitExecution", + Handler: _Execution_WaitExecution_Handler, + ServerStreams: true, + }, + }, + Metadata: "build/bazel/remote/execution/v2/remote_execution.proto", +} + +const ( + ActionCache_GetActionResult_FullMethodName = "/build.bazel.remote.execution.v2.ActionCache/GetActionResult" + ActionCache_UpdateActionResult_FullMethodName = "/build.bazel.remote.execution.v2.ActionCache/UpdateActionResult" +) + +// ActionCacheClient is the client API for ActionCache service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// The action cache API is used to query whether a given action has already been +// performed and, if so, retrieve its result. Unlike the +// [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage], +// which addresses blobs by their own content, the action cache addresses the +// [ActionResult][build.bazel.remote.execution.v2.ActionResult] by a +// digest of the encoded [Action][build.bazel.remote.execution.v2.Action] +// which produced them. +// +// The lifetime of entries in the action cache is implementation-specific, but +// the server SHOULD assume that more recently used entries are more likely to +// be used again. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +type ActionCacheClient interface { + // Retrieve a cached execution result. + // + // Implementations SHOULD ensure that any blobs referenced from the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage] + // are available at the time of returning the + // [ActionResult][build.bazel.remote.execution.v2.ActionResult] and will be + // for some period of time afterwards. The lifetimes of the referenced blobs SHOULD be increased + // if necessary and applicable. + // + // Errors: + // + // * `NOT_FOUND`: The requested `ActionResult` is not in the cache. + GetActionResult(ctx context.Context, in *GetActionResultRequest, opts ...grpc.CallOption) (*ActionResult, error) + // Upload a new execution result. + // + // In order to allow the server to perform access control based on the type of + // action, and to assist with client debugging, the client MUST first upload + // the [Action][build.bazel.remote.execution.v2.Action] that produced the + // result, along with its + // [Command][build.bazel.remote.execution.v2.Command], into the + // `ContentAddressableStorage`. + // + // Server implementations MAY modify the + // `UpdateActionResultRequest.action_result` and return an equivalent value. + // + // Errors: + // + // - `INVALID_ARGUMENT`: One or more arguments are invalid. + // - `FAILED_PRECONDITION`: One or more errors occurred in updating the + // action result, such as a missing command or action. + // - `RESOURCE_EXHAUSTED`: There is insufficient storage space to add the + // entry to the cache. + UpdateActionResult(ctx context.Context, in *UpdateActionResultRequest, opts ...grpc.CallOption) (*ActionResult, error) +} + +type actionCacheClient struct { + cc grpc.ClientConnInterface +} + +func NewActionCacheClient(cc grpc.ClientConnInterface) ActionCacheClient { + return &actionCacheClient{cc} +} + +func (c *actionCacheClient) GetActionResult(ctx context.Context, in *GetActionResultRequest, opts ...grpc.CallOption) (*ActionResult, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ActionResult) + err := c.cc.Invoke(ctx, ActionCache_GetActionResult_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *actionCacheClient) UpdateActionResult(ctx context.Context, in *UpdateActionResultRequest, opts ...grpc.CallOption) (*ActionResult, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ActionResult) + err := c.cc.Invoke(ctx, ActionCache_UpdateActionResult_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// ActionCacheServer is the server API for ActionCache service. +// All implementations must embed UnimplementedActionCacheServer +// for forward compatibility. +// +// The action cache API is used to query whether a given action has already been +// performed and, if so, retrieve its result. Unlike the +// [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage], +// which addresses blobs by their own content, the action cache addresses the +// [ActionResult][build.bazel.remote.execution.v2.ActionResult] by a +// digest of the encoded [Action][build.bazel.remote.execution.v2.Action] +// which produced them. +// +// The lifetime of entries in the action cache is implementation-specific, but +// the server SHOULD assume that more recently used entries are more likely to +// be used again. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +type ActionCacheServer interface { + // Retrieve a cached execution result. + // + // Implementations SHOULD ensure that any blobs referenced from the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage] + // are available at the time of returning the + // [ActionResult][build.bazel.remote.execution.v2.ActionResult] and will be + // for some period of time afterwards. The lifetimes of the referenced blobs SHOULD be increased + // if necessary and applicable. + // + // Errors: + // + // * `NOT_FOUND`: The requested `ActionResult` is not in the cache. + GetActionResult(context.Context, *GetActionResultRequest) (*ActionResult, error) + // Upload a new execution result. + // + // In order to allow the server to perform access control based on the type of + // action, and to assist with client debugging, the client MUST first upload + // the [Action][build.bazel.remote.execution.v2.Action] that produced the + // result, along with its + // [Command][build.bazel.remote.execution.v2.Command], into the + // `ContentAddressableStorage`. + // + // Server implementations MAY modify the + // `UpdateActionResultRequest.action_result` and return an equivalent value. + // + // Errors: + // + // - `INVALID_ARGUMENT`: One or more arguments are invalid. + // - `FAILED_PRECONDITION`: One or more errors occurred in updating the + // action result, such as a missing command or action. + // - `RESOURCE_EXHAUSTED`: There is insufficient storage space to add the + // entry to the cache. + UpdateActionResult(context.Context, *UpdateActionResultRequest) (*ActionResult, error) + mustEmbedUnimplementedActionCacheServer() +} + +// UnimplementedActionCacheServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedActionCacheServer struct{} + +func (UnimplementedActionCacheServer) GetActionResult(context.Context, *GetActionResultRequest) (*ActionResult, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetActionResult not implemented") +} +func (UnimplementedActionCacheServer) UpdateActionResult(context.Context, *UpdateActionResultRequest) (*ActionResult, error) { + return nil, status.Errorf(codes.Unimplemented, "method UpdateActionResult not implemented") +} +func (UnimplementedActionCacheServer) mustEmbedUnimplementedActionCacheServer() {} +func (UnimplementedActionCacheServer) testEmbeddedByValue() {} + +// UnsafeActionCacheServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to ActionCacheServer will +// result in compilation errors. +type UnsafeActionCacheServer interface { + mustEmbedUnimplementedActionCacheServer() +} + +func RegisterActionCacheServer(s grpc.ServiceRegistrar, srv ActionCacheServer) { + // If the following call pancis, it indicates UnimplementedActionCacheServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&ActionCache_ServiceDesc, srv) +} + +func _ActionCache_GetActionResult_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetActionResultRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ActionCacheServer).GetActionResult(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ActionCache_GetActionResult_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ActionCacheServer).GetActionResult(ctx, req.(*GetActionResultRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ActionCache_UpdateActionResult_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateActionResultRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ActionCacheServer).UpdateActionResult(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ActionCache_UpdateActionResult_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ActionCacheServer).UpdateActionResult(ctx, req.(*UpdateActionResultRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// ActionCache_ServiceDesc is the grpc.ServiceDesc for ActionCache service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var ActionCache_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "build.bazel.remote.execution.v2.ActionCache", + HandlerType: (*ActionCacheServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetActionResult", + Handler: _ActionCache_GetActionResult_Handler, + }, + { + MethodName: "UpdateActionResult", + Handler: _ActionCache_UpdateActionResult_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "build/bazel/remote/execution/v2/remote_execution.proto", +} + +const ( + ContentAddressableStorage_FindMissingBlobs_FullMethodName = "/build.bazel.remote.execution.v2.ContentAddressableStorage/FindMissingBlobs" + ContentAddressableStorage_BatchUpdateBlobs_FullMethodName = "/build.bazel.remote.execution.v2.ContentAddressableStorage/BatchUpdateBlobs" + ContentAddressableStorage_BatchReadBlobs_FullMethodName = "/build.bazel.remote.execution.v2.ContentAddressableStorage/BatchReadBlobs" + ContentAddressableStorage_GetTree_FullMethodName = "/build.bazel.remote.execution.v2.ContentAddressableStorage/GetTree" + ContentAddressableStorage_SplitBlob_FullMethodName = "/build.bazel.remote.execution.v2.ContentAddressableStorage/SplitBlob" + ContentAddressableStorage_SpliceBlob_FullMethodName = "/build.bazel.remote.execution.v2.ContentAddressableStorage/SpliceBlob" +) + +// ContentAddressableStorageClient is the client API for ContentAddressableStorage service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// The CAS (content-addressable storage) is used to store the inputs to and +// outputs from the execution service. Each piece of content is addressed by the +// digest of its binary data. +// +// Most of the binary data stored in the CAS is opaque to the execution engine, +// and is only used as a communication medium. In order to build an +// [Action][build.bazel.remote.execution.v2.Action], +// however, the client will need to also upload the +// [Command][build.bazel.remote.execution.v2.Command] and input root +// [Directory][build.bazel.remote.execution.v2.Directory] for the Action. +// The Command and Directory messages must be marshalled to wire format and then +// uploaded under the hash as with any other piece of content. In practice, the +// input root directory is likely to refer to other Directories in its +// hierarchy, which must also each be uploaded on their own. +// +// For small file uploads the client should group them together and call +// [BatchUpdateBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchUpdateBlobs]. +// +// For large uploads, the client must use the +// [Write method][google.bytestream.ByteStream.Write] of the ByteStream API. +// +// For uncompressed data, the `WriteRequest.resource_name` is of the following form: +// `{instance_name}/uploads/{uuid}/blobs/{digest_function/}{hash}/{size}{/optional_metadata}` +// +// Where: +// - `instance_name` is an identifier used to distinguish between the various +// instances on the server. Syntax and semantics of this field are defined +// by the server; Clients must not make any assumptions about it (e.g., +// whether it spans multiple path segments or not). If it is the empty path, +// the leading slash is omitted, so that the `resource_name` becomes +// `uploads/{uuid}/blobs/{digest_function/}{hash}/{size}{/optional_metadata}`. +// To simplify parsing, a path segment cannot equal any of the following +// keywords: `blobs`, `uploads`, `actions`, `actionResults`, `operations`, +// `capabilities` or `compressed-blobs`. +// - `uuid` is a version 4 UUID generated by the client, used to avoid +// collisions between concurrent uploads of the same data. Clients MAY +// reuse the same `uuid` for uploading different blobs. +// - `digest_function` is a lowercase string form of a `DigestFunction.Value` +// enum, indicating which digest function was used to compute `hash`. If the +// digest function used is one of MD5, MURMUR3, SHA1, SHA256, SHA384, SHA512, +// or VSO, this component MUST be omitted. In that case the server SHOULD +// infer the digest function using the length of the `hash` and the digest +// functions announced in the server's capabilities. +// - `hash` and `size` refer to the [Digest][build.bazel.remote.execution.v2.Digest] +// of the data being uploaded. +// - `optional_metadata` is implementation specific data, which clients MAY omit. +// Servers MAY ignore this metadata. +// +// Data can alternatively be uploaded in compressed form, with the following +// `WriteRequest.resource_name` form: +// `{instance_name}/uploads/{uuid}/compressed-blobs/{compressor}/{digest_function/}{uncompressed_hash}/{uncompressed_size}{/optional_metadata}` +// +// Where: +// - `instance_name`, `uuid`, `digest_function` and `optional_metadata` are +// defined as above. +// - `compressor` is a lowercase string form of a `Compressor.Value` enum +// other than `identity`, which is supported by the server and advertised in +// [CacheCapabilities.supported_compressors][build.bazel.remote.execution.v2.CacheCapabilities.supported_compressors]. +// - `uncompressed_hash` and `uncompressed_size` refer to the +// [Digest][build.bazel.remote.execution.v2.Digest] of the data being +// uploaded, once uncompressed. Servers MUST verify that these match +// the uploaded data once uncompressed, and MUST return an +// `INVALID_ARGUMENT` error in the case of mismatch. +// +// Note that when writing compressed blobs, the `WriteRequest.write_offset` in +// the initial request in a stream refers to the offset in the uncompressed form +// of the blob. In subsequent requests, `WriteRequest.write_offset` MUST be the +// sum of the first request's 'WriteRequest.write_offset' and the total size of +// all the compressed data bundles in the previous requests. +// Note that this mixes an uncompressed offset with a compressed byte length, +// which is nonsensical, but it is done to fit the semantics of the existing +// ByteStream protocol. +// +// Uploads of the same data MAY occur concurrently in any form, compressed or +// uncompressed. +// +// Clients SHOULD NOT use gRPC-level compression for ByteStream API `Write` +// calls of compressed blobs, since this would compress already-compressed data. +// +// When attempting an upload, if another client has already completed the upload +// (which may occur in the middle of a single upload if another client uploads +// the same blob concurrently), the request will terminate immediately without +// error, and with a response whose `committed_size` is the value `-1` if this +// is a compressed upload, or with the full size of the uploaded file if this is +// an uncompressed upload (regardless of how much data was transmitted by the +// client). If the client completes the upload but the +// [Digest][build.bazel.remote.execution.v2.Digest] does not match, an +// `INVALID_ARGUMENT` error will be returned. In either case, the client should +// not attempt to retry the upload. +// +// Small downloads can be grouped and requested in a batch via +// [BatchReadBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchReadBlobs]. +// +// For large downloads, the client must use the +// [Read method][google.bytestream.ByteStream.Read] of the ByteStream API. +// +// For uncompressed data, the `ReadRequest.resource_name` is of the following form: +// `{instance_name}/blobs/{digest_function/}{hash}/{size}` +// Where `instance_name`, `digest_function`, `hash` and `size` are defined as +// for uploads. +// +// Data can alternatively be downloaded in compressed form, with the following +// `ReadRequest.resource_name` form: +// `{instance_name}/compressed-blobs/{compressor}/{digest_function/}{uncompressed_hash}/{uncompressed_size}` +// +// Where: +// - `instance_name`, `compressor` and `digest_function` are defined as for +// uploads. +// - `uncompressed_hash` and `uncompressed_size` refer to the +// [Digest][build.bazel.remote.execution.v2.Digest] of the data being +// downloaded, once uncompressed. Clients MUST verify that these match +// the downloaded data once uncompressed, and take appropriate steps in +// the case of failure such as retrying a limited number of times or +// surfacing an error to the user. +// +// When downloading compressed blobs: +// - `ReadRequest.read_offset` refers to the offset in the uncompressed form +// of the blob. +// - Servers MUST return `INVALID_ARGUMENT` if `ReadRequest.read_limit` is +// non-zero. +// - Servers MAY use any compression level they choose, including different +// levels for different blobs (e.g. choosing a level designed for maximum +// speed for data known to be incompressible). +// - Clients SHOULD NOT use gRPC-level compression, since this would compress +// already-compressed data. +// +// Servers MUST be able to provide data for all recently advertised blobs in +// each of the compression formats that the server supports, as well as in +// uncompressed form. +// +// Additionally, ByteStream requests MAY come with an additional plain text header +// that indicates the `resource_name` of the blob being sent. The header, if +// present, MUST follow the following convention: +// * name: `build.bazel.remote.execution.v2.resource-name`. +// * contents: the plain text resource_name of the request message. +// If set, the contents of the header MUST match the `resource_name` of the request +// message. Servers MAY use this header to assist in routing requests to the +// appropriate backend. +// +// The lifetime of entries in the CAS is implementation specific, but it SHOULD +// be long enough to allow for newly-added and recently looked-up entries to be +// used in subsequent calls (e.g. to +// [Execute][build.bazel.remote.execution.v2.Execution.Execute]). +// +// Servers MUST behave as though empty blobs are always available, even if they +// have not been uploaded. Clients MAY optimize away the uploading or +// downloading of empty blobs. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +type ContentAddressableStorageClient interface { + // Determine if blobs are present in the CAS. + // + // Clients can use this API before uploading blobs to determine which ones are + // already present in the CAS and do not need to be uploaded again. + // + // Servers SHOULD increase the lifetimes of the referenced blobs if necessary and + // applicable. + // + // There are no method-specific errors. + FindMissingBlobs(ctx context.Context, in *FindMissingBlobsRequest, opts ...grpc.CallOption) (*FindMissingBlobsResponse, error) + // Upload many blobs at once. + // + // The server may enforce a limit of the combined total size of blobs + // to be uploaded using this API. This limit may be obtained using the + // [Capabilities][build.bazel.remote.execution.v2.Capabilities] API. + // Requests exceeding the limit should either be split into smaller + // chunks or uploaded using the + // [ByteStream API][google.bytestream.ByteStream], as appropriate. + // + // This request is equivalent to calling a Bytestream `Write` request + // on each individual blob, in parallel. The requests may succeed or fail + // independently. + // + // Errors: + // + // - `INVALID_ARGUMENT`: The client attempted to upload more than the + // server supported limit. + // + // Individual requests may return the following errors, additionally: + // + // * `RESOURCE_EXHAUSTED`: There is insufficient disk quota to store the blob. + // * `INVALID_ARGUMENT`: The + // [Digest][build.bazel.remote.execution.v2.Digest] does not match the + // provided data. + BatchUpdateBlobs(ctx context.Context, in *BatchUpdateBlobsRequest, opts ...grpc.CallOption) (*BatchUpdateBlobsResponse, error) + // Download many blobs at once. + // + // The server may enforce a limit of the combined total size of blobs + // to be downloaded using this API. This limit may be obtained using the + // [Capabilities][build.bazel.remote.execution.v2.Capabilities] API. + // Requests exceeding the limit should either be split into smaller + // chunks or downloaded using the + // [ByteStream API][google.bytestream.ByteStream], as appropriate. + // + // This request is equivalent to calling a Bytestream `Read` request + // on each individual blob, in parallel. The requests may succeed or fail + // independently. + // + // Errors: + // + // - `INVALID_ARGUMENT`: The client attempted to read more than the + // server supported limit. + // + // Every error on individual read will be returned in the corresponding digest + // status. + BatchReadBlobs(ctx context.Context, in *BatchReadBlobsRequest, opts ...grpc.CallOption) (*BatchReadBlobsResponse, error) + // Fetch the entire directory tree rooted at a node. + // + // This request must be targeted at a + // [Directory][build.bazel.remote.execution.v2.Directory] stored in the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage] + // (CAS). The server will enumerate the `Directory` tree recursively and + // return every node descended from the root. + // + // The GetTreeRequest.page_token parameter can be used to skip ahead in + // the stream (e.g. when retrying a partially completed and aborted request), + // by setting it to a value taken from GetTreeResponse.next_page_token of the + // last successfully processed GetTreeResponse). + // + // The exact traversal order is unspecified and, unless retrieving subsequent + // pages from an earlier request, is not guaranteed to be stable across + // multiple invocations of `GetTree`. + // + // If part of the tree is missing from the CAS, the server will return the + // portion present and omit the rest. + // + // Errors: + // + // * `NOT_FOUND`: The requested tree root is not present in the CAS. + GetTree(ctx context.Context, in *GetTreeRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[GetTreeResponse], error) + // SplitBlob retrieves information about how a blob is split into chunks. + // + // This call returns information about how a blob is split into chunks, and + // returns a list of the chunk digests. Using the returned list of chunk digests, + // a client can check which chunks are locally available and only fetch the + // missing ones. The desired blob can be assembled by concatenating the fetched + // chunks in the order of the digests in the list. The chunks SHOULD all be + // available in the CAS. + // + // This API can be used to reduce the required data to download a large blob + // from CAS if some chunks from similar blobs are locally available. For this + // procedure to work properly, blobs SHOULD be split in a content-defined way, + // rather than with fixed-sized chunking. + // + // If a split request is answered successfully, a client can expect the + // following guarantees from the server: + // 1. The blob chunks are stored in CAS. + // 2. Concatenating the blob chunks in the order of the digest list returned + // by the server results in the original blob. + // + // Servers which implement this functionality MUST declare that they support + // it by setting the + // [CacheCapabilities.split_blob_support][build.bazel.remote.execution.v2.CacheCapabilities.split_blob_support] + // field accordingly. + // + // Clients MUST check that the server supports this capability, before using + // it. + // + // Clients SHOULD verify that the digest of the blob assembled by the fetched + // chunks is equal to the requested blob digest. + // + // The lifetimes of the generated chunk blobs MAY be independent of the + // lifetime of the original blob. In particular: + // - A blob and any chunk derived from it MAY be evicted from the CAS at + // different times. + // - A call to [SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob] + // extends the lifetime of the original blob, and sets the lifetimes of + // the resulting chunks (or extends the lifetimes of already-existing + // chunks). + // - Touching a chunk extends its lifetime, but the server MAY choose not + // to extend the lifetime of the original blob. + // - Touching the original blob extends its lifetime, but the server MAY + // choose not to extend the lifetimes of chunks derived from it. + // + // When blob splitting and splicing is used at the same time, the clients and + // the server SHOULD agree out-of-band upon a chunking algorithm used by both + // parties to benefit from each other's chunk data and avoid unnecessary data + // duplication. + // + // Errors: + // + // - `NOT_FOUND`: The requested blob is not present in the CAS, OR there is no + // split information available for the blob, OR at least one chunk needed to + // reconstruct the blob is missing from the CAS. + // - `RESOURCE_EXHAUSTED`: There is insufficient disk quota to store the blob + // chunks. + SplitBlob(ctx context.Context, in *SplitBlobRequest, opts ...grpc.CallOption) (*SplitBlobResponse, error) + // SpliceBlob tells the CAS how chunks can compose a blob. + // + // This is the complementary operation to the + // [ContentAddressableStorage.SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob] + // function to handle the chunked upload of large blobs to save upload + // traffic. + // + // When uploading a large blob using chunked upload, clients MUST first upload + // all chunks to the CAS, then call this RPC to tell the server how those chunks + // compose the original blob. The chunks referenced in the SpliceBlob call SHOULD be + // available in the CAS before calling this RPC. + // + // If a client needs to upload a large blob and is able to split a blob into + // chunks in such a way that reusable chunks are obtained, e.g., by means of + // content-defined chunking, it can first determine which parts of the blob + // are already available in the remote CAS and upload the missing chunks, and + // then use this API to store information on how the chunks compose the + // original blob. + // + // Servers which implement this functionality MUST declare that they support + // it by setting the + // [CacheCapabilities.splice_blob_support][build.bazel.remote.execution.v2.CacheCapabilities.splice_blob_support] + // field accordingly. + // + // Clients MUST check that the server supports this capability, before using + // it. + // + // In order to ensure data consistency of the CAS, the server MUST only add + // blobs to the CAS after verifying their digests. In particular, servers MUST NOT + // trust digests provided by the client. The server MAY accept a request as no-op + // if the client-specified blob is already in CAS or if information on how to + // construct the blob from chunks is available. If the client-specified blob is + // not already in the CAS, the server MUST verify that the digest of the newly + // created blob assembled from chunks matches the digest specified by the + // client, and reject the request if they differ. Servers MAY choose to allow + // overwriting existing chunk mappings or to store multiple chunk mappings for + // the same blob. + // + // When blob splitting and splicing is used at the same time, the clients and + // the server SHOULD agree out-of-band upon a chunking algorithm used by both + // parties to benefit from each other's chunk data and avoid unnecessary data + // duplication. + // + // Errors: + // + // - `NOT_FOUND`: At least one of the blob chunks is not present in the CAS. + // - `RESOURCE_EXHAUSTED`: There is insufficient disk quota to store the + // spliced blob. + // - `INVALID_ARGUMENT`: The digest of the spliced blob is different from the + // provided expected digest. + // - `ALREADY_EXISTS`: The blob already exists in CAS and the server did not + // extend the lifetime of the chunks specified in the request, e.g. because + // it prefers a different chunking and extended those instead. Clients can + // call [SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob] + // to check what chunk mapping the server is using. + SpliceBlob(ctx context.Context, in *SpliceBlobRequest, opts ...grpc.CallOption) (*SpliceBlobResponse, error) +} + +type contentAddressableStorageClient struct { + cc grpc.ClientConnInterface +} + +func NewContentAddressableStorageClient(cc grpc.ClientConnInterface) ContentAddressableStorageClient { + return &contentAddressableStorageClient{cc} +} + +func (c *contentAddressableStorageClient) FindMissingBlobs(ctx context.Context, in *FindMissingBlobsRequest, opts ...grpc.CallOption) (*FindMissingBlobsResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(FindMissingBlobsResponse) + err := c.cc.Invoke(ctx, ContentAddressableStorage_FindMissingBlobs_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *contentAddressableStorageClient) BatchUpdateBlobs(ctx context.Context, in *BatchUpdateBlobsRequest, opts ...grpc.CallOption) (*BatchUpdateBlobsResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(BatchUpdateBlobsResponse) + err := c.cc.Invoke(ctx, ContentAddressableStorage_BatchUpdateBlobs_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *contentAddressableStorageClient) BatchReadBlobs(ctx context.Context, in *BatchReadBlobsRequest, opts ...grpc.CallOption) (*BatchReadBlobsResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(BatchReadBlobsResponse) + err := c.cc.Invoke(ctx, ContentAddressableStorage_BatchReadBlobs_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *contentAddressableStorageClient) GetTree(ctx context.Context, in *GetTreeRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[GetTreeResponse], error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + stream, err := c.cc.NewStream(ctx, &ContentAddressableStorage_ServiceDesc.Streams[0], ContentAddressableStorage_GetTree_FullMethodName, cOpts...) + if err != nil { + return nil, err + } + x := &grpc.GenericClientStream[GetTreeRequest, GetTreeResponse]{ClientStream: stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type ContentAddressableStorage_GetTreeClient = grpc.ServerStreamingClient[GetTreeResponse] + +func (c *contentAddressableStorageClient) SplitBlob(ctx context.Context, in *SplitBlobRequest, opts ...grpc.CallOption) (*SplitBlobResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SplitBlobResponse) + err := c.cc.Invoke(ctx, ContentAddressableStorage_SplitBlob_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *contentAddressableStorageClient) SpliceBlob(ctx context.Context, in *SpliceBlobRequest, opts ...grpc.CallOption) (*SpliceBlobResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SpliceBlobResponse) + err := c.cc.Invoke(ctx, ContentAddressableStorage_SpliceBlob_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// ContentAddressableStorageServer is the server API for ContentAddressableStorage service. +// All implementations must embed UnimplementedContentAddressableStorageServer +// for forward compatibility. +// +// The CAS (content-addressable storage) is used to store the inputs to and +// outputs from the execution service. Each piece of content is addressed by the +// digest of its binary data. +// +// Most of the binary data stored in the CAS is opaque to the execution engine, +// and is only used as a communication medium. In order to build an +// [Action][build.bazel.remote.execution.v2.Action], +// however, the client will need to also upload the +// [Command][build.bazel.remote.execution.v2.Command] and input root +// [Directory][build.bazel.remote.execution.v2.Directory] for the Action. +// The Command and Directory messages must be marshalled to wire format and then +// uploaded under the hash as with any other piece of content. In practice, the +// input root directory is likely to refer to other Directories in its +// hierarchy, which must also each be uploaded on their own. +// +// For small file uploads the client should group them together and call +// [BatchUpdateBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchUpdateBlobs]. +// +// For large uploads, the client must use the +// [Write method][google.bytestream.ByteStream.Write] of the ByteStream API. +// +// For uncompressed data, the `WriteRequest.resource_name` is of the following form: +// `{instance_name}/uploads/{uuid}/blobs/{digest_function/}{hash}/{size}{/optional_metadata}` +// +// Where: +// - `instance_name` is an identifier used to distinguish between the various +// instances on the server. Syntax and semantics of this field are defined +// by the server; Clients must not make any assumptions about it (e.g., +// whether it spans multiple path segments or not). If it is the empty path, +// the leading slash is omitted, so that the `resource_name` becomes +// `uploads/{uuid}/blobs/{digest_function/}{hash}/{size}{/optional_metadata}`. +// To simplify parsing, a path segment cannot equal any of the following +// keywords: `blobs`, `uploads`, `actions`, `actionResults`, `operations`, +// `capabilities` or `compressed-blobs`. +// - `uuid` is a version 4 UUID generated by the client, used to avoid +// collisions between concurrent uploads of the same data. Clients MAY +// reuse the same `uuid` for uploading different blobs. +// - `digest_function` is a lowercase string form of a `DigestFunction.Value` +// enum, indicating which digest function was used to compute `hash`. If the +// digest function used is one of MD5, MURMUR3, SHA1, SHA256, SHA384, SHA512, +// or VSO, this component MUST be omitted. In that case the server SHOULD +// infer the digest function using the length of the `hash` and the digest +// functions announced in the server's capabilities. +// - `hash` and `size` refer to the [Digest][build.bazel.remote.execution.v2.Digest] +// of the data being uploaded. +// - `optional_metadata` is implementation specific data, which clients MAY omit. +// Servers MAY ignore this metadata. +// +// Data can alternatively be uploaded in compressed form, with the following +// `WriteRequest.resource_name` form: +// `{instance_name}/uploads/{uuid}/compressed-blobs/{compressor}/{digest_function/}{uncompressed_hash}/{uncompressed_size}{/optional_metadata}` +// +// Where: +// - `instance_name`, `uuid`, `digest_function` and `optional_metadata` are +// defined as above. +// - `compressor` is a lowercase string form of a `Compressor.Value` enum +// other than `identity`, which is supported by the server and advertised in +// [CacheCapabilities.supported_compressors][build.bazel.remote.execution.v2.CacheCapabilities.supported_compressors]. +// - `uncompressed_hash` and `uncompressed_size` refer to the +// [Digest][build.bazel.remote.execution.v2.Digest] of the data being +// uploaded, once uncompressed. Servers MUST verify that these match +// the uploaded data once uncompressed, and MUST return an +// `INVALID_ARGUMENT` error in the case of mismatch. +// +// Note that when writing compressed blobs, the `WriteRequest.write_offset` in +// the initial request in a stream refers to the offset in the uncompressed form +// of the blob. In subsequent requests, `WriteRequest.write_offset` MUST be the +// sum of the first request's 'WriteRequest.write_offset' and the total size of +// all the compressed data bundles in the previous requests. +// Note that this mixes an uncompressed offset with a compressed byte length, +// which is nonsensical, but it is done to fit the semantics of the existing +// ByteStream protocol. +// +// Uploads of the same data MAY occur concurrently in any form, compressed or +// uncompressed. +// +// Clients SHOULD NOT use gRPC-level compression for ByteStream API `Write` +// calls of compressed blobs, since this would compress already-compressed data. +// +// When attempting an upload, if another client has already completed the upload +// (which may occur in the middle of a single upload if another client uploads +// the same blob concurrently), the request will terminate immediately without +// error, and with a response whose `committed_size` is the value `-1` if this +// is a compressed upload, or with the full size of the uploaded file if this is +// an uncompressed upload (regardless of how much data was transmitted by the +// client). If the client completes the upload but the +// [Digest][build.bazel.remote.execution.v2.Digest] does not match, an +// `INVALID_ARGUMENT` error will be returned. In either case, the client should +// not attempt to retry the upload. +// +// Small downloads can be grouped and requested in a batch via +// [BatchReadBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchReadBlobs]. +// +// For large downloads, the client must use the +// [Read method][google.bytestream.ByteStream.Read] of the ByteStream API. +// +// For uncompressed data, the `ReadRequest.resource_name` is of the following form: +// `{instance_name}/blobs/{digest_function/}{hash}/{size}` +// Where `instance_name`, `digest_function`, `hash` and `size` are defined as +// for uploads. +// +// Data can alternatively be downloaded in compressed form, with the following +// `ReadRequest.resource_name` form: +// `{instance_name}/compressed-blobs/{compressor}/{digest_function/}{uncompressed_hash}/{uncompressed_size}` +// +// Where: +// - `instance_name`, `compressor` and `digest_function` are defined as for +// uploads. +// - `uncompressed_hash` and `uncompressed_size` refer to the +// [Digest][build.bazel.remote.execution.v2.Digest] of the data being +// downloaded, once uncompressed. Clients MUST verify that these match +// the downloaded data once uncompressed, and take appropriate steps in +// the case of failure such as retrying a limited number of times or +// surfacing an error to the user. +// +// When downloading compressed blobs: +// - `ReadRequest.read_offset` refers to the offset in the uncompressed form +// of the blob. +// - Servers MUST return `INVALID_ARGUMENT` if `ReadRequest.read_limit` is +// non-zero. +// - Servers MAY use any compression level they choose, including different +// levels for different blobs (e.g. choosing a level designed for maximum +// speed for data known to be incompressible). +// - Clients SHOULD NOT use gRPC-level compression, since this would compress +// already-compressed data. +// +// Servers MUST be able to provide data for all recently advertised blobs in +// each of the compression formats that the server supports, as well as in +// uncompressed form. +// +// Additionally, ByteStream requests MAY come with an additional plain text header +// that indicates the `resource_name` of the blob being sent. The header, if +// present, MUST follow the following convention: +// * name: `build.bazel.remote.execution.v2.resource-name`. +// * contents: the plain text resource_name of the request message. +// If set, the contents of the header MUST match the `resource_name` of the request +// message. Servers MAY use this header to assist in routing requests to the +// appropriate backend. +// +// The lifetime of entries in the CAS is implementation specific, but it SHOULD +// be long enough to allow for newly-added and recently looked-up entries to be +// used in subsequent calls (e.g. to +// [Execute][build.bazel.remote.execution.v2.Execution.Execute]). +// +// Servers MUST behave as though empty blobs are always available, even if they +// have not been uploaded. Clients MAY optimize away the uploading or +// downloading of empty blobs. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +type ContentAddressableStorageServer interface { + // Determine if blobs are present in the CAS. + // + // Clients can use this API before uploading blobs to determine which ones are + // already present in the CAS and do not need to be uploaded again. + // + // Servers SHOULD increase the lifetimes of the referenced blobs if necessary and + // applicable. + // + // There are no method-specific errors. + FindMissingBlobs(context.Context, *FindMissingBlobsRequest) (*FindMissingBlobsResponse, error) + // Upload many blobs at once. + // + // The server may enforce a limit of the combined total size of blobs + // to be uploaded using this API. This limit may be obtained using the + // [Capabilities][build.bazel.remote.execution.v2.Capabilities] API. + // Requests exceeding the limit should either be split into smaller + // chunks or uploaded using the + // [ByteStream API][google.bytestream.ByteStream], as appropriate. + // + // This request is equivalent to calling a Bytestream `Write` request + // on each individual blob, in parallel. The requests may succeed or fail + // independently. + // + // Errors: + // + // - `INVALID_ARGUMENT`: The client attempted to upload more than the + // server supported limit. + // + // Individual requests may return the following errors, additionally: + // + // * `RESOURCE_EXHAUSTED`: There is insufficient disk quota to store the blob. + // * `INVALID_ARGUMENT`: The + // [Digest][build.bazel.remote.execution.v2.Digest] does not match the + // provided data. + BatchUpdateBlobs(context.Context, *BatchUpdateBlobsRequest) (*BatchUpdateBlobsResponse, error) + // Download many blobs at once. + // + // The server may enforce a limit of the combined total size of blobs + // to be downloaded using this API. This limit may be obtained using the + // [Capabilities][build.bazel.remote.execution.v2.Capabilities] API. + // Requests exceeding the limit should either be split into smaller + // chunks or downloaded using the + // [ByteStream API][google.bytestream.ByteStream], as appropriate. + // + // This request is equivalent to calling a Bytestream `Read` request + // on each individual blob, in parallel. The requests may succeed or fail + // independently. + // + // Errors: + // + // - `INVALID_ARGUMENT`: The client attempted to read more than the + // server supported limit. + // + // Every error on individual read will be returned in the corresponding digest + // status. + BatchReadBlobs(context.Context, *BatchReadBlobsRequest) (*BatchReadBlobsResponse, error) + // Fetch the entire directory tree rooted at a node. + // + // This request must be targeted at a + // [Directory][build.bazel.remote.execution.v2.Directory] stored in the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage] + // (CAS). The server will enumerate the `Directory` tree recursively and + // return every node descended from the root. + // + // The GetTreeRequest.page_token parameter can be used to skip ahead in + // the stream (e.g. when retrying a partially completed and aborted request), + // by setting it to a value taken from GetTreeResponse.next_page_token of the + // last successfully processed GetTreeResponse). + // + // The exact traversal order is unspecified and, unless retrieving subsequent + // pages from an earlier request, is not guaranteed to be stable across + // multiple invocations of `GetTree`. + // + // If part of the tree is missing from the CAS, the server will return the + // portion present and omit the rest. + // + // Errors: + // + // * `NOT_FOUND`: The requested tree root is not present in the CAS. + GetTree(*GetTreeRequest, grpc.ServerStreamingServer[GetTreeResponse]) error + // SplitBlob retrieves information about how a blob is split into chunks. + // + // This call returns information about how a blob is split into chunks, and + // returns a list of the chunk digests. Using the returned list of chunk digests, + // a client can check which chunks are locally available and only fetch the + // missing ones. The desired blob can be assembled by concatenating the fetched + // chunks in the order of the digests in the list. The chunks SHOULD all be + // available in the CAS. + // + // This API can be used to reduce the required data to download a large blob + // from CAS if some chunks from similar blobs are locally available. For this + // procedure to work properly, blobs SHOULD be split in a content-defined way, + // rather than with fixed-sized chunking. + // + // If a split request is answered successfully, a client can expect the + // following guarantees from the server: + // 1. The blob chunks are stored in CAS. + // 2. Concatenating the blob chunks in the order of the digest list returned + // by the server results in the original blob. + // + // Servers which implement this functionality MUST declare that they support + // it by setting the + // [CacheCapabilities.split_blob_support][build.bazel.remote.execution.v2.CacheCapabilities.split_blob_support] + // field accordingly. + // + // Clients MUST check that the server supports this capability, before using + // it. + // + // Clients SHOULD verify that the digest of the blob assembled by the fetched + // chunks is equal to the requested blob digest. + // + // The lifetimes of the generated chunk blobs MAY be independent of the + // lifetime of the original blob. In particular: + // - A blob and any chunk derived from it MAY be evicted from the CAS at + // different times. + // - A call to [SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob] + // extends the lifetime of the original blob, and sets the lifetimes of + // the resulting chunks (or extends the lifetimes of already-existing + // chunks). + // - Touching a chunk extends its lifetime, but the server MAY choose not + // to extend the lifetime of the original blob. + // - Touching the original blob extends its lifetime, but the server MAY + // choose not to extend the lifetimes of chunks derived from it. + // + // When blob splitting and splicing is used at the same time, the clients and + // the server SHOULD agree out-of-band upon a chunking algorithm used by both + // parties to benefit from each other's chunk data and avoid unnecessary data + // duplication. + // + // Errors: + // + // - `NOT_FOUND`: The requested blob is not present in the CAS, OR there is no + // split information available for the blob, OR at least one chunk needed to + // reconstruct the blob is missing from the CAS. + // - `RESOURCE_EXHAUSTED`: There is insufficient disk quota to store the blob + // chunks. + SplitBlob(context.Context, *SplitBlobRequest) (*SplitBlobResponse, error) + // SpliceBlob tells the CAS how chunks can compose a blob. + // + // This is the complementary operation to the + // [ContentAddressableStorage.SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob] + // function to handle the chunked upload of large blobs to save upload + // traffic. + // + // When uploading a large blob using chunked upload, clients MUST first upload + // all chunks to the CAS, then call this RPC to tell the server how those chunks + // compose the original blob. The chunks referenced in the SpliceBlob call SHOULD be + // available in the CAS before calling this RPC. + // + // If a client needs to upload a large blob and is able to split a blob into + // chunks in such a way that reusable chunks are obtained, e.g., by means of + // content-defined chunking, it can first determine which parts of the blob + // are already available in the remote CAS and upload the missing chunks, and + // then use this API to store information on how the chunks compose the + // original blob. + // + // Servers which implement this functionality MUST declare that they support + // it by setting the + // [CacheCapabilities.splice_blob_support][build.bazel.remote.execution.v2.CacheCapabilities.splice_blob_support] + // field accordingly. + // + // Clients MUST check that the server supports this capability, before using + // it. + // + // In order to ensure data consistency of the CAS, the server MUST only add + // blobs to the CAS after verifying their digests. In particular, servers MUST NOT + // trust digests provided by the client. The server MAY accept a request as no-op + // if the client-specified blob is already in CAS or if information on how to + // construct the blob from chunks is available. If the client-specified blob is + // not already in the CAS, the server MUST verify that the digest of the newly + // created blob assembled from chunks matches the digest specified by the + // client, and reject the request if they differ. Servers MAY choose to allow + // overwriting existing chunk mappings or to store multiple chunk mappings for + // the same blob. + // + // When blob splitting and splicing is used at the same time, the clients and + // the server SHOULD agree out-of-band upon a chunking algorithm used by both + // parties to benefit from each other's chunk data and avoid unnecessary data + // duplication. + // + // Errors: + // + // - `NOT_FOUND`: At least one of the blob chunks is not present in the CAS. + // - `RESOURCE_EXHAUSTED`: There is insufficient disk quota to store the + // spliced blob. + // - `INVALID_ARGUMENT`: The digest of the spliced blob is different from the + // provided expected digest. + // - `ALREADY_EXISTS`: The blob already exists in CAS and the server did not + // extend the lifetime of the chunks specified in the request, e.g. because + // it prefers a different chunking and extended those instead. Clients can + // call [SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob] + // to check what chunk mapping the server is using. + SpliceBlob(context.Context, *SpliceBlobRequest) (*SpliceBlobResponse, error) + mustEmbedUnimplementedContentAddressableStorageServer() +} + +// UnimplementedContentAddressableStorageServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedContentAddressableStorageServer struct{} + +func (UnimplementedContentAddressableStorageServer) FindMissingBlobs(context.Context, *FindMissingBlobsRequest) (*FindMissingBlobsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method FindMissingBlobs not implemented") +} +func (UnimplementedContentAddressableStorageServer) BatchUpdateBlobs(context.Context, *BatchUpdateBlobsRequest) (*BatchUpdateBlobsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method BatchUpdateBlobs not implemented") +} +func (UnimplementedContentAddressableStorageServer) BatchReadBlobs(context.Context, *BatchReadBlobsRequest) (*BatchReadBlobsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method BatchReadBlobs not implemented") +} +func (UnimplementedContentAddressableStorageServer) GetTree(*GetTreeRequest, grpc.ServerStreamingServer[GetTreeResponse]) error { + return status.Errorf(codes.Unimplemented, "method GetTree not implemented") +} +func (UnimplementedContentAddressableStorageServer) SplitBlob(context.Context, *SplitBlobRequest) (*SplitBlobResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SplitBlob not implemented") +} +func (UnimplementedContentAddressableStorageServer) SpliceBlob(context.Context, *SpliceBlobRequest) (*SpliceBlobResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SpliceBlob not implemented") +} +func (UnimplementedContentAddressableStorageServer) mustEmbedUnimplementedContentAddressableStorageServer() { +} +func (UnimplementedContentAddressableStorageServer) testEmbeddedByValue() {} + +// UnsafeContentAddressableStorageServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to ContentAddressableStorageServer will +// result in compilation errors. +type UnsafeContentAddressableStorageServer interface { + mustEmbedUnimplementedContentAddressableStorageServer() +} + +func RegisterContentAddressableStorageServer(s grpc.ServiceRegistrar, srv ContentAddressableStorageServer) { + // If the following call pancis, it indicates UnimplementedContentAddressableStorageServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&ContentAddressableStorage_ServiceDesc, srv) +} + +func _ContentAddressableStorage_FindMissingBlobs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(FindMissingBlobsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ContentAddressableStorageServer).FindMissingBlobs(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ContentAddressableStorage_FindMissingBlobs_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ContentAddressableStorageServer).FindMissingBlobs(ctx, req.(*FindMissingBlobsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ContentAddressableStorage_BatchUpdateBlobs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(BatchUpdateBlobsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ContentAddressableStorageServer).BatchUpdateBlobs(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ContentAddressableStorage_BatchUpdateBlobs_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ContentAddressableStorageServer).BatchUpdateBlobs(ctx, req.(*BatchUpdateBlobsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ContentAddressableStorage_BatchReadBlobs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(BatchReadBlobsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ContentAddressableStorageServer).BatchReadBlobs(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ContentAddressableStorage_BatchReadBlobs_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ContentAddressableStorageServer).BatchReadBlobs(ctx, req.(*BatchReadBlobsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ContentAddressableStorage_GetTree_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(GetTreeRequest) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(ContentAddressableStorageServer).GetTree(m, &grpc.GenericServerStream[GetTreeRequest, GetTreeResponse]{ServerStream: stream}) +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type ContentAddressableStorage_GetTreeServer = grpc.ServerStreamingServer[GetTreeResponse] + +func _ContentAddressableStorage_SplitBlob_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SplitBlobRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ContentAddressableStorageServer).SplitBlob(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ContentAddressableStorage_SplitBlob_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ContentAddressableStorageServer).SplitBlob(ctx, req.(*SplitBlobRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ContentAddressableStorage_SpliceBlob_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SpliceBlobRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ContentAddressableStorageServer).SpliceBlob(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ContentAddressableStorage_SpliceBlob_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ContentAddressableStorageServer).SpliceBlob(ctx, req.(*SpliceBlobRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// ContentAddressableStorage_ServiceDesc is the grpc.ServiceDesc for ContentAddressableStorage service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var ContentAddressableStorage_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "build.bazel.remote.execution.v2.ContentAddressableStorage", + HandlerType: (*ContentAddressableStorageServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "FindMissingBlobs", + Handler: _ContentAddressableStorage_FindMissingBlobs_Handler, + }, + { + MethodName: "BatchUpdateBlobs", + Handler: _ContentAddressableStorage_BatchUpdateBlobs_Handler, + }, + { + MethodName: "BatchReadBlobs", + Handler: _ContentAddressableStorage_BatchReadBlobs_Handler, + }, + { + MethodName: "SplitBlob", + Handler: _ContentAddressableStorage_SplitBlob_Handler, + }, + { + MethodName: "SpliceBlob", + Handler: _ContentAddressableStorage_SpliceBlob_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "GetTree", + Handler: _ContentAddressableStorage_GetTree_Handler, + ServerStreams: true, + }, + }, + Metadata: "build/bazel/remote/execution/v2/remote_execution.proto", +} + +const ( + Capabilities_GetCapabilities_FullMethodName = "/build.bazel.remote.execution.v2.Capabilities/GetCapabilities" +) + +// CapabilitiesClient is the client API for Capabilities service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// The Capabilities service may be used by remote execution clients to query +// various server properties, in order to self-configure or return meaningful +// error messages. +// +// The query may include a particular `instance_name`, in which case the values +// returned will pertain to that instance. +type CapabilitiesClient interface { + // GetCapabilities returns the server capabilities configuration of the + // remote endpoint. + // Only the capabilities of the services supported by the endpoint will + // be returned: + // - Execution + CAS + Action Cache endpoints should return both + // CacheCapabilities and ExecutionCapabilities. + // - Execution only endpoints should return ExecutionCapabilities. + // - CAS + Action Cache only endpoints should return CacheCapabilities. + // + // There are no method-specific errors. + GetCapabilities(ctx context.Context, in *GetCapabilitiesRequest, opts ...grpc.CallOption) (*ServerCapabilities, error) +} + +type capabilitiesClient struct { + cc grpc.ClientConnInterface +} + +func NewCapabilitiesClient(cc grpc.ClientConnInterface) CapabilitiesClient { + return &capabilitiesClient{cc} +} + +func (c *capabilitiesClient) GetCapabilities(ctx context.Context, in *GetCapabilitiesRequest, opts ...grpc.CallOption) (*ServerCapabilities, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ServerCapabilities) + err := c.cc.Invoke(ctx, Capabilities_GetCapabilities_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// CapabilitiesServer is the server API for Capabilities service. +// All implementations must embed UnimplementedCapabilitiesServer +// for forward compatibility. +// +// The Capabilities service may be used by remote execution clients to query +// various server properties, in order to self-configure or return meaningful +// error messages. +// +// The query may include a particular `instance_name`, in which case the values +// returned will pertain to that instance. +type CapabilitiesServer interface { + // GetCapabilities returns the server capabilities configuration of the + // remote endpoint. + // Only the capabilities of the services supported by the endpoint will + // be returned: + // - Execution + CAS + Action Cache endpoints should return both + // CacheCapabilities and ExecutionCapabilities. + // - Execution only endpoints should return ExecutionCapabilities. + // - CAS + Action Cache only endpoints should return CacheCapabilities. + // + // There are no method-specific errors. + GetCapabilities(context.Context, *GetCapabilitiesRequest) (*ServerCapabilities, error) + mustEmbedUnimplementedCapabilitiesServer() +} + +// UnimplementedCapabilitiesServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedCapabilitiesServer struct{} + +func (UnimplementedCapabilitiesServer) GetCapabilities(context.Context, *GetCapabilitiesRequest) (*ServerCapabilities, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetCapabilities not implemented") +} +func (UnimplementedCapabilitiesServer) mustEmbedUnimplementedCapabilitiesServer() {} +func (UnimplementedCapabilitiesServer) testEmbeddedByValue() {} + +// UnsafeCapabilitiesServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to CapabilitiesServer will +// result in compilation errors. +type UnsafeCapabilitiesServer interface { + mustEmbedUnimplementedCapabilitiesServer() +} + +func RegisterCapabilitiesServer(s grpc.ServiceRegistrar, srv CapabilitiesServer) { + // If the following call pancis, it indicates UnimplementedCapabilitiesServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&Capabilities_ServiceDesc, srv) +} + +func _Capabilities_GetCapabilities_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetCapabilitiesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(CapabilitiesServer).GetCapabilities(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Capabilities_GetCapabilities_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(CapabilitiesServer).GetCapabilities(ctx, req.(*GetCapabilitiesRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// Capabilities_ServiceDesc is the grpc.ServiceDesc for Capabilities service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Capabilities_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "build.bazel.remote.execution.v2.Capabilities", + HandlerType: (*CapabilitiesServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetCapabilities", + Handler: _Capabilities_GetCapabilities_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "build/bazel/remote/execution/v2/remote_execution.proto", +} diff --git a/internal/proto/gen/build/bazel/semver/semver.pb.go b/internal/proto/gen/build/bazel/semver/semver.pb.go new file mode 100644 index 0000000..26f874c --- /dev/null +++ b/internal/proto/gen/build/bazel/semver/semver.pb.go @@ -0,0 +1,191 @@ +// Copyright 2018 The Bazel Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.12 +// protoc (unknown) +// source: build/bazel/semver/semver.proto + +package semver + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// The full version of a given tool. +type SemVer struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Major int32 `protobuf:"varint,1,opt,name=major,proto3"` + xxx_hidden_Minor int32 `protobuf:"varint,2,opt,name=minor,proto3"` + xxx_hidden_Patch int32 `protobuf:"varint,3,opt,name=patch,proto3"` + xxx_hidden_Prerelease string `protobuf:"bytes,4,opt,name=prerelease,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SemVer) Reset() { + *x = SemVer{} + mi := &file_build_bazel_semver_semver_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SemVer) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SemVer) ProtoMessage() {} + +func (x *SemVer) ProtoReflect() protoreflect.Message { + mi := &file_build_bazel_semver_semver_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *SemVer) GetMajor() int32 { + if x != nil { + return x.xxx_hidden_Major + } + return 0 +} + +func (x *SemVer) GetMinor() int32 { + if x != nil { + return x.xxx_hidden_Minor + } + return 0 +} + +func (x *SemVer) GetPatch() int32 { + if x != nil { + return x.xxx_hidden_Patch + } + return 0 +} + +func (x *SemVer) GetPrerelease() string { + if x != nil { + return x.xxx_hidden_Prerelease + } + return "" +} + +func (x *SemVer) SetMajor(v int32) { + x.xxx_hidden_Major = v +} + +func (x *SemVer) SetMinor(v int32) { + x.xxx_hidden_Minor = v +} + +func (x *SemVer) SetPatch(v int32) { + x.xxx_hidden_Patch = v +} + +func (x *SemVer) SetPrerelease(v string) { + x.xxx_hidden_Prerelease = v +} + +type SemVer_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The major version, e.g 10 for 10.2.3. + Major int32 + // The minor version, e.g. 2 for 10.2.3. + Minor int32 + // The patch version, e.g 3 for 10.2.3. + Patch int32 + // The pre-release version. Either this field or major/minor/patch fields + // must be filled. They are mutually exclusive. Pre-release versions are + // assumed to be earlier than any released versions. + Prerelease string +} + +func (b0 SemVer_builder) Build() *SemVer { + m0 := &SemVer{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Major = b.Major + x.xxx_hidden_Minor = b.Minor + x.xxx_hidden_Patch = b.Patch + x.xxx_hidden_Prerelease = b.Prerelease + return m0 +} + +var File_build_bazel_semver_semver_proto protoreflect.FileDescriptor + +const file_build_bazel_semver_semver_proto_rawDesc = "" + + "\n" + + "\x1fbuild/bazel/semver/semver.proto\x12\x12build.bazel.semver\"j\n" + + "\x06SemVer\x12\x14\n" + + "\x05major\x18\x01 \x01(\x05R\x05major\x12\x14\n" + + "\x05minor\x18\x02 \x01(\x05R\x05minor\x12\x14\n" + + "\x05patch\x18\x03 \x01(\x05R\x05patch\x12\x1e\n" + + "\n" + + "prerelease\x18\x04 \x01(\tR\n" + + "prereleaseBt\n" + + "\x12build.bazel.semverB\vSemverProtoP\x01Z4github.com/bazelbuild/remote-apis/build/bazel/semver\xa2\x02\x03SMV\xaa\x02\x12Build.Bazel.Semverb\x06proto3" + +var file_build_bazel_semver_semver_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_build_bazel_semver_semver_proto_goTypes = []any{ + (*SemVer)(nil), // 0: build.bazel.semver.SemVer +} +var file_build_bazel_semver_semver_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_build_bazel_semver_semver_proto_init() } +func file_build_bazel_semver_semver_proto_init() { + if File_build_bazel_semver_semver_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_build_bazel_semver_semver_proto_rawDesc), len(file_build_bazel_semver_semver_proto_rawDesc)), + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_build_bazel_semver_semver_proto_goTypes, + DependencyIndexes: file_build_bazel_semver_semver_proto_depIdxs, + MessageInfos: file_build_bazel_semver_semver_proto_msgTypes, + }.Build() + File_build_bazel_semver_semver_proto = out.File + file_build_bazel_semver_semver_proto_goTypes = nil + file_build_bazel_semver_semver_proto_depIdxs = nil +} diff --git a/internal/proto/gen/google/bytestream/bytestream.pb.go b/internal/proto/gen/google/bytestream/bytestream.pb.go new file mode 100644 index 0000000..d374d3b --- /dev/null +++ b/internal/proto/gen/google/bytestream/bytestream.pb.go @@ -0,0 +1,598 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.12 +// protoc (unknown) +// source: google/bytestream/bytestream.proto + +package bytestream + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// Request object for ByteStream.Read. +type ReadRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_ResourceName string `protobuf:"bytes,1,opt,name=resource_name,json=resourceName,proto3"` + xxx_hidden_ReadOffset int64 `protobuf:"varint,2,opt,name=read_offset,json=readOffset,proto3"` + xxx_hidden_ReadLimit int64 `protobuf:"varint,3,opt,name=read_limit,json=readLimit,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ReadRequest) Reset() { + *x = ReadRequest{} + mi := &file_google_bytestream_bytestream_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ReadRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ReadRequest) ProtoMessage() {} + +func (x *ReadRequest) ProtoReflect() protoreflect.Message { + mi := &file_google_bytestream_bytestream_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *ReadRequest) GetResourceName() string { + if x != nil { + return x.xxx_hidden_ResourceName + } + return "" +} + +func (x *ReadRequest) GetReadOffset() int64 { + if x != nil { + return x.xxx_hidden_ReadOffset + } + return 0 +} + +func (x *ReadRequest) GetReadLimit() int64 { + if x != nil { + return x.xxx_hidden_ReadLimit + } + return 0 +} + +func (x *ReadRequest) SetResourceName(v string) { + x.xxx_hidden_ResourceName = v +} + +func (x *ReadRequest) SetReadOffset(v int64) { + x.xxx_hidden_ReadOffset = v +} + +func (x *ReadRequest) SetReadLimit(v int64) { + x.xxx_hidden_ReadLimit = v +} + +type ReadRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The name of the resource to read. + ResourceName string + // The offset for the first byte to return in the read, relative to the start + // of the resource. + // + // A `read_offset` that is negative or greater than the size of the resource + // will cause an `OUT_OF_RANGE` error. + ReadOffset int64 + // The maximum number of `data` bytes the server is allowed to return in the + // sum of all `ReadResponse` messages. A `read_limit` of zero indicates that + // there is no limit, and a negative `read_limit` will cause an error. + // + // If the stream returns fewer bytes than allowed by the `read_limit` and no + // error occurred, the stream includes all data from the `read_offset` to the + // end of the resource. + ReadLimit int64 +} + +func (b0 ReadRequest_builder) Build() *ReadRequest { + m0 := &ReadRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_ResourceName = b.ResourceName + x.xxx_hidden_ReadOffset = b.ReadOffset + x.xxx_hidden_ReadLimit = b.ReadLimit + return m0 +} + +// Response object for ByteStream.Read. +type ReadResponse struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_Data []byte `protobuf:"bytes,10,opt,name=data,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ReadResponse) Reset() { + *x = ReadResponse{} + mi := &file_google_bytestream_bytestream_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ReadResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ReadResponse) ProtoMessage() {} + +func (x *ReadResponse) ProtoReflect() protoreflect.Message { + mi := &file_google_bytestream_bytestream_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *ReadResponse) GetData() []byte { + if x != nil { + return x.xxx_hidden_Data + } + return nil +} + +func (x *ReadResponse) SetData(v []byte) { + if v == nil { + v = []byte{} + } + x.xxx_hidden_Data = v +} + +type ReadResponse_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // A portion of the data for the resource. The service **may** leave `data` + // empty for any given `ReadResponse`. This enables the service to inform the + // client that the request is still live while it is running an operation to + // generate more data. + Data []byte +} + +func (b0 ReadResponse_builder) Build() *ReadResponse { + m0 := &ReadResponse{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_Data = b.Data + return m0 +} + +// Request object for ByteStream.Write. +type WriteRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_ResourceName string `protobuf:"bytes,1,opt,name=resource_name,json=resourceName,proto3"` + xxx_hidden_WriteOffset int64 `protobuf:"varint,2,opt,name=write_offset,json=writeOffset,proto3"` + xxx_hidden_FinishWrite bool `protobuf:"varint,3,opt,name=finish_write,json=finishWrite,proto3"` + xxx_hidden_Data []byte `protobuf:"bytes,10,opt,name=data,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WriteRequest) Reset() { + *x = WriteRequest{} + mi := &file_google_bytestream_bytestream_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WriteRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WriteRequest) ProtoMessage() {} + +func (x *WriteRequest) ProtoReflect() protoreflect.Message { + mi := &file_google_bytestream_bytestream_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *WriteRequest) GetResourceName() string { + if x != nil { + return x.xxx_hidden_ResourceName + } + return "" +} + +func (x *WriteRequest) GetWriteOffset() int64 { + if x != nil { + return x.xxx_hidden_WriteOffset + } + return 0 +} + +func (x *WriteRequest) GetFinishWrite() bool { + if x != nil { + return x.xxx_hidden_FinishWrite + } + return false +} + +func (x *WriteRequest) GetData() []byte { + if x != nil { + return x.xxx_hidden_Data + } + return nil +} + +func (x *WriteRequest) SetResourceName(v string) { + x.xxx_hidden_ResourceName = v +} + +func (x *WriteRequest) SetWriteOffset(v int64) { + x.xxx_hidden_WriteOffset = v +} + +func (x *WriteRequest) SetFinishWrite(v bool) { + x.xxx_hidden_FinishWrite = v +} + +func (x *WriteRequest) SetData(v []byte) { + if v == nil { + v = []byte{} + } + x.xxx_hidden_Data = v +} + +type WriteRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The name of the resource to write. This **must** be set on the first + // `WriteRequest` of each `Write()` action. If it is set on subsequent calls, + // it **must** match the value of the first request. + ResourceName string + // The offset from the beginning of the resource at which the data should be + // written. It is required on all `WriteRequest`s. + // + // In the first `WriteRequest` of a `Write()` action, it indicates + // the initial offset for the `Write()` call. The value **must** be equal to + // the `committed_size` that a call to `QueryWriteStatus()` would return. + // + // On subsequent calls, this value **must** be set and **must** be equal to + // the sum of the first `write_offset` and the sizes of all `data` bundles + // sent previously on this stream. + // + // An incorrect value will cause an error. + WriteOffset int64 + // If `true`, this indicates that the write is complete. Sending any + // `WriteRequest`s subsequent to one in which `finish_write` is `true` will + // cause an error. + FinishWrite bool + // A portion of the data for the resource. The client **may** leave `data` + // empty for any given `WriteRequest`. This enables the client to inform the + // service that the request is still live while it is running an operation to + // generate more data. + Data []byte +} + +func (b0 WriteRequest_builder) Build() *WriteRequest { + m0 := &WriteRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_ResourceName = b.ResourceName + x.xxx_hidden_WriteOffset = b.WriteOffset + x.xxx_hidden_FinishWrite = b.FinishWrite + x.xxx_hidden_Data = b.Data + return m0 +} + +// Response object for ByteStream.Write. +type WriteResponse struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_CommittedSize int64 `protobuf:"varint,1,opt,name=committed_size,json=committedSize,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WriteResponse) Reset() { + *x = WriteResponse{} + mi := &file_google_bytestream_bytestream_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WriteResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WriteResponse) ProtoMessage() {} + +func (x *WriteResponse) ProtoReflect() protoreflect.Message { + mi := &file_google_bytestream_bytestream_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *WriteResponse) GetCommittedSize() int64 { + if x != nil { + return x.xxx_hidden_CommittedSize + } + return 0 +} + +func (x *WriteResponse) SetCommittedSize(v int64) { + x.xxx_hidden_CommittedSize = v +} + +type WriteResponse_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The number of bytes that have been processed for the given resource. + CommittedSize int64 +} + +func (b0 WriteResponse_builder) Build() *WriteResponse { + m0 := &WriteResponse{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_CommittedSize = b.CommittedSize + return m0 +} + +// Request object for ByteStream.QueryWriteStatus. +type QueryWriteStatusRequest struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_ResourceName string `protobuf:"bytes,1,opt,name=resource_name,json=resourceName,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *QueryWriteStatusRequest) Reset() { + *x = QueryWriteStatusRequest{} + mi := &file_google_bytestream_bytestream_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *QueryWriteStatusRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*QueryWriteStatusRequest) ProtoMessage() {} + +func (x *QueryWriteStatusRequest) ProtoReflect() protoreflect.Message { + mi := &file_google_bytestream_bytestream_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *QueryWriteStatusRequest) GetResourceName() string { + if x != nil { + return x.xxx_hidden_ResourceName + } + return "" +} + +func (x *QueryWriteStatusRequest) SetResourceName(v string) { + x.xxx_hidden_ResourceName = v +} + +type QueryWriteStatusRequest_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The name of the resource whose write status is being requested. + ResourceName string +} + +func (b0 QueryWriteStatusRequest_builder) Build() *QueryWriteStatusRequest { + m0 := &QueryWriteStatusRequest{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_ResourceName = b.ResourceName + return m0 +} + +// Response object for ByteStream.QueryWriteStatus. +type QueryWriteStatusResponse struct { + state protoimpl.MessageState `protogen:"opaque.v1"` + xxx_hidden_CommittedSize int64 `protobuf:"varint,1,opt,name=committed_size,json=committedSize,proto3"` + xxx_hidden_Complete bool `protobuf:"varint,2,opt,name=complete,proto3"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *QueryWriteStatusResponse) Reset() { + *x = QueryWriteStatusResponse{} + mi := &file_google_bytestream_bytestream_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *QueryWriteStatusResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*QueryWriteStatusResponse) ProtoMessage() {} + +func (x *QueryWriteStatusResponse) ProtoReflect() protoreflect.Message { + mi := &file_google_bytestream_bytestream_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +func (x *QueryWriteStatusResponse) GetCommittedSize() int64 { + if x != nil { + return x.xxx_hidden_CommittedSize + } + return 0 +} + +func (x *QueryWriteStatusResponse) GetComplete() bool { + if x != nil { + return x.xxx_hidden_Complete + } + return false +} + +func (x *QueryWriteStatusResponse) SetCommittedSize(v int64) { + x.xxx_hidden_CommittedSize = v +} + +func (x *QueryWriteStatusResponse) SetComplete(v bool) { + x.xxx_hidden_Complete = v +} + +type QueryWriteStatusResponse_builder struct { + _ [0]func() // Prevents comparability and use of unkeyed literals for the builder. + + // The number of bytes that have been processed for the given resource. + CommittedSize int64 + // `complete` is `true` only if the client has sent a `WriteRequest` with + // `finish_write` set to true, and the server has processed that request. + Complete bool +} + +func (b0 QueryWriteStatusResponse_builder) Build() *QueryWriteStatusResponse { + m0 := &QueryWriteStatusResponse{} + b, x := &b0, m0 + _, _ = b, x + x.xxx_hidden_CommittedSize = b.CommittedSize + x.xxx_hidden_Complete = b.Complete + return m0 +} + +var File_google_bytestream_bytestream_proto protoreflect.FileDescriptor + +const file_google_bytestream_bytestream_proto_rawDesc = "" + + "\n" + + "\"google/bytestream/bytestream.proto\x12\x11google.bytestream\"r\n" + + "\vReadRequest\x12#\n" + + "\rresource_name\x18\x01 \x01(\tR\fresourceName\x12\x1f\n" + + "\vread_offset\x18\x02 \x01(\x03R\n" + + "readOffset\x12\x1d\n" + + "\n" + + "read_limit\x18\x03 \x01(\x03R\treadLimit\"\"\n" + + "\fReadResponse\x12\x12\n" + + "\x04data\x18\n" + + " \x01(\fR\x04data\"\x8d\x01\n" + + "\fWriteRequest\x12#\n" + + "\rresource_name\x18\x01 \x01(\tR\fresourceName\x12!\n" + + "\fwrite_offset\x18\x02 \x01(\x03R\vwriteOffset\x12!\n" + + "\ffinish_write\x18\x03 \x01(\bR\vfinishWrite\x12\x12\n" + + "\x04data\x18\n" + + " \x01(\fR\x04data\"6\n" + + "\rWriteResponse\x12%\n" + + "\x0ecommitted_size\x18\x01 \x01(\x03R\rcommittedSize\">\n" + + "\x17QueryWriteStatusRequest\x12#\n" + + "\rresource_name\x18\x01 \x01(\tR\fresourceName\"]\n" + + "\x18QueryWriteStatusResponse\x12%\n" + + "\x0ecommitted_size\x18\x01 \x01(\x03R\rcommittedSize\x12\x1a\n" + + "\bcomplete\x18\x02 \x01(\bR\bcomplete2\x92\x02\n" + + "\n" + + "ByteStream\x12I\n" + + "\x04Read\x12\x1e.google.bytestream.ReadRequest\x1a\x1f.google.bytestream.ReadResponse0\x01\x12L\n" + + "\x05Write\x12\x1f.google.bytestream.WriteRequest\x1a .google.bytestream.WriteResponse(\x01\x12k\n" + + "\x10QueryWriteStatus\x12*.google.bytestream.QueryWriteStatusRequest\x1a+.google.bytestream.QueryWriteStatusResponseBe\n" + + "\x15com.google.bytestreamB\x0fByteStreamProtoZ;google.golang.org/genproto/googleapis/bytestream;bytestreamb\x06proto3" + +var file_google_bytestream_bytestream_proto_msgTypes = make([]protoimpl.MessageInfo, 6) +var file_google_bytestream_bytestream_proto_goTypes = []any{ + (*ReadRequest)(nil), // 0: google.bytestream.ReadRequest + (*ReadResponse)(nil), // 1: google.bytestream.ReadResponse + (*WriteRequest)(nil), // 2: google.bytestream.WriteRequest + (*WriteResponse)(nil), // 3: google.bytestream.WriteResponse + (*QueryWriteStatusRequest)(nil), // 4: google.bytestream.QueryWriteStatusRequest + (*QueryWriteStatusResponse)(nil), // 5: google.bytestream.QueryWriteStatusResponse +} +var file_google_bytestream_bytestream_proto_depIdxs = []int32{ + 0, // 0: google.bytestream.ByteStream.Read:input_type -> google.bytestream.ReadRequest + 2, // 1: google.bytestream.ByteStream.Write:input_type -> google.bytestream.WriteRequest + 4, // 2: google.bytestream.ByteStream.QueryWriteStatus:input_type -> google.bytestream.QueryWriteStatusRequest + 1, // 3: google.bytestream.ByteStream.Read:output_type -> google.bytestream.ReadResponse + 3, // 4: google.bytestream.ByteStream.Write:output_type -> google.bytestream.WriteResponse + 5, // 5: google.bytestream.ByteStream.QueryWriteStatus:output_type -> google.bytestream.QueryWriteStatusResponse + 3, // [3:6] is the sub-list for method output_type + 0, // [0:3] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_google_bytestream_bytestream_proto_init() } +func file_google_bytestream_bytestream_proto_init() { + if File_google_bytestream_bytestream_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_google_bytestream_bytestream_proto_rawDesc), len(file_google_bytestream_bytestream_proto_rawDesc)), + NumEnums: 0, + NumMessages: 6, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_google_bytestream_bytestream_proto_goTypes, + DependencyIndexes: file_google_bytestream_bytestream_proto_depIdxs, + MessageInfos: file_google_bytestream_bytestream_proto_msgTypes, + }.Build() + File_google_bytestream_bytestream_proto = out.File + file_google_bytestream_bytestream_proto_goTypes = nil + file_google_bytestream_bytestream_proto_depIdxs = nil +} diff --git a/internal/proto/gen/google/bytestream/bytestream_grpc.pb.go b/internal/proto/gen/google/bytestream/bytestream_grpc.pb.go new file mode 100644 index 0000000..e7eadd9 --- /dev/null +++ b/internal/proto/gen/google/bytestream/bytestream_grpc.pb.go @@ -0,0 +1,334 @@ +// Copyright 2025 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.5.1 +// - protoc (unknown) +// source: google/bytestream/bytestream.proto + +package bytestream + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + ByteStream_Read_FullMethodName = "/google.bytestream.ByteStream/Read" + ByteStream_Write_FullMethodName = "/google.bytestream.ByteStream/Write" + ByteStream_QueryWriteStatus_FullMethodName = "/google.bytestream.ByteStream/QueryWriteStatus" +) + +// ByteStreamClient is the client API for ByteStream service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// #### Introduction +// +// The Byte Stream API enables a client to read and write a stream of bytes to +// and from a resource. Resources have names, and these names are supplied in +// the API calls below to identify the resource that is being read from or +// written to. +// +// All implementations of the Byte Stream API export the interface defined here: +// +// * `Read()`: Reads the contents of a resource. +// +// - `Write()`: Writes the contents of a resource. The client can call `Write()` +// multiple times with the same resource and can check the status of the write +// by calling `QueryWriteStatus()`. +// +// #### Service parameters and metadata +// +// The ByteStream API provides no direct way to access/modify any metadata +// associated with the resource. +// +// #### Errors +// +// The errors returned by the service are in the Google canonical error space. +type ByteStreamClient interface { + // `Read()` is used to retrieve the contents of a resource as a sequence + // of bytes. The bytes are returned in a sequence of responses, and the + // responses are delivered as the results of a server-side streaming RPC. + Read(ctx context.Context, in *ReadRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ReadResponse], error) + // `Write()` is used to send the contents of a resource as a sequence of + // bytes. The bytes are sent in a sequence of request protos of a client-side + // streaming RPC. + // + // A `Write()` action is resumable. If there is an error or the connection is + // broken during the `Write()`, the client should check the status of the + // `Write()` by calling `QueryWriteStatus()` and continue writing from the + // returned `committed_size`. This may be less than the amount of data the + // client previously sent. + // + // Calling `Write()` on a resource name that was previously written and + // finalized could cause an error, depending on whether the underlying service + // allows over-writing of previously written resources. + // + // When the client closes the request channel, the service will respond with + // a `WriteResponse`. The service will not view the resource as `complete` + // until the client has sent a `WriteRequest` with `finish_write` set to + // `true`. Sending any requests on a stream after sending a request with + // `finish_write` set to `true` will cause an error. The client **should** + // check the `WriteResponse` it receives to determine how much data the + // service was able to commit and whether the service views the resource as + // `complete` or not. + Write(ctx context.Context, opts ...grpc.CallOption) (grpc.ClientStreamingClient[WriteRequest, WriteResponse], error) + // `QueryWriteStatus()` is used to find the `committed_size` for a resource + // that is being written, which can then be used as the `write_offset` for + // the next `Write()` call. + // + // If the resource does not exist (i.e., the resource has been deleted, or the + // first `Write()` has not yet reached the service), this method returns the + // error `NOT_FOUND`. + // + // The client **may** call `QueryWriteStatus()` at any time to determine how + // much data has been processed for this resource. This is useful if the + // client is buffering data and needs to know which data can be safely + // evicted. For any sequence of `QueryWriteStatus()` calls for a given + // resource name, the sequence of returned `committed_size` values will be + // non-decreasing. + QueryWriteStatus(ctx context.Context, in *QueryWriteStatusRequest, opts ...grpc.CallOption) (*QueryWriteStatusResponse, error) +} + +type byteStreamClient struct { + cc grpc.ClientConnInterface +} + +func NewByteStreamClient(cc grpc.ClientConnInterface) ByteStreamClient { + return &byteStreamClient{cc} +} + +func (c *byteStreamClient) Read(ctx context.Context, in *ReadRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ReadResponse], error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + stream, err := c.cc.NewStream(ctx, &ByteStream_ServiceDesc.Streams[0], ByteStream_Read_FullMethodName, cOpts...) + if err != nil { + return nil, err + } + x := &grpc.GenericClientStream[ReadRequest, ReadResponse]{ClientStream: stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type ByteStream_ReadClient = grpc.ServerStreamingClient[ReadResponse] + +func (c *byteStreamClient) Write(ctx context.Context, opts ...grpc.CallOption) (grpc.ClientStreamingClient[WriteRequest, WriteResponse], error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + stream, err := c.cc.NewStream(ctx, &ByteStream_ServiceDesc.Streams[1], ByteStream_Write_FullMethodName, cOpts...) + if err != nil { + return nil, err + } + x := &grpc.GenericClientStream[WriteRequest, WriteResponse]{ClientStream: stream} + return x, nil +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type ByteStream_WriteClient = grpc.ClientStreamingClient[WriteRequest, WriteResponse] + +func (c *byteStreamClient) QueryWriteStatus(ctx context.Context, in *QueryWriteStatusRequest, opts ...grpc.CallOption) (*QueryWriteStatusResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(QueryWriteStatusResponse) + err := c.cc.Invoke(ctx, ByteStream_QueryWriteStatus_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// ByteStreamServer is the server API for ByteStream service. +// All implementations must embed UnimplementedByteStreamServer +// for forward compatibility. +// +// #### Introduction +// +// The Byte Stream API enables a client to read and write a stream of bytes to +// and from a resource. Resources have names, and these names are supplied in +// the API calls below to identify the resource that is being read from or +// written to. +// +// All implementations of the Byte Stream API export the interface defined here: +// +// * `Read()`: Reads the contents of a resource. +// +// - `Write()`: Writes the contents of a resource. The client can call `Write()` +// multiple times with the same resource and can check the status of the write +// by calling `QueryWriteStatus()`. +// +// #### Service parameters and metadata +// +// The ByteStream API provides no direct way to access/modify any metadata +// associated with the resource. +// +// #### Errors +// +// The errors returned by the service are in the Google canonical error space. +type ByteStreamServer interface { + // `Read()` is used to retrieve the contents of a resource as a sequence + // of bytes. The bytes are returned in a sequence of responses, and the + // responses are delivered as the results of a server-side streaming RPC. + Read(*ReadRequest, grpc.ServerStreamingServer[ReadResponse]) error + // `Write()` is used to send the contents of a resource as a sequence of + // bytes. The bytes are sent in a sequence of request protos of a client-side + // streaming RPC. + // + // A `Write()` action is resumable. If there is an error or the connection is + // broken during the `Write()`, the client should check the status of the + // `Write()` by calling `QueryWriteStatus()` and continue writing from the + // returned `committed_size`. This may be less than the amount of data the + // client previously sent. + // + // Calling `Write()` on a resource name that was previously written and + // finalized could cause an error, depending on whether the underlying service + // allows over-writing of previously written resources. + // + // When the client closes the request channel, the service will respond with + // a `WriteResponse`. The service will not view the resource as `complete` + // until the client has sent a `WriteRequest` with `finish_write` set to + // `true`. Sending any requests on a stream after sending a request with + // `finish_write` set to `true` will cause an error. The client **should** + // check the `WriteResponse` it receives to determine how much data the + // service was able to commit and whether the service views the resource as + // `complete` or not. + Write(grpc.ClientStreamingServer[WriteRequest, WriteResponse]) error + // `QueryWriteStatus()` is used to find the `committed_size` for a resource + // that is being written, which can then be used as the `write_offset` for + // the next `Write()` call. + // + // If the resource does not exist (i.e., the resource has been deleted, or the + // first `Write()` has not yet reached the service), this method returns the + // error `NOT_FOUND`. + // + // The client **may** call `QueryWriteStatus()` at any time to determine how + // much data has been processed for this resource. This is useful if the + // client is buffering data and needs to know which data can be safely + // evicted. For any sequence of `QueryWriteStatus()` calls for a given + // resource name, the sequence of returned `committed_size` values will be + // non-decreasing. + QueryWriteStatus(context.Context, *QueryWriteStatusRequest) (*QueryWriteStatusResponse, error) + mustEmbedUnimplementedByteStreamServer() +} + +// UnimplementedByteStreamServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedByteStreamServer struct{} + +func (UnimplementedByteStreamServer) Read(*ReadRequest, grpc.ServerStreamingServer[ReadResponse]) error { + return status.Errorf(codes.Unimplemented, "method Read not implemented") +} +func (UnimplementedByteStreamServer) Write(grpc.ClientStreamingServer[WriteRequest, WriteResponse]) error { + return status.Errorf(codes.Unimplemented, "method Write not implemented") +} +func (UnimplementedByteStreamServer) QueryWriteStatus(context.Context, *QueryWriteStatusRequest) (*QueryWriteStatusResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method QueryWriteStatus not implemented") +} +func (UnimplementedByteStreamServer) mustEmbedUnimplementedByteStreamServer() {} +func (UnimplementedByteStreamServer) testEmbeddedByValue() {} + +// UnsafeByteStreamServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to ByteStreamServer will +// result in compilation errors. +type UnsafeByteStreamServer interface { + mustEmbedUnimplementedByteStreamServer() +} + +func RegisterByteStreamServer(s grpc.ServiceRegistrar, srv ByteStreamServer) { + // If the following call pancis, it indicates UnimplementedByteStreamServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&ByteStream_ServiceDesc, srv) +} + +func _ByteStream_Read_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(ReadRequest) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(ByteStreamServer).Read(m, &grpc.GenericServerStream[ReadRequest, ReadResponse]{ServerStream: stream}) +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type ByteStream_ReadServer = grpc.ServerStreamingServer[ReadResponse] + +func _ByteStream_Write_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(ByteStreamServer).Write(&grpc.GenericServerStream[WriteRequest, WriteResponse]{ServerStream: stream}) +} + +// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name. +type ByteStream_WriteServer = grpc.ClientStreamingServer[WriteRequest, WriteResponse] + +func _ByteStream_QueryWriteStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryWriteStatusRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ByteStreamServer).QueryWriteStatus(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ByteStream_QueryWriteStatus_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ByteStreamServer).QueryWriteStatus(ctx, req.(*QueryWriteStatusRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// ByteStream_ServiceDesc is the grpc.ServiceDesc for ByteStream service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var ByteStream_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "google.bytestream.ByteStream", + HandlerType: (*ByteStreamServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "QueryWriteStatus", + Handler: _ByteStream_QueryWriteStatus_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "Read", + Handler: _ByteStream_Read_Handler, + ServerStreams: true, + }, + { + StreamName: "Write", + Handler: _ByteStream_Write_Handler, + ClientStreams: true, + }, + }, + Metadata: "google/bytestream/bytestream.proto", +} diff --git a/internal/server/action_result.go b/internal/server/action_result.go index 3aa80ca..bc22e7c 100644 --- a/internal/server/action_result.go +++ b/internal/server/action_result.go @@ -3,6 +3,10 @@ package server import ( "errors" "fmt" + + "google.golang.org/protobuf/proto" + + remoteexecution "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/execution/v2" ) const maxActionResultObjects = 100_000 @@ -53,164 +57,98 @@ func newActionResultReferences() actionResultReferences { } func parseActionResult(data []byte) (actionResultReferences, error) { - references := newActionResultReferences() - var stdoutDigest *digestReference - var stderrDigest *digestReference - var stdoutInline bool - var stderrInline bool + message := &remoteexecution.ActionResult{} + if err := proto.Unmarshal(data, message); err != nil { + return actionResultReferences{}, fmt.Errorf("action_result: %w", err) + } - err := visitWireFields(data, func(field wireField) error { - switch field.number { - case 2: - message, err := field.message("action_result.output_files") - if err != nil { - return err - } - digest, inline, err := parseOutputFile(message) - if err != nil { - return err - } - if digest != nil && !inline { - return references.blobs.add(*digest) - } - case 3: - message, err := field.message("action_result.output_directories") - if err != nil { - return err - } - tree, root, err := parseOutputDirectory(message) - if err != nil { - return err - } - if tree != nil { - if err := references.trees.add(*tree); err != nil { - return err - } - } - if root != nil { - if err := references.directories.add(*root); err != nil { - return err - } - } - case 5: - if _, err := field.message("action_result.stdout_raw"); err != nil { - return err - } - stdoutInline = true - case 6: - message, err := field.message("action_result.stdout_digest") - if err != nil { - return err - } - reference, err := parseDigest(message) - if err != nil { - return fmt.Errorf("action_result.stdout_digest: %w", err) - } - stdoutDigest = &reference - case 7: - if _, err := field.message("action_result.stderr_raw"); err != nil { - return err - } - stderrInline = true - case 8: - message, err := field.message("action_result.stderr_digest") - if err != nil { - return err - } - reference, err := parseDigest(message) - if err != nil { - return fmt.Errorf("action_result.stderr_digest: %w", err) - } - stderrDigest = &reference + references := newActionResultReferences() + for _, file := range message.GetOutputFiles() { + if !file.HasDigest() { + if len(file.GetContents()) == 0 { + return actionResultReferences{}, errors.New( + "output_file has neither digest nor inline contents", + ) + } + continue } - return nil - }) - if err != nil { - return actionResultReferences{}, err - } - if stdoutDigest != nil && !stdoutInline { - if err := references.blobs.add(*stdoutDigest); err != nil { + reference, err := digestReferenceFrom(file.GetDigest(), "output_file.digest") + if err != nil { return actionResultReferences{}, err } - } - if stderrDigest != nil && !stderrInline { - if err := references.blobs.add(*stderrDigest); err != nil { + // Inlined contents travel with the action result, so they are not part of + // the CAS closure even though the digest is still declared. + if len(file.GetContents()) > 0 { + continue + } + if err := references.blobs.add(reference); err != nil { return actionResultReferences{}, err } } - return references, nil -} -func parseOutputFile(data []byte) (*digestReference, bool, error) { - var digest *digestReference - var contentsInline bool - err := visitWireFields(data, func(field wireField) error { - switch field.number { - case 2: - message, err := field.message("output_file.digest") - if err != nil { - return err - } - reference, err := parseDigest(message) - if err != nil { - return fmt.Errorf("output_file.digest: %w", err) - } - if digest != nil { - return errors.New("output_file.digest is repeated") - } - digest = &reference - case 5: - if _, err := field.message("output_file.contents"); err != nil { - return err - } - contentsInline = true + for _, directory := range message.GetOutputDirectories() { + if !directory.HasTreeDigest() && !directory.HasRootDirectoryDigest() { + return actionResultReferences{}, errors.New( + "output_directory has no tree or root directory digest", + ) + } + if err := addOutputDigest( + &references.trees, + directory.GetTreeDigest(), + "output_directory.tree_digest", + ); err != nil { + return actionResultReferences{}, err + } + if err := addOutputDigest( + &references.directories, + directory.GetRootDirectoryDigest(), + "output_directory.root_directory_digest", + ); err != nil { + return actionResultReferences{}, err } - return nil - }) - if err != nil { - return nil, false, err - } - if digest == nil && !contentsInline { - return nil, false, errors.New("output_file has neither digest nor inline contents") } - return digest, contentsInline, nil -} -func parseOutputDirectory(data []byte) (*digestReference, *digestReference, error) { - var tree *digestReference - var root *digestReference - err := visitWireFields(data, func(field wireField) error { - var destination **digestReference - var name string - switch field.number { - case 3: - destination = &tree - name = "output_directory.tree_digest" - case 5: - destination = &root - name = "output_directory.root_directory_digest" - default: + addStream := func(digest *remoteexecution.Digest, inline []byte, name string) error { + if digest == nil { return nil } - message, err := field.message(name) + reference, err := digestReferenceFrom(digest, name) if err != nil { return err } - reference, err := parseDigest(message) - if err != nil { - return fmt.Errorf("%s: %w", name, err) - } - if *destination != nil { - return fmt.Errorf("%s is repeated", name) + if len(inline) > 0 { + return nil } - *destination = &reference + return references.blobs.add(reference) + } + if err := addStream( + message.GetStdoutDigest(), + message.GetStdoutRaw(), + "action_result.stdout_digest", + ); err != nil { + return actionResultReferences{}, err + } + if err := addStream( + message.GetStderrDigest(), + message.GetStderrRaw(), + "action_result.stderr_digest", + ); err != nil { + return actionResultReferences{}, err + } + return references, nil +} + +func addOutputDigest( + collection *digestCollection, + digest *remoteexecution.Digest, + name string, +) error { + if digest == nil { return nil - }) - if err != nil { - return nil, nil, err } - if tree == nil && root == nil { - return nil, nil, errors.New("output_directory has no tree or root directory digest") + reference, err := digestReferenceFrom(digest, name) + if err != nil { + return err } - return tree, root, nil + return collection.add(reference) } diff --git a/internal/server/action_result_test.go b/internal/server/action_result_test.go index b1253e4..45a77b6 100644 --- a/internal/server/action_result_test.go +++ b/internal/server/action_result_test.go @@ -8,7 +8,9 @@ import ( "strings" "testing" - "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" + + remoteexecution "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/execution/v2" ) func TestParseActionResultCollectsOnlyExternalCASReferences(t *testing.T) { @@ -19,14 +21,16 @@ func TestParseActionResultCollectsOnlyExternalCASReferences(t *testing.T) { stdout := referenceFor([]byte("inline stdout")) stderr := referenceFor([]byte("external stderr")) - actionResult := concatProto( - bytesField(2, outputFileProto(direct, nil)), - bytesField(2, outputFileProto(inline, []byte("inline output"))), - bytesField(3, outputDirectoryProto(tree, root)), - bytesField(5, []byte("inline stdout")), - bytesField(6, digestProto(stdout)), - bytesField(8, digestProto(stderr)), - ) + actionResult := marshalProto(t, remoteexecution.ActionResult_builder{ + OutputFiles: []*remoteexecution.OutputFile{ + outputFileProto(direct, nil), + outputFileProto(inline, []byte("inline output")), + }, + OutputDirectories: []*remoteexecution.OutputDirectory{outputDirectoryProto(tree, root)}, + StdoutRaw: []byte("inline stdout"), + StdoutDigest: digestProto(stdout), + StderrDigest: digestProto(stderr), + }.Build()) references, err := parseActionResult(actionResult) if err != nil { @@ -38,11 +42,11 @@ func TestParseActionResultCollectsOnlyExternalCASReferences(t *testing.T) { } func TestParseActionResultRejectsMalformedDigest(t *testing.T) { - malformedDigest := concatProto( - bytesField(1, []byte(strings.Repeat("A", 64))), - varintField(2, 1), - ) - actionResult := bytesField(2, bytesField(2, malformedDigest)) + actionResult := marshalProto(t, remoteexecution.ActionResult_builder{ + OutputFiles: []*remoteexecution.OutputFile{ + outputFileProto(digestReference{hash: strings.Repeat("A", 64), size: 1}, nil), + }, + }.Build()) if _, err := parseActionResult(actionResult); err == nil { t.Fatal("uppercase digest was accepted") } @@ -51,13 +55,18 @@ func TestParseActionResultRejectsMalformedDigest(t *testing.T) { func TestParseTreeCollectsFilesAndRequiresEmbeddedChildren(t *testing.T) { rootFile := referenceFor([]byte("root file")) childFile := referenceFor([]byte("child file")) - child := bytesField(1, fileNodeProto(childFile)) - childReference := referenceFor(child) - root := concatProto( - bytesField(1, fileNodeProto(rootFile)), - bytesField(2, directoryNodeProto(childReference)), - ) - tree := concatProto(bytesField(1, root), bytesField(2, child)) + child := remoteexecution.Directory_builder{ + Files: []*remoteexecution.FileNode{fileNodeProto(childFile)}, + }.Build() + childReference := referenceFor(marshalProto(t, child)) + root := remoteexecution.Directory_builder{ + Files: []*remoteexecution.FileNode{fileNodeProto(rootFile)}, + Directories: []*remoteexecution.DirectoryNode{directoryNodeProto(childReference)}, + }.Build() + tree := marshalProto(t, remoteexecution.Tree_builder{ + Root: root, + Children: []*remoteexecution.Directory{child}, + }.Build()) files, err := parseTree(tree) if err != nil { @@ -65,7 +74,8 @@ func TestParseTreeCollectsFilesAndRequiresEmbeddedChildren(t *testing.T) { } assertReferences(t, files, rootFile, childFile) - if _, err := parseTree(bytesField(1, root)); err == nil { + truncated := marshalProto(t, remoteexecution.Tree_builder{Root: root}.Build()) + if _, err := parseTree(truncated); err == nil { t.Fatal("Tree with a missing embedded child was accepted") } } @@ -73,7 +83,7 @@ func TestParseTreeCollectsFilesAndRequiresEmbeddedChildren(t *testing.T) { func TestActionResultReadRequiresCompleteCASClosure(t *testing.T) { output := []byte("cached output") outputReference := referenceFor(output) - actionResult := bytesField(2, outputFileProto(outputReference, nil)) + actionResult := actionResultProto(t, outputReference) actionDigest := strings.Repeat("a", 64) t.Run("complete", func(t *testing.T) { @@ -88,8 +98,8 @@ func TestActionResultReadRequiresCompleteCASClosure(t *testing.T) { } stats := server.Snapshot() if stats.ValidatedActionResults != 1 || stats.IncompleteActionResults != 0 || - stats.InvalidActionResults != 0 || stats.Hits != 1 || stats.BackendDownloads != 1 || - stats.BackendExistenceChecks != 1 { + stats.InvalidActionResults != 0 || stats.Hits != 1 || stats.BackendDownloads != 0 || + stats.BackendExistenceChecks != 0 { t.Fatalf("unexpected stats: %+v", stats) } }) @@ -112,7 +122,9 @@ func TestActionResultReadRequiresCompleteCASClosure(t *testing.T) { func TestActionResultReadAllowsImplicitEmptyCASDigest(t *testing.T) { emptyReference := referenceFor(nil) - actionResult := bytesField(6, digestProto(emptyReference)) + actionResult := marshalProto(t, remoteexecution.ActionResult_builder{ + StdoutDigest: digestProto(emptyReference), + }.Build()) actionDigest := strings.Repeat("1", 64) backend := newMemoryBackend() backend.objects["test-v1-ac-"+actionDigest] = actionResult @@ -124,16 +136,24 @@ func TestActionResultReadAllowsImplicitEmptyCASDigest(t *testing.T) { } stats := server.Snapshot() if stats.ValidatedActionResults != 1 || stats.IncompleteActionResults != 0 || - stats.Hits != 1 || stats.BackendDownloads != 1 || stats.BackendExistenceChecks != 0 { + stats.Hits != 1 || stats.BackendDownloads != 0 || stats.BackendExistenceChecks != 0 { t.Fatalf("unexpected stats: %+v", stats) } } func TestActionResultReadValidatesTreeFileClosure(t *testing.T) { fileReference := referenceFor([]byte("missing nested file")) - tree := bytesField(1, bytesField(1, fileNodeProto(fileReference))) + tree := marshalProto(t, remoteexecution.Tree_builder{ + Root: remoteexecution.Directory_builder{ + Files: []*remoteexecution.FileNode{fileNodeProto(fileReference)}, + }.Build(), + }.Build()) treeReference := referenceFor(tree) - actionResult := bytesField(3, outputDirectoryProto(treeReference, digestReference{})) + actionResult := marshalProto(t, remoteexecution.ActionResult_builder{ + OutputDirectories: []*remoteexecution.OutputDirectory{ + outputDirectoryProto(treeReference, digestReference{}), + }, + }.Build()) actionDigest := strings.Repeat("b", 64) backend := newMemoryBackend() @@ -146,7 +166,7 @@ func TestActionResultReadValidatesTreeFileClosure(t *testing.T) { t.Fatalf("status = %d, want 404", response.Code) } stats := server.Snapshot() - if stats.IncompleteActionResults != 1 || stats.BackendDownloads != 2 { + if stats.IncompleteActionResults != 1 || stats.BackendDownloads != 0 { t.Fatalf("unexpected stats: %+v", stats) } } @@ -154,11 +174,19 @@ func TestActionResultReadValidatesTreeFileClosure(t *testing.T) { func TestActionResultReadValidatesRootDirectoryClosure(t *testing.T) { file := []byte("nested output") fileReference := referenceFor(file) - child := bytesField(1, fileNodeProto(fileReference)) + child := marshalProto(t, remoteexecution.Directory_builder{ + Files: []*remoteexecution.FileNode{fileNodeProto(fileReference)}, + }.Build()) childReference := referenceFor(child) - root := bytesField(2, directoryNodeProto(childReference)) + root := marshalProto(t, remoteexecution.Directory_builder{ + Directories: []*remoteexecution.DirectoryNode{directoryNodeProto(childReference)}, + }.Build()) rootReference := referenceFor(root) - actionResult := bytesField(3, outputDirectoryProto(digestReference{}, rootReference)) + actionResult := marshalProto(t, remoteexecution.ActionResult_builder{ + OutputDirectories: []*remoteexecution.OutputDirectory{ + outputDirectoryProto(digestReference{}, rootReference), + }, + }.Build()) actionDigest := strings.Repeat("e", 64) t.Run("complete", func(t *testing.T) { @@ -174,8 +202,8 @@ func TestActionResultReadValidatesRootDirectoryClosure(t *testing.T) { t.Fatalf("status = %d, want 200", response.Code) } stats := server.Snapshot() - if stats.ValidatedActionResults != 1 || stats.BackendDownloads != 3 || - stats.BackendExistenceChecks != 1 { + if stats.ValidatedActionResults != 1 || stats.BackendDownloads != 0 || + stats.BackendExistenceChecks != 0 { t.Fatalf("unexpected stats: %+v", stats) } }) @@ -192,7 +220,7 @@ func TestActionResultReadValidatesRootDirectoryClosure(t *testing.T) { t.Fatalf("status = %d, want 404", response.Code) } stats := server.Snapshot() - if stats.IncompleteActionResults != 1 || stats.BackendDownloads != 3 { + if stats.IncompleteActionResults != 1 || stats.BackendDownloads != 0 { t.Fatalf("unexpected stats: %+v", stats) } }) @@ -216,7 +244,7 @@ func TestActionResultReadRejectsInvalidPayload(t *testing.T) { func TestActionResultReadHandlesExistenceCheckErrors(t *testing.T) { outputReference := referenceFor([]byte("output")) - actionResult := bytesField(2, outputFileProto(outputReference, nil)) + actionResult := actionResultProto(t, outputReference) actionDigest := strings.Repeat("f", 64) for _, test := range []struct { @@ -230,19 +258,25 @@ func TestActionResultReadHandlesExistenceCheckErrors(t *testing.T) { } { t.Run(test.name, func(t *testing.T) { backend := newMemoryBackend() - backend.objects["test-v1-ac-"+actionDigest] = actionResult - backend.existsErr = errors.New("unavailable") + writer := testServer(t, backend, nil) + if response := putCacheObject(writer, "/cas/"+outputReference.hash, []byte("output")); response.Code != http.StatusNoContent { + t.Fatalf("seed CAS PUT = %d", response.Code) + } + if response := putCacheObject(writer, "/ac/"+actionDigest, actionResult); response.Code != http.StatusNoContent { + t.Fatalf("seed AC PUT = %d", response.Code) + } + closePackedServer(t, writer) server := testServer(t, backend, func(cfg *Config) { cfg.FailOpen = test.failOpen }) + backend.loadErr = errors.New("unavailable") response := readCacheObject(server, "/ac/"+actionDigest) if response.Code != test.status { t.Fatalf("status = %d, want %d", response.Code, test.status) } stats := server.Snapshot() - if stats.BackendLoadErrors != 1 || stats.Misses != test.misses || - stats.BackendExistenceChecks != 1 { + if stats.BackendLoadErrors != 1 || stats.Misses != test.misses { t.Fatalf("unexpected stats: %+v", stats) } }) @@ -252,26 +286,36 @@ func TestActionResultReadHandlesExistenceCheckErrors(t *testing.T) { func TestActionResultUploadPublishesOnlyCompleteCASClosure(t *testing.T) { output := []byte("persisted output") outputReference := referenceFor(output) - actionResult := bytesField(2, outputFileProto(outputReference, nil)) + actionResult := actionResultProto(t, outputReference) actionDigest := strings.Repeat("d", 64) t.Run("complete", func(t *testing.T) { backend := newMemoryBackend() - backend.objects["test-v1-cas-"+outputReference.hash] = output server := testServer(t, backend, nil) + if response := putCacheObject(server, "/cas/"+outputReference.hash, output); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } response := putCacheObject(server, "/ac/"+actionDigest, actionResult) if response.Code != http.StatusNoContent { t.Fatalf("status = %d, body = %s", response.Code, response.Body) } - if !bytes.Equal(backend.objects["test-v1-ac-"+actionDigest], actionResult) { - t.Fatal("complete action result was not published") + if err := server.packs.flush(t.Context(), true); err != nil { + t.Fatal(err) + } + if err := server.packs.flush(t.Context(), true); err != nil { + t.Fatal(err) } stats := server.Snapshot() - if stats.Uploads != 1 || stats.ValidatedActionResults != 1 || + if stats.PackUploads != 1 || stats.ManifestUploads != 1 || stats.Uploads != 2 || stats.ValidatedActionResults != 1 || stats.SkippedActionResultUploads != 0 { t.Fatalf("unexpected stats: %+v", stats) } + reader := testServer(t, backend, nil) + if restored := readCacheObject(reader, "/ac/"+actionDigest); restored.Code != http.StatusOK || + !bytes.Equal(restored.Body.Bytes(), actionResult) { + t.Fatalf("complete action result was not restored: %d %q", restored.Code, restored.Body.Bytes()) + } }) t.Run("missing output", func(t *testing.T) { @@ -282,8 +326,11 @@ func TestActionResultUploadPublishesOnlyCompleteCASClosure(t *testing.T) { if response.Code != http.StatusNoContent { t.Fatalf("status = %d, body = %s", response.Code, response.Body) } - if _, exists := backend.objects["test-v1-ac-"+actionDigest]; exists { - t.Fatal("incomplete action result was published") + server.packs.mu.Lock() + pending := len(server.packs.pendingActions) + server.packs.mu.Unlock() + if pending != 0 { + t.Fatal("incomplete action result was staged") } stats := server.Snapshot() if stats.Uploads != 0 || stats.IncompleteActionResults != 1 || @@ -295,7 +342,9 @@ func TestActionResultUploadPublishesOnlyCompleteCASClosure(t *testing.T) { func TestActionResultUploadAllowsImplicitEmptyCASDigest(t *testing.T) { emptyReference := referenceFor(nil) - actionResult := bytesField(8, digestProto(emptyReference)) + actionResult := marshalProto(t, remoteexecution.ActionResult_builder{ + StderrDigest: digestProto(emptyReference), + }.Build()) actionDigest := strings.Repeat("2", 64) backend := newMemoryBackend() server := testServer(t, backend, nil) @@ -304,11 +353,11 @@ func TestActionResultUploadAllowsImplicitEmptyCASDigest(t *testing.T) { if response.Code != http.StatusNoContent { t.Fatalf("status = %d, body = %s", response.Code, response.Body) } - if !bytes.Equal(backend.objects["test-v1-ac-"+actionDigest], actionResult) { - t.Fatal("action result with an implicit empty digest was not published") + if err := server.packs.flush(t.Context(), true); err != nil { + t.Fatal(err) } stats := server.Snapshot() - if stats.Uploads != 1 || stats.ValidatedActionResults != 1 || + if stats.PackUploads != 1 || stats.ManifestUploads != 1 || stats.Uploads != 2 || stats.ValidatedActionResults != 1 || stats.IncompleteActionResults != 0 || stats.SkippedActionResultUploads != 0 || stats.BackendExistenceChecks != 0 { t.Fatalf("unexpected stats: %+v", stats) @@ -322,6 +371,13 @@ func readCacheObject(server *Server, path string) *httptest.ResponseRecorder { return response } +func headCacheObject(server *Server, path string) *httptest.ResponseRecorder { + request := httptest.NewRequest(http.MethodHead, path, nil) + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, request) + return response +} + func putCacheObject(server *Server, path string, body []byte) *httptest.ResponseRecorder { request := httptest.NewRequest(http.MethodPut, path, bytes.NewReader(body)) response := httptest.NewRecorder() @@ -333,56 +389,55 @@ func referenceFor(data []byte) digestReference { return digestReference{hash: digest(data), size: int64(len(data))} } -func digestProto(reference digestReference) []byte { - return concatProto( - bytesField(1, []byte(reference.hash)), - varintField(2, uint64(reference.size)), - ) +func digestProto(reference digestReference) *remoteexecution.Digest { + return remoteexecution.Digest_builder{ + Hash: reference.hash, + SizeBytes: reference.size, + }.Build() } -func outputFileProto(reference digestReference, inline []byte) []byte { - message := bytesField(2, digestProto(reference)) - if inline != nil { - message = append(message, bytesField(5, inline)...) - } - return message +func outputFileProto(reference digestReference, inline []byte) *remoteexecution.OutputFile { + return remoteexecution.OutputFile_builder{ + Digest: digestProto(reference), + Contents: inline, + }.Build() } -func outputDirectoryProto(tree, root digestReference) []byte { - var message []byte +func outputDirectoryProto(tree, root digestReference) *remoteexecution.OutputDirectory { + message := remoteexecution.OutputDirectory_builder{} if tree.hash != "" { - message = append(message, bytesField(3, digestProto(tree))...) + message.TreeDigest = digestProto(tree) } if root.hash != "" { - message = append(message, bytesField(5, digestProto(root))...) + message.RootDirectoryDigest = digestProto(root) } - return message -} - -func fileNodeProto(reference digestReference) []byte { - return bytesField(2, digestProto(reference)) + return message.Build() } -func directoryNodeProto(reference digestReference) []byte { - return bytesField(2, digestProto(reference)) +func fileNodeProto(reference digestReference) *remoteexecution.FileNode { + return remoteexecution.FileNode_builder{Digest: digestProto(reference)}.Build() } -func bytesField(number protowire.Number, value []byte) []byte { - message := protowire.AppendTag(nil, number, protowire.BytesType) - return protowire.AppendBytes(message, value) +func directoryNodeProto(reference digestReference) *remoteexecution.DirectoryNode { + return remoteexecution.DirectoryNode_builder{Digest: digestProto(reference)}.Build() } -func varintField(number protowire.Number, value uint64) []byte { - message := protowire.AppendTag(nil, number, protowire.VarintType) - return protowire.AppendVarint(message, value) +// actionResultProto builds the minimal action result that references a single CAS +// blob, which is the fixture most cache-level tests need. +func actionResultProto(t *testing.T, output digestReference) []byte { + t.Helper() + return marshalProto(t, remoteexecution.ActionResult_builder{ + OutputFiles: []*remoteexecution.OutputFile{outputFileProto(output, nil)}, + }.Build()) } -func concatProto(fields ...[]byte) []byte { - var message []byte - for _, field := range fields { - message = append(message, field...) +func marshalProto(t *testing.T, message proto.Message) []byte { + t.Helper() + encoded, err := proto.Marshal(message) + if err != nil { + t.Fatal(err) } - return message + return encoded } func assertReferences(t *testing.T, got []digestReference, want ...digestReference) { diff --git a/internal/server/action_result_validation.go b/internal/server/action_result_validation.go index e2b8447..69d94a8 100644 --- a/internal/server/action_result_validation.go +++ b/internal/server/action_result_validation.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "os" ) var ( @@ -29,11 +28,6 @@ func (s *Server) validateActionResult(ctx context.Context, object object) error return err } -func (s *Server) validateActionResultForPublication(ctx context.Context, object object) error { - _, err := s.validateActionResultClosure(ctx, object, true, false) - return err -} - func (s *Server) collectActionResultClosure(ctx context.Context, object object) ([]digestReference, error) { return s.validateActionResultClosure(ctx, object, false, true) } @@ -44,7 +38,7 @@ func (s *Server) validateActionResultClosure( requirePersisted bool, collect bool, ) ([]digestReference, error) { - data, err := os.ReadFile(object.path) + data, err := object.readAll() if err != nil { return nil, fmt.Errorf("read action result: %w", err) } @@ -95,14 +89,24 @@ func (v *actionResultValidator) validateBlob(reference digestReference) error { return err } v.collect(reference) - key := v.server.cfg.KeyPrefix + "-cas-" + reference.hash - found, err := v.casExists(key) + size, found, err := v.casPresence(reference.hash) if err != nil { return err } if !found { return missingCASObject(reference) } + // A recorded size that disagrees with the action result means the entry is + // not the blob this action claims to have produced. + if size >= 0 && size != reference.size { + return fmt.Errorf( + "%w: CAS object %s has size %d; action result declares %d", + errInvalidActionResult, + reference.hash, + size, + reference.size, + ) + } return nil } @@ -117,7 +121,7 @@ func (v *actionResultValidator) validateTree(reference digestReference) error { if err != nil { return err } - data, err := os.ReadFile(object.path) + data, err := object.readAll() if err != nil { return fmt.Errorf("read tree CAS object %s: %w", reference.hash, err) } @@ -148,7 +152,7 @@ func (v *actionResultValidator) validateDirectoryClosure(roots []digestReference if err != nil { return err } - data, err := os.ReadFile(object.path) + data, err := object.readAll() if err != nil { return fmt.Errorf("read directory CAS object %s: %w", reference.hash, err) } @@ -176,7 +180,7 @@ func (v *actionResultValidator) loadCAS(reference digestReference) (object, erro if err := v.reserveObject(); err != nil { return object{}, err } - key := v.server.cfg.KeyPrefix + "-cas-" + reference.hash + key := v.server.objectKey("cas", reference.hash) if v.requirePersisted { found, err := v.server.backendExists(v.context, key) if err != nil { @@ -205,11 +209,14 @@ func (v *actionResultValidator) loadCAS(reference digestReference) (object, erro return cachedObject, nil } -func (v *actionResultValidator) casExists(key string) (bool, error) { +// casPresence reports availability and size from the manifest without +// downloading the object. Publication still demands a persisted entry. +func (v *actionResultValidator) casPresence(digest string) (int64, bool, error) { if v.requirePersisted { - return v.server.backendExists(v.context, key) + found, err := v.server.backendExists(v.context, v.server.objectKey("cas", digest)) + return -1, found, err } - return v.server.exists(v.context, key) + return v.server.presence(v.context, "cas", digest) } func (v *actionResultValidator) reserveObject() error { diff --git a/internal/server/asset_alias.go b/internal/server/asset_alias.go new file mode 100644 index 0000000..43e5de0 --- /dev/null +++ b/internal/server/asset_alias.go @@ -0,0 +1,74 @@ +package server + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + + "google.golang.org/protobuf/proto" + + remoteexecution "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/execution/v2" +) + +// aliasDomain keeps alias keys from colliding with real action digests, which +// share the action-cache namespace. +const aliasDomain = "bazel-github-actions-cache-v2/asset-alias\x00" + +// aliasOutputPath labels the alias record for anyone inspecting the cache. +const aliasOutputPath = "asset" + +// aliasKey names the entry mapping a non-sha256 checksum onto the sha256 digest +// the content is actually stored under. +func aliasKey(checksum assetChecksum) string { + sum := sha256.Sum256([]byte(aliasDomain + checksum.algorithm + "\x00" + checksum.hash)) + return hex.EncodeToString(sum[:]) +} + +// An alias is recorded as an action result referencing the blob, which is not a +// trick so much as a reuse: that is already the cache's "record pointing at CAS +// content" type. The existing validation then applies unchanged, so an alias +// whose blob has been evicted reads as a miss, and in packed mode serving the +// alias renews the retention of the pack holding the blob. +func aliasRecord(reference digestReference) *remoteexecution.ActionResult { + return remoteexecution.ActionResult_builder{ + OutputFiles: []*remoteexecution.OutputFile{ + remoteexecution.OutputFile_builder{ + Path: aliasOutputPath, + Digest: digestProtoFor(reference), + }.Build(), + }, + }.Build() +} + +func (s *Server) loadAlias(ctx context.Context, checksum assetChecksum) (digestReference, bool) { + data, err := s.readObjectBytes(ctx, "ac", aliasKey(checksum)) + if err != nil { + return digestReference{}, false + } + record := &remoteexecution.ActionResult{} + if err := proto.Unmarshal(data, record); err != nil { + return digestReference{}, false + } + files := record.GetOutputFiles() + if len(files) != 1 { + return digestReference{}, false + } + reference, err := digestReferenceFrom(files[0].GetDigest(), "asset alias") + if err != nil { + return digestReference{}, false + } + return reference, true +} + +func (s *Server) saveAlias( + ctx context.Context, + checksum assetChecksum, + reference digestReference, +) error { + data, err := proto.Marshal(aliasRecord(reference)) + if err != nil { + return err + } + return s.writeObject(ctx, "ac", aliasKey(checksum), bytes.NewReader(data), int64(len(data))) +} diff --git a/internal/server/asset_headers.go b/internal/server/asset_headers.go new file mode 100644 index 0000000..c148ca4 --- /dev/null +++ b/internal/server/asset_headers.go @@ -0,0 +1,271 @@ +package server + +import ( + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + remoteasset "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/asset/v1" +) + +// Bazel attaches request headers as qualifiers, generic ones under +// http_header: and per-URI ones under http_header_url::. The colon is +// used as the delimiter because a header name may not contain one. +const ( + headerQualifier = "http_header:" + headerURLQualifier = "http_header_url:" +) + +// Headers that decide where a request goes, or how its body is framed, are +// never taken from a caller. +var refusedHeaders = map[string]struct{}{ + "host": {}, + "content-length": {}, + "transfer-encoding": {}, + "connection": {}, + "upgrade": {}, + "te": {}, + "trailer": {}, +} + +// assetHeaders holds the headers a fetch may send, keyed by the URI index they +// were scoped to. A URI-specific value wins over the generic one, which is what +// the qualifier definition requires. +type assetHeaders struct { + generic http.Header + specific map[int]http.Header +} + +const ( + maxAssetHeaders = 32 + maxAssetHeaderLen = 8 * 1024 +) + +func parseAssetHeaders(qualifiers []*remoteasset.Qualifier, uris int) (assetHeaders, error) { + headers := assetHeaders{generic: http.Header{}, specific: map[int]http.Header{}} + count := 0 + for _, qualifier := range qualifiers { + name := qualifier.GetName() + index := -1 + switch { + case strings.HasPrefix(name, headerURLQualifier): + rest := strings.TrimPrefix(name, headerURLQualifier) + position, header, found := strings.Cut(rest, ":") + if !found { + return assetHeaders{}, fmt.Errorf("%s qualifier has no header name", headerURLQualifier) + } + parsed, err := strconv.Atoi(position) + if err != nil || parsed < 0 || parsed >= uris { + return assetHeaders{}, fmt.Errorf("%s names uri %q, which was not supplied", headerURLQualifier, position) + } + index, name = parsed, header + case strings.HasPrefix(name, headerQualifier): + name = strings.TrimPrefix(name, headerQualifier) + default: + continue + } + + if err := validateHeader(name, qualifier.GetValue()); err != nil { + return assetHeaders{}, err + } + count++ + if count > maxAssetHeaders { + return assetHeaders{}, fmt.Errorf("more than %d headers were supplied", maxAssetHeaders) + } + if index < 0 { + headers.generic.Add(name, qualifier.GetValue()) + continue + } + if headers.specific[index] == nil { + headers.specific[index] = http.Header{} + } + headers.specific[index].Add(name, qualifier.GetValue()) + } + return headers, nil +} + +func validateHeader(name, value string) error { + if name == "" { + return fmt.Errorf("a header qualifier has no name") + } + if !httpTokenValid(name) { + return fmt.Errorf("header name %q is not a token", name) + } + if _, refused := refusedHeaders[strings.ToLower(name)]; refused { + return fmt.Errorf("refusing to send a %s header", name) + } + if len(value) > maxAssetHeaderLen { + return fmt.Errorf("the %s header is longer than %d bytes", name, maxAssetHeaderLen) + } + // A newline would let a value inject a header of its own. + if strings.ContainsAny(value, "\r\n\x00") { + return fmt.Errorf("the %s header contains a control character", name) + } + return nil +} + +func httpTokenValid(name string) bool { + for _, character := range name { + if character >= 0x80 || strings.ContainsRune(" \t\"(),/:;<=>?@[\\]{}\x7f", character) || character < 0x21 { + return false + } + } + return true +} + +// forURI returns the headers to send to one of the request's URIs. +func (h assetHeaders) forURI(index int) http.Header { + merged := http.Header{} + for name, values := range h.generic { + merged[name] = append([]string(nil), values...) + } + for name, values := range h.specific[index] { + merged[name] = append([]string(nil), values...) + } + return merged +} + +// sensitiveHeaders must not survive a redirect to another origin, the same rule +// browsers and curl apply. Go drops these itself on a cross-domain redirect, +// but only for the ones it knows about, and only across domains rather than +// origins. +var sensitiveHeaders = []string{"Authorization", "Proxy-Authorization", "Cookie", "Www-Authenticate"} + +func carriesCredential(headers http.Header) bool { + for _, name := range sensitiveHeaders { + if headers.Get(name) != "" { + return true + } + } + return false +} + +// assetRoute is a URI pattern whose credentials this server is permitted to +// forward. Anything an operator has not named is refused rather than fetched +// without its credential, so a private asset never reaches a shared cache. +type assetRoute struct { + host string + wildcard bool + pathPrefix string +} + +// ParseAssetRoutes accepts patterns such as https://ghcr.io/v2/acme/* and +// https://*.example.com/. A trailing * makes the path a prefix; without one the +// match still has to fall on a path segment boundary. +// +// Entries are separated by newlines rather than commas, because a comma is a +// legal URL character and a list of these is read by people. +func ParseAssetRoutes(patterns []string) ([]assetRoute, error) { + routes := make([]assetRoute, 0, len(patterns)) + for _, entry := range patterns { + for _, pattern := range strings.Split(entry, "\n") { + pattern = strings.TrimSpace(pattern) + if pattern == "" { + continue + } + route, err := parseAssetRoute(pattern) + if err != nil { + return nil, err + } + routes = append(routes, route) + } + } + return routes, nil +} + +func parseAssetRoute(pattern string) (assetRoute, error) { + parsed, err := url.Parse(pattern) + if err != nil { + return assetRoute{}, fmt.Errorf("asset route %q is not a URL", pattern) + } + if parsed.Scheme != "https" { + return assetRoute{}, fmt.Errorf("asset route %q must be https", pattern) + } + if parsed.User != nil { + return assetRoute{}, fmt.Errorf("asset route %q must not carry userinfo", pattern) + } + host := strings.ToLower(parsed.Host) + route := assetRoute{host: host, pathPrefix: parsed.Path} + if rest, found := strings.CutPrefix(host, "*."); found { + if rest == "" || !strings.Contains(rest, ".") { + return assetRoute{}, fmt.Errorf("asset route %q must wildcard a domain, not a suffix", pattern) + } + route.host, route.wildcard = rest, true + } + if route.host == "" { + return assetRoute{}, fmt.Errorf("asset route %q has no host", pattern) + } + if route.pathPrefix == "" { + route.pathPrefix = "/" + } + return route, nil +} + +func (r assetRoute) matches(target *url.URL) bool { + host := strings.ToLower(target.Host) + if r.wildcard { + // A label boundary is required, so evil-ghcr.io does not match *.ghcr.io. + if !strings.HasSuffix(host, "."+r.host) { + return false + } + } else if host != r.host { + return false + } + path := target.EscapedPath() + if prefix, found := strings.CutSuffix(r.pathPrefix, "*"); found { + return strings.HasPrefix(path, prefix) + } + if path == r.pathPrefix { + return true + } + // Without a wildcard the prefix only covers whole segments, so /v2/acme + // does not admit /v2/acme-private. + return strings.HasPrefix(path, strings.TrimSuffix(r.pathPrefix, "/")+"/") +} + +func routeAllows(routes []assetRoute, target *url.URL) bool { + for _, route := range routes { + if route.matches(target) { + return true + } + } + return false +} + +// permittedHeaders drops a credential the operator has not opted into sending. +// It reports an error rather than fetching without it, so that a private asset +// is left to Bazel's own downloader instead of landing in a shared cache. +func permittedHeaders(headers http.Header, target *url.URL, routes []assetRoute) (http.Header, error) { + if !carriesCredential(headers) { + return headers, nil + } + if !routeAllows(routes, target) { + return nil, fmt.Errorf( + "refusing to send credentials to %s; add it to asset-header-routes to cache authenticated assets", + safeURIString(target.String()), + ) + } + return headers, nil +} + +// sameOrigin reports whether credentials may be carried from one URL to +// another. Scheme, host and port must all match. +func sameOrigin(from, to *url.URL) bool { + return from.Scheme == to.Scheme && from.Host == to.Host +} + +// stripSensitiveOnRedirect removes credentials once a redirect leaves the +// origin they were issued for. +func stripSensitiveOnRedirect(request *http.Request, via []*http.Request) { + if len(via) == 0 { + return + } + if sameOrigin(via[0].URL, request.URL) { + return + } + for _, name := range sensitiveHeaders { + request.Header.Del(name) + } +} diff --git a/internal/server/asset_headers_test.go b/internal/server/asset_headers_test.go new file mode 100644 index 0000000..9be9643 --- /dev/null +++ b/internal/server/asset_headers_test.go @@ -0,0 +1,154 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "net/url" + "os" + "strings" + "testing" + + remoteasset "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/asset/v1" +) + +func qualifier(name, value string) *remoteasset.Qualifier { + return remoteasset.Qualifier_builder{Name: name, Value: value}.Build() +} + +// A URI-specific header must win over the generic one, and a generic header +// must reach every URI. +func TestAssetHeadersPreferTheUriSpecificValue(t *testing.T) { + headers, err := parseAssetHeaders([]*remoteasset.Qualifier{ + qualifier("http_header:Accept", "*/*"), + qualifier("http_header:Authorization", "Bearer generic"), + qualifier("http_header_url:1:Authorization", "Bearer second"), + }, 2) + if err != nil { + t.Fatal(err) + } + if got := headers.forURI(0).Get("Authorization"); got != "Bearer generic" { + t.Fatalf("uri 0 authorization = %q", got) + } + if got := headers.forURI(1).Get("Authorization"); got != "Bearer second" { + t.Fatalf("uri 1 authorization = %q", got) + } + for _, index := range []int{0, 1} { + if got := headers.forURI(index).Get("Accept"); got != "*/*" { + t.Fatalf("uri %d lost the generic header: %q", index, got) + } + } +} + +// Merging must not let one URI's headers leak into another's. +func TestAssetHeadersDoNotLeakBetweenUris(t *testing.T) { + headers, err := parseAssetHeaders([]*remoteasset.Qualifier{ + qualifier("http_header_url:0:Authorization", "Bearer first"), + }, 2) + if err != nil { + t.Fatal(err) + } + if got := headers.forURI(1).Get("Authorization"); got != "" { + t.Fatalf("uri 1 received uri 0's credential: %q", got) + } +} + +func TestAssetHeadersRejectUnusableQualifiers(t *testing.T) { + cases := map[string][]*remoteasset.Qualifier{ + "unknown uri": {qualifier("http_header_url:7:Accept", "*/*")}, + "negative uri": {qualifier("http_header_url:-1:Accept", "*/*")}, + "no header name": {qualifier("http_header_url:0", "*/*")}, + "empty name": {qualifier("http_header:", "*/*")}, + "not a token": {qualifier("http_header:Bad Header", "*/*")}, + "header injection": {qualifier("http_header:Accept", "*/*\r\nX-Evil: 1")}, + "routing header": {qualifier("http_header:Host", "evil.example")}, + "framing header": {qualifier("http_header:Content-Length", "0")}, + "oversized value": {qualifier("http_header:Accept", strings.Repeat("a", maxAssetHeaderLen+1))}, + } + for name, qualifiers := range cases { + if _, err := parseAssetHeaders(qualifiers, 1); err == nil { + t.Errorf("%s was accepted", name) + } + } +} + +func TestAssetHeadersAreBounded(t *testing.T) { + qualifiers := make([]*remoteasset.Qualifier, 0, maxAssetHeaders+1) + for index := 0; index <= maxAssetHeaders; index++ { + qualifiers = append(qualifiers, qualifier("http_header:X-Many-"+string(rune('a'+index%26)), "1")) + } + if _, err := parseAssetHeaders(qualifiers, 1); err == nil { + t.Fatal("an unbounded number of headers was accepted") + } +} + +// A credential issued for one origin must not follow a redirect to another, +// which is how a hostile origin would harvest it. +func TestSensitiveHeadersDoNotSurviveACrossOriginRedirect(t *testing.T) { + origin := func(raw string) *url.URL { + parsed, err := url.Parse(raw) + if err != nil { + t.Fatal(err) + } + return parsed + } + cases := []struct { + from, to string + kept bool + }{ + {"https://ghcr.io/a", "https://ghcr.io/b", true}, + {"https://ghcr.io/a", "https://evil.example/b", false}, + {"https://ghcr.io/a", "https://ghcr.io.evil.example/b", false}, + {"https://ghcr.io/a", "https://ghcr.io:8443/b", false}, + } + for _, testCase := range cases { + request := &http.Request{URL: origin(testCase.to), Header: http.Header{}} + request.Header.Set("Authorization", "Bearer secret") + request.Header.Set("Cookie", "session=secret") + request.Header.Set("Accept", "*/*") + stripSensitiveOnRedirect(request, []*http.Request{{URL: origin(testCase.from)}}) + + if kept := request.Header.Get("Authorization") != ""; kept != testCase.kept { + t.Errorf("%s -> %s: authorization kept = %v, want %v", testCase.from, testCase.to, kept, testCase.kept) + } + if kept := request.Header.Get("Cookie") != ""; kept != testCase.kept { + t.Errorf("%s -> %s: cookie kept = %v, want %v", testCase.from, testCase.to, kept, testCase.kept) + } + // A header that carries no credential is never the problem. + if request.Header.Get("Accept") != "*/*" { + t.Errorf("%s -> %s: dropped a harmless header", testCase.from, testCase.to) + } + } +} + +// The headers have to reach the origin, or the whole feature is inert. +func TestFetchSendsTheDeclaredHeadersToTheOrigin(t *testing.T) { + var seen http.Header + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seen = r.Header.Clone() + _, _ = w.Write([]byte("asset body")) + })) + defer origin.Close() + + backend := newMemoryBackend() + server := testServer(t, backend, func(cfg *Config) { + cfg.AssetClient = origin.Client() + }) + blob := []byte("asset body") + reference := referenceFor(blob) + headers := http.Header{} + headers.Set("Authorization", "Bearer secret") + + path, _, err := server.downloadAsset( + t.Context(), + origin.URL, + assetChecksum{algorithm: sha256Algorithm, hash: reference.hash}, + headers, + ) + if err != nil { + t.Fatal(err) + } + defer os.Remove(path) + if got := seen.Get("Authorization"); got != "Bearer secret" { + t.Fatalf("origin saw authorization %q", got) + } +} diff --git a/internal/server/asset_routes_test.go b/internal/server/asset_routes_test.go new file mode 100644 index 0000000..26087dd --- /dev/null +++ b/internal/server/asset_routes_test.go @@ -0,0 +1,159 @@ +package server + +import ( + "net/http" + "net/url" + "strings" + "testing" +) + +func mustRoutes(t *testing.T, patterns ...string) []assetRoute { + t.Helper() + routes, err := ParseAssetRoutes(patterns) + if err != nil { + t.Fatal(err) + } + return routes +} + +func mustURL(t *testing.T, raw string) *url.URL { + t.Helper() + parsed, err := url.Parse(raw) + if err != nil { + t.Fatal(err) + } + return parsed +} + +func TestAssetRoutesMatchOnlyWhatTheyName(t *testing.T) { + routes := mustRoutes(t, + "https://ghcr.io/v2/acme/*", + "https://registry.example.com/", + "https://*.jfrog.example/artifactory/", + ) + allowed := []string{ + "https://ghcr.io/v2/acme/app/manifests/sha256:abc", + "https://ghcr.io/v2/acme/", + "https://registry.example.com/", + "https://registry.example.com/v2/anything", + "https://team.jfrog.example/artifactory/repo/file.tgz", + "https://a.b.jfrog.example/artifactory/", + } + for _, uri := range allowed { + if !routeAllows(routes, mustURL(t, uri)) { + t.Errorf("%s should be allowed", uri) + } + } + + refused := []string{ + // A different repository on the same registry. + "https://ghcr.io/v2/other/app/manifests/sha256:abc", + // Prefix without a segment boundary. + "https://ghcr.io/v2/acme-private/app", + // Lookalike hosts. + "https://ghcr.io.evil.example/v2/acme/app", + "https://evil-ghcr.io/v2/acme/app", + "https://notregistry.example.com/", + // The wildcard covers subdomains, not the apex or a suffix match. + "https://jfrog.example/artifactory/", + "https://eviljfrog.example/artifactory/", + // A port change is a different origin. + "https://registry.example.com:8443/", + // Right host, wrong path. + "https://team.jfrog.example/private/file.tgz", + } + for _, uri := range refused { + if routeAllows(routes, mustURL(t, uri)) { + t.Errorf("%s should be refused", uri) + } + } +} + +// A comma is a legal URL character, so entries are separated by newlines and a +// pattern containing one has to survive. +func TestAssetRoutesAreNewlineSeparated(t *testing.T) { + routes, err := ParseAssetRoutes([]string{ + "\n https://ghcr.io/v2/acme/* \r\n\nhttps://registry.example.com/a,b/\n", + }) + if err != nil { + t.Fatal(err) + } + if len(routes) != 2 { + t.Fatalf("parsed %d routes, want 2", len(routes)) + } + if !routeAllows(routes, mustURL(t, "https://ghcr.io/v2/acme/app")) { + t.Error("the first route was lost to whitespace") + } + if !routeAllows(routes, mustURL(t, "https://registry.example.com/a,b/thing")) { + t.Error("a comma inside a pattern was treated as a separator") + } +} + +func TestAssetRoutesRejectUnusablePatterns(t *testing.T) { + for _, pattern := range []string{ + "http://ghcr.io/", // not https + "ghcr.io/v2/", // no scheme + "https://user:pass@ghcr.io/", // userinfo + "https://*./", // wildcards a suffix, not a domain + "https://*.io/", // wildcards a public suffix + "https:///v2/", // no host + } { + if _, err := ParseAssetRoutes([]string{pattern}); err == nil { + t.Errorf("%q was accepted", pattern) + } + } +} + +// Nothing is allowed until an operator says so, so a private asset is left to +// Bazel rather than landing in a cache the whole repository reads. +func TestCredentialsAreRefusedUntilARouteAllowsThem(t *testing.T) { + credentialed := http.Header{} + credentialed.Set("Authorization", "Bearer secret") + target := mustURL(t, "https://ghcr.io/v2/acme/app/blobs/sha256:abc") + + if _, err := permittedHeaders(credentialed, target, nil); err == nil { + t.Fatal("credentials were sent with no route configured") + } + if _, err := permittedHeaders(credentialed, target, mustRoutes(t, "https://ghcr.io/v2/other/*")); err == nil { + t.Fatal("credentials were sent to a route that was not allowed") + } + got, err := permittedHeaders(credentialed, target, mustRoutes(t, "https://ghcr.io/v2/acme/*")) + if err != nil { + t.Fatal(err) + } + if got.Get("Authorization") != "Bearer secret" { + t.Fatalf("an allowed route lost its credential: %q", got.Get("Authorization")) + } +} + +// A header that carries no credential says nothing about whether the content is +// private, so it needs no opt-in. +func TestHeadersWithoutCredentialsNeedNoRoute(t *testing.T) { + plain := http.Header{} + plain.Set("Accept", "application/vnd.oci.image.manifest.v1+json") + got, err := permittedHeaders(plain, mustURL(t, "https://ghcr.io/v2/acme/app"), nil) + if err != nil { + t.Fatal(err) + } + if got.Get("Accept") == "" { + t.Fatal("a harmless header was dropped") + } +} + +// The refusal is what a person acts on, so it has to say what to change. +func TestRefusalNamesTheSettingAndNotTheCredential(t *testing.T) { + credentialed := http.Header{} + credentialed.Set("Authorization", "Bearer super-secret-token") + _, err := permittedHeaders(credentialed, mustURL(t, "https://ghcr.io/v2/acme/app?token=leaky"), nil) + if err == nil { + t.Fatal("expected a refusal") + } + if !strings.Contains(err.Error(), "asset-header-routes") { + t.Fatalf("the refusal does not say what to change: %v", err) + } + for _, secret := range []string{"super-secret-token", "leaky"} { + if strings.Contains(err.Error(), secret) { + t.Fatalf("the refusal leaked %q: %v", secret, err) + } + } +} diff --git a/internal/server/block_codec.go b/internal/server/block_codec.go new file mode 100644 index 0000000..c44bacb --- /dev/null +++ b/internal/server/block_codec.go @@ -0,0 +1,113 @@ +package server + +import ( + "errors" + "fmt" + + "github.com/klauspost/compress/zstd" +) + +// Block encodings recorded in the manifest. An empty encoding means the block +// holds the object's bytes verbatim, which keeps older manifests readable. +const ( + blockEncodingRaw = "" + blockEncodingZstd = "zstd" +) + +const ( + // Below this size a frame header costs more than compression saves. + minCompressibleBlockSize = 256 + // Compressed output must be at least this much smaller to be worth the + // decompression on every later read. + maxUsefulCompressionRatio = 0.95 + // Large objects are sampled first so an incompressible one, such as a + // gzipped OCI layer, is rejected after a few hundred KB rather than after + // compressing hundreds of MB. + compressionProbeSize = 256 << 10 + compressionProbeThreshold = 4 * compressionProbeSize +) + +// blockCodec compresses individual pack blocks. Compressing each block on its +// own keeps the CARv2 index meaningful: a reader restores one block and +// decompresses only that block, instead of expanding a whole pack to serve one +// object. +type blockCodec struct { + encoder *zstd.Encoder + decoder *zstd.Decoder + enabled bool +} + +func newBlockCodec(enabled bool, level, maxBlobSize int64) (*blockCodec, error) { + // Both are safe for concurrent EncodeAll/DecodeAll use. + encoder, err := zstd.NewWriter( + nil, + zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(int(level))), + zstd.WithEncoderConcurrency(1), + ) + if err != nil { + return nil, fmt.Errorf("create zstd encoder: %w", err) + } + decoder, err := zstd.NewReader( + nil, + zstd.WithDecoderConcurrency(1), + zstd.WithDecoderMaxMemory(uint64(maxBlobSize)), + ) + if err != nil { + return nil, fmt.Errorf("create zstd decoder: %w", err) + } + return &blockCodec{encoder: encoder, decoder: decoder, enabled: enabled}, nil +} + +// encode returns the bytes to store and the encoding to record. It falls back +// to the original bytes whenever compression does not pay for itself. +func (c *blockCodec) encode(data []byte) ([]byte, string) { + if !c.enabled || len(data) < minCompressibleBlockSize { + return data, blockEncodingRaw + } + if len(data) > compressionProbeThreshold && !c.probeWorthwhile(data) { + return data, blockEncodingRaw + } + compressed := c.encoder.EncodeAll(data, nil) + if float64(len(compressed)) > float64(len(data))*maxUsefulCompressionRatio { + return data, blockEncodingRaw + } + return compressed, blockEncodingZstd +} + +func (c *blockCodec) probeWorthwhile(data []byte) bool { + sample := data[:compressionProbeSize] + compressed := c.encoder.EncodeAll(sample, nil) + return float64(len(compressed)) <= float64(len(sample))*maxUsefulCompressionRatio +} + +// decode restores a stored block. plainSize comes from the manifest and bounds +// the output, so a corrupt or hostile frame cannot expand without limit. +func (c *blockCodec) decode(stored []byte, encoding string, plainSize int64) ([]byte, error) { + switch encoding { + case blockEncodingRaw: + return stored, nil + case blockEncodingZstd: + if plainSize < 0 { + return nil, errors.New("compressed block has no declared size") + } + plain, err := c.decoder.DecodeAll(stored, make([]byte, 0, plainSize)) + if err != nil { + return nil, fmt.Errorf("decompress block: %w", err) + } + if int64(len(plain)) != plainSize { + return nil, fmt.Errorf("decompressed block is %d bytes; manifest declares %d", len(plain), plainSize) + } + return plain, nil + default: + return nil, fmt.Errorf("unsupported block encoding %q", encoding) + } +} + +func (c *blockCodec) close() { + _ = c.encoder.Close() + c.decoder.Close() +} + +func validBlockEncoding(encoding string) bool { + return encoding == blockEncodingRaw || encoding == blockEncodingZstd +} diff --git a/internal/server/block_codec_test.go b/internal/server/block_codec_test.go new file mode 100644 index 0000000..84e6a5a --- /dev/null +++ b/internal/server/block_codec_test.go @@ -0,0 +1,203 @@ +package server + +import ( + "bytes" + "crypto/rand" + "net/http" + "strings" + "testing" + "time" +) + +func testPackedServerWithCompression(t *testing.T, backend *memoryBackend, maxBlobSize int64, enabled bool) *Server { + t.Helper() + return testServer(t, backend, func(cfg *Config) { + cfg.Catalog = memoryCatalog{backend: backend} + cfg.MaxBlobSize = maxBlobSize + cfg.PackSize = maxBlobSize + cfg.PackFlushInterval = time.Hour + cfg.PackCompression = enabled + cfg.MaxManifests = 100 + }) +} + +func packBytes(t *testing.T, backend *memoryBackend) int { + t.Helper() + backend.mu.Lock() + defer backend.mu.Unlock() + total := 0 + for key, value := range backend.objects { + if strings.Contains(key, "-car-pack-v1-") { + total += len(value) + } + } + return total +} + +func TestPackedBlocksAreCompressedAndRestoredExactly(t *testing.T) { + const size = 256 << 10 + payload := bytes.Repeat([]byte("bazel remote cache payload; "), size/28) + backend := newMemoryBackend() + seed := testPackedServerWithCompression(t, backend, 8<<20, true) + if response := putCacheObject(seed, "/cas/"+digest(payload), payload); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + closePackedServer(t, seed) + + stats := seed.Snapshot() + if stats.CompressedBlocks != 1 || stats.CompressionSavedBytes == 0 { + t.Fatalf("block was not compressed: %+v", stats) + } + if stored := packBytes(t, backend); stored >= len(payload)/2 { + t.Fatalf("pack holds %d bytes for a %d byte payload", stored, len(payload)) + } + + restore := testPackedServerWithCompression(t, backend, 8<<20, true) + defer closePackedServer(t, restore) + response := readCacheObject(restore, "/cas/"+digest(payload)) + if response.Code != http.StatusOK { + t.Fatalf("CAS GET = %d", response.Code) + } + if !bytes.Equal(response.Body.Bytes(), payload) { + t.Fatal("restored payload differs from the published payload") + } +} + +func TestPackedIncompressibleBlocksAreStoredVerbatim(t *testing.T) { + payload := make([]byte, 128<<10) + if _, err := rand.Read(payload); err != nil { + t.Fatal(err) + } + backend := newMemoryBackend() + seed := testPackedServerWithCompression(t, backend, 8<<20, true) + if response := putCacheObject(seed, "/cas/"+digest(payload), payload); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + closePackedServer(t, seed) + if stats := seed.Snapshot(); stats.CompressedBlocks != 0 { + t.Fatalf("random data was stored compressed: %+v", stats) + } + + restore := testPackedServerWithCompression(t, backend, 8<<20, true) + defer closePackedServer(t, restore) + response := readCacheObject(restore, "/cas/"+digest(payload)) + if response.Code != http.StatusOK || !bytes.Equal(response.Body.Bytes(), payload) { + t.Fatalf("CAS GET = %d", response.Code) + } +} + +func TestPackedCompressedBlocksAreReadableWithoutCompressionEnabled(t *testing.T) { + payload := bytes.Repeat([]byte("readable by a reader that never compresses; "), 4096) + backend := newMemoryBackend() + seed := testPackedServerWithCompression(t, backend, 8<<20, true) + if response := putCacheObject(seed, "/cas/"+digest(payload), payload); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + closePackedServer(t, seed) + + // Disabling compression must only stop writing it, never stop reading it. + restore := testPackedServerWithCompression(t, backend, 8<<20, false) + defer closePackedServer(t, restore) + response := readCacheObject(restore, "/cas/"+digest(payload)) + if response.Code != http.StatusOK || !bytes.Equal(response.Body.Bytes(), payload) { + t.Fatalf("CAS GET = %d", response.Code) + } +} + +func TestPackedTamperedCompressedBlockIsACacheMiss(t *testing.T) { + payload := bytes.Repeat([]byte("tamper detection through the block CID; "), 4096) + backend := newMemoryBackend() + seed := testPackedServerWithCompression(t, backend, 8<<20, true) + if response := putCacheObject(seed, "/cas/"+digest(payload), payload); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + closePackedServer(t, seed) + + backend.mu.Lock() + for key, value := range backend.objects { + if strings.Contains(key, "-car-pack-v1-") { + value[len(value)-1] ^= 0xff + } + } + backend.mu.Unlock() + + restore := testPackedServerWithCompression(t, backend, 8<<20, true) + defer closePackedServer(t, restore) + if response := readCacheObject(restore, "/cas/"+digest(payload)); response.Code != http.StatusNotFound { + t.Fatalf("tampered pack = %d", response.Code) + } +} + +func TestBlockCodecSkipsSmallAndIncompressibleInput(t *testing.T) { + codec, err := newBlockCodec(true, defaultPackCompressionLevel, 8<<20) + if err != nil { + t.Fatal(err) + } + defer codec.close() + + small := bytes.Repeat([]byte("a"), minCompressibleBlockSize-1) + if _, encoding := codec.encode(small); encoding != blockEncodingRaw { + t.Fatalf("small input encoding = %q", encoding) + } + random := make([]byte, compressionProbeThreshold+1) + if _, err := rand.Read(random); err != nil { + t.Fatal(err) + } + if _, encoding := codec.encode(random); encoding != blockEncodingRaw { + t.Fatalf("incompressible input encoding = %q", encoding) + } + + compressible := bytes.Repeat([]byte("compress me please "), 1024) + stored, encoding := codec.encode(compressible) + if encoding != blockEncodingZstd || len(stored) >= len(compressible) { + t.Fatalf("compressible input encoding = %q, %d bytes", encoding, len(stored)) + } + plain, err := codec.decode(stored, encoding, int64(len(compressible))) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(plain, compressible) { + t.Fatal("round trip changed the block") + } + if _, err := codec.decode(stored, encoding, int64(len(compressible))-1); err == nil { + t.Fatal("a size disagreeing with the manifest was accepted") + } + if _, err := codec.decode(stored, "brotli", int64(len(compressible))); err == nil { + t.Fatal("an unknown encoding was accepted") + } +} + +func TestManifestFormatOneIsStillReadable(t *testing.T) { + casDigest := digest([]byte("legacy")) + casCID, err := rawCIDForDigest(casDigest) + if err != nil { + t.Fatal(err) + } + packID := digest([]byte("legacy pack")) + legacy := manifest{ + Version: minManifestFormatVersion, + Parents: []string{}, + Packs: []packDescriptor{{ID: packID, Key: packKeyFor("test", packID), Size: 10}}, + CAS: []manifestObject{{ + Digest: casDigest, + CID: casCID.String(), + Block: casCID.String(), + PackID: packID, + Size: 6, + }}, + } + encoded, manifestCID, err := encodeManifest(legacy) + if err != nil { + t.Fatal(err) + } + decoded, err := decodeManifest(encoded, manifestCID) + if err != nil { + t.Fatal(err) + } + if len(decoded.CAS) != 1 { + t.Fatalf("decoded %d CAS entries", len(decoded.CAS)) + } + if decoded.CAS[0].Encoding != blockEncodingRaw || decoded.CAS[0].Block != casCID.String() { + t.Fatalf("format 1 entry did not default to a verbatim block: %+v", decoded.CAS[0]) + } +} diff --git a/internal/server/file_io.go b/internal/server/file_io.go new file mode 100644 index 0000000..e6228a7 --- /dev/null +++ b/internal/server/file_io.go @@ -0,0 +1,88 @@ +package server + +import ( + "context" + "io" + "sync/atomic" +) + +// maxConcurrentFileIO bounds the request-driven filesystem calls in flight at +// once. Every blocking file syscall pins an OS thread, and Bazel fans uploads +// and downloads out to roughly 10k concurrent streams (100 connections of 100 +// streams each). Left unbounded, a large burst on a slow runner disk exceeds the +// Go runtime's 10k-thread limit and aborts the process with "fatal error: +// thread exhaustion". A goroutine queued on the gate holds no thread. +const maxConcurrentFileIO = 64 + +// ioGate admits a bounded number of blocking filesystem calls. Slots are held +// only for the duration of each call, never across network I/O, so a slow +// client cannot starve other requests. +type ioGate struct { + slots chan struct{} + active atomic.Int64 + peak atomic.Int64 +} + +func newIOGate(limit int) *ioGate { + return &ioGate{slots: make(chan struct{}, limit)} +} + +func (g *ioGate) enter(ctx context.Context) error { + select { + case g.slots <- struct{}{}: + case <-ctx.Done(): + return ctx.Err() + } + active := g.active.Add(1) + for { + peak := g.peak.Load() + if active <= peak || g.peak.CompareAndSwap(peak, active) { + return nil + } + } +} + +func (g *ioGate) exit() { + g.active.Add(-1) + <-g.slots +} + +// do runs call while holding a slot. Cleanup that must happen regardless of +// cancellation should pass context.Background. +func (g *ioGate) do(ctx context.Context, call func() error) error { + if err := g.enter(ctx); err != nil { + return err + } + defer g.exit() + return call() +} + +// gatedWriter holds a gate slot for each write to the underlying file. +type gatedWriter struct { + ctx context.Context + gate *ioGate + w io.Writer +} + +func (w gatedWriter) Write(p []byte) (int, error) { + if err := w.gate.enter(w.ctx); err != nil { + return 0, err + } + defer w.gate.exit() + return w.w.Write(p) +} + +// gatedReader holds a gate slot for each read from the underlying file. +type gatedReader struct { + ctx context.Context + gate *ioGate + r io.Reader +} + +func (r gatedReader) Read(p []byte) (int, error) { + if err := r.gate.enter(r.ctx); err != nil { + return 0, err + } + defer r.gate.exit() + return r.r.Read(p) +} diff --git a/internal/server/file_io_test.go b/internal/server/file_io_test.go new file mode 100644 index 0000000..5f412c0 --- /dev/null +++ b/internal/server/file_io_test.go @@ -0,0 +1,447 @@ +package server + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/google/bytestream" +) + +func TestIOGateBoundsConcurrentCalls(t *testing.T) { + const limit = 3 + gate := newIOGate(limit) + var active, peak atomic.Int64 + var wg sync.WaitGroup + for range 50 { + wg.Go(func() { + err := gate.do(t.Context(), func() error { + now := active.Add(1) + defer active.Add(-1) + for { + old := peak.Load() + if now <= old || peak.CompareAndSwap(old, now) { + break + } + } + time.Sleep(time.Millisecond) + return nil + }) + if err != nil { + t.Error(err) + } + }) + } + wg.Wait() + if got := peak.Load(); got > limit { + t.Fatalf("observed %d concurrent calls, limit is %d", got, limit) + } + if got := gate.peak.Load(); got != peak.Load() { + t.Fatalf("gate recorded peak %d, observed %d", got, peak.Load()) + } +} + +func TestIOGateAbandonsQueuedCallOnCancellation(t *testing.T) { + gate := newIOGate(1) + if err := gate.enter(t.Context()); err != nil { + t.Fatal(err) + } + defer gate.exit() + + ctx, cancel := context.WithCancel(t.Context()) + cancel() + called := false + err := gate.do(ctx, func() error { + called = true + return nil + }) + if !errors.Is(err, context.Canceled) || called { + t.Fatalf("err = %v, called = %t; want context.Canceled without running the call", err, called) + } +} + +func spoolFiles(t *testing.T, dir string) []string { + t.Helper() + matches, err := filepath.Glob(filepath.Join(dir, "upload-*")) + if err != nil { + t.Fatal(err) + } + return matches +} + +func TestUploadsWaitForFileIOSlot(t *testing.T) { + server := testServer(t, newMemoryBackend(), nil) + server.fileIO = newIOGate(1) + client := bytestream.NewByteStreamClient(testGRPCConn(t, server)) + + // Occupy the only slot, as a burst of other uploads would. + if err := server.fileIO.enter(t.Context()); err != nil { + t.Fatal(err) + } + held := true + defer func() { + if held { + server.fileIO.exit() + } + }() + + data := []byte("queued behind file io") + reference := digestReference{hash: digest(data), size: int64(len(data))} + done := make(chan error, 1) + go func() { + stream, err := client.Write(t.Context()) + if err == nil { + err = stream.Send(bytestream.WriteRequest_builder{ + ResourceName: writeResource(reference), + Data: data, + FinishWrite: true, + }.Build()) + } + if err == nil { + _, err = stream.CloseAndRecv() + } + done <- err + }() + + select { + case err := <-done: + t.Fatalf("upload finished while file io was saturated: %v", err) + case <-time.After(100 * time.Millisecond): + } + if files := spoolFiles(t, server.cfg.CacheDir); len(files) != 0 { + t.Fatalf("spool files created while file io was saturated: %v", files) + } + + held = false + server.fileIO.exit() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("upload did not resume after a file io slot was released") + } + if got := server.Snapshot().BytesReceived; got != uint64(len(data)) { + t.Fatalf("bytes received = %d, want %d", got, len(data)) + } +} + +func TestQueuedUploadLeavesNoSpoolFileWhenCancelled(t *testing.T) { + server := testServer(t, newMemoryBackend(), nil) + server.fileIO = newIOGate(1) + if err := server.fileIO.enter(t.Context()); err != nil { + t.Fatal(err) + } + defer server.fileIO.exit() + + ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond) + defer cancel() + data := []byte("abandoned") + err := server.writeObject(ctx, "cas", digest(data), bytes.NewReader(data), int64(len(data))) + if !errors.Is(err, errLocalFailure) { + t.Fatalf("err = %v, want errLocalFailure", err) + } + if files := spoolFiles(t, server.cfg.CacheDir); len(files) != 0 { + t.Fatalf("cancelled upload left spool files: %v", files) + } +} + +// Bazel fans uploads out to thousands of concurrent ByteStream writes. Spool +// filesystem calls must stay within the gate however wide the fan-out, because +// each one in flight pins an OS thread. +func TestConcurrentUploadBurstStaysWithinFileIOLimit(t *testing.T) { + const limit, uploads, chunk = 4, 500, 4 * 1024 + backend := newMemoryBackend() + server := testServer(t, backend, func(cfg *Config) { + cfg.Catalog = memoryCatalog{backend: backend} + cfg.MaxBlobSize = 64 * 1024 + cfg.PackSize = 16 * 1024 * 1024 + cfg.PackFlushInterval = time.Hour + cfg.MaxManifests = 100 + }) + defer closePackedServer(t, server) + server.fileIO = newIOGate(limit) + client := bytestream.NewByteStreamClient(testGRPCConn(t, server)) + + var wg sync.WaitGroup + var sent atomic.Uint64 + for i := range uploads { + wg.Go(func() { + data := bytes.Repeat([]byte(fmt.Sprintf("blob-%04d|", i)), 3*chunk/10) + sum := sha256.Sum256(data) + reference := digestReference{hash: hex.EncodeToString(sum[:]), size: int64(len(data))} + stream, err := client.Write(t.Context()) + if err != nil { + t.Error(err) + return + } + for offset := 0; offset < len(data); offset += chunk { + end := min(offset+chunk, len(data)) + request := bytestream.WriteRequest_builder{ + Data: data[offset:end], + WriteOffset: int64(offset), + FinishWrite: end == len(data), + } + if offset == 0 { + request.ResourceName = writeResource(reference) + } + if err := stream.Send(request.Build()); err != nil { + t.Error(err) + return + } + } + if _, err := stream.CloseAndRecv(); err != nil { + t.Error(err) + return + } + sent.Add(uint64(len(data))) + }) + } + wg.Wait() + + if peak := server.fileIO.peak.Load(); peak > limit || peak == 0 { + t.Fatalf("peak concurrent file io = %d, want 1..%d", peak, limit) + } + if active := server.fileIO.active.Load(); active != 0 { + t.Fatalf("%d file io slots leaked", active) + } + if got, want := server.Snapshot().BytesReceived, sent.Load(); got != want { + t.Fatalf("bytes received = %d, want %d", got, want) + } +} + +func burstPackedConfig(backend *memoryBackend) func(*Config) { + return func(cfg *Config) { + cfg.Catalog = memoryCatalog{backend: backend} + // A restored pack is bounded by the blob size limit too. + cfg.MaxBlobSize = 16 * 1024 * 1024 + cfg.PackSize = 16 * 1024 * 1024 + cfg.PackFlushInterval = time.Hour + cfg.MaxManifests = 100 + } +} + +func TestPackedSpoolReaderClosesBeforeDeletion(t *testing.T) { + backend := newMemoryBackend() + server := testServer(t, backend, burstPackedConfig(backend)) + t.Cleanup(func() { closePackedServer(t, server) }) + data := []byte("packed spool reader") + if err := server.writeObject(t.Context(), "cas", digest(data), bytes.NewReader(data), int64(len(data))); err != nil { + t.Fatal(err) + } + reader, _, err := server.openObject(t.Context(), "cas", digest(data)) + if err != nil { + t.Fatal(err) + } + defer reader.Close() + if runtime.GOOS == "windows" { + if server.objectFilesMu.TryLock() { + server.objectFilesMu.Unlock() + t.Fatal("open Windows spool reader did not hold the deletion lock") + } + } + got, err := io.ReadAll(server.gateReader(t.Context(), reader)) + if err != nil || !bytes.Equal(got, data) { + t.Fatalf("read spool = %q, %v", got, err) + } + if err := reader.Close(); err != nil { + t.Fatal(err) + } + if !server.objectFilesMu.TryLock() { + t.Fatal("closed spool reader still holds the deletion lock") + } + server.objectFilesMu.Unlock() + if err := server.packs.flush(t.Context(), true); err != nil { + t.Fatal(err) + } + if files := spoolFiles(t, server.cfg.CacheDir); len(files) != 0 { + t.Fatalf("packed publication left object spool files: %v", files) + } +} + +// restoredPackedServer seeds one pack with count blobs and returns a fresh +// server that can only serve them by restoring that pack. +func restoredPackedServer(t *testing.T, count int) (*Server, [][]byte) { + t.Helper() + backend := newMemoryBackend() + seed := testServer(t, backend, burstPackedConfig(backend)) + blobs := make([][]byte, count) + for i := range blobs { + blobs[i] = bytes.Repeat([]byte(fmt.Sprintf("packed-%04d|", i)), 100) + err := seed.writeObject(t.Context(), "cas", digest(blobs[i]), bytes.NewReader(blobs[i]), int64(len(blobs[i]))) + if err != nil { + t.Fatal(err) + } + } + closePackedServer(t, seed) + + restore := testServer(t, backend, burstPackedConfig(backend)) + t.Cleanup(func() { closePackedServer(t, restore) }) + return restore, blobs +} + +func readBlob(t *testing.T, client bytestream.ByteStreamClient, data []byte) ([]byte, error) { + t.Helper() + reference := digestReference{hash: digest(data), size: int64(len(data))} + stream, err := client.Read(t.Context(), bytestream.ReadRequest_builder{ + ResourceName: readResource(reference), + }.Build()) + if err != nil { + return nil, err + } + var received []byte + for { + response, err := stream.Recv() + if err == io.EOF { + return received, nil + } + if err != nil { + return nil, err + } + received = append(received, response.GetData()...) + } +} + +func packedObjectFiles(t *testing.T, dir string) []string { + t.Helper() + matches, err := filepath.Glob(filepath.Join(dir, "packed-object-*")) + if err != nil { + t.Fatal(err) + } + return matches +} + +// Reopening a pack per read re-indexed the whole archive and spent several +// blocking syscalls on every lookup, which made read bursts pin thousands of +// threads. Once restored, a pack must serve every later read from one reader. +func TestPackedReadsShareOneReaderPerPack(t *testing.T) { + server, blobs := restoredPackedServer(t, 3) + if _, err := server.readObjectBytes(t.Context(), "cas", digest(blobs[0])); err != nil { + t.Fatal(err) + } + server.packs.mu.Lock() + if len(server.packs.loadedPacks) != 1 { + t.Fatalf("loaded %d packs, want 1", len(server.packs.loadedPacks)) + } + for _, pack := range server.packs.loadedPacks { + // Unix permits unlinking a mapped file; Windows keeps its path until + // the reader closes. Both must reuse the same restored reader. + if runtime.GOOS != "windows" { + if err := os.Remove(pack.path); err != nil { + t.Fatal(err) + } + } + } + server.packs.mu.Unlock() + + for _, blob := range blobs[1:] { + data, err := server.readObjectBytes(t.Context(), "cas", digest(blob)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(data, blob) { + t.Fatal("packed read returned the wrong bytes") + } + } + if downloads := server.Snapshot().PackDownloads; downloads != 1 { + t.Fatalf("pack downloads = %d, want 1", downloads) + } +} + +func TestPackedReadsAvoidFileIOForRestoredObjects(t *testing.T) { + server, blobs := restoredPackedServer(t, 2) + client := bytestream.NewByteStreamClient(testGRPCConn(t, server)) + // Restore the pack first so the gate only blocks file-backed operations. + if _, err := readBlob(t, client, blobs[0]); err != nil { + t.Fatal(err) + } + before := len(packedObjectFiles(t, server.cfg.CacheDir)) + if before != 0 { + t.Fatalf("pack restore created %d packed-object files before the second read", before) + } + + server.fileIO = newIOGate(1) + if err := server.fileIO.enter(t.Context()); err != nil { + t.Fatal(err) + } + held := true + defer func() { + if held { + server.fileIO.exit() + } + }() + + type result struct { + data []byte + err error + } + done := make(chan result, 1) + go func() { + data, err := readBlob(t, client, blobs[1]) + done <- result{data, err} + }() + + select { + case got := <-done: + if got.err != nil { + t.Fatal(got.err) + } + if !bytes.Equal(got.data, blobs[1]) { + t.Fatal("read returned the wrong bytes") + } + case <-time.After(5 * time.Second): + t.Fatal("packed object read waited for a file io slot") + } + if after := len(packedObjectFiles(t, server.cfg.CacheDir)); after != before { + t.Fatalf("read created %d packed-object files", after-before) + } + + held = false + server.fileIO.exit() +} + +// Restored objects are served from decoded pack data without request-driven +// filesystem operations, even when Bazel fans reads out widely. +func TestConcurrentPackedReadBurstDoesNotUseFileIO(t *testing.T) { + const limit, reads = 4, 500 + server, blobs := restoredPackedServer(t, reads) + server.fileIO = newIOGate(limit) + client := bytestream.NewByteStreamClient(testGRPCConn(t, server)) + + var wg sync.WaitGroup + for _, blob := range blobs { + wg.Go(func() { + data, err := readBlob(t, client, blob) + if err != nil { + t.Error(err) + return + } + if !bytes.Equal(data, blob) { + t.Error("read returned the wrong bytes") + } + }) + } + wg.Wait() + + if peak := server.fileIO.peak.Load(); peak != 0 { + t.Fatalf("packed reads used %d concurrent file io slots, want none (limit %d)", peak, limit) + } + if active := server.fileIO.active.Load(); active != 0 { + t.Fatalf("%d file io slots leaked", active) + } + if downloads := server.Snapshot().PackDownloads; downloads != 1 { + t.Fatalf("pack downloads = %d, want 1", downloads) + } +} diff --git a/internal/server/grpc.go b/internal/server/grpc.go new file mode 100644 index 0000000..c3a2698 --- /dev/null +++ b/internal/server/grpc.go @@ -0,0 +1,197 @@ +package server + +import ( + "bytes" + "context" + "errors" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + + remoteasset "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/asset/v1" + remoteexecution "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/execution/v2" + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/semver" + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/google/bytestream" +) + +// maxBatchSize bounds a single BatchUpdateBlobs or BatchReadBlobs payload. +// Anything larger has to use the ByteStream API, which streams in chunks instead +// of buffering a whole gRPC message. +const maxBatchSize = 4 * 1024 * 1024 + +// grpcMessageHeadroom leaves room for the framing around a maximum-size batch. +const grpcMessageHeadroom = 1024 * 1024 + +// GRPCHandler returns a gRPC server exposing the cache half of the Bazel remote +// execution API. Remote execution itself is not offered, so Bazel treats the +// endpoint as a cache-only backend. +func (s *Server) GRPCHandler() *grpc.Server { + handler := grpc.NewServer( + grpc.MaxRecvMsgSize(maxBatchSize+grpcMessageHeadroom), + grpc.MaxSendMsgSize(maxBatchSize+grpcMessageHeadroom), + ) + remoteexecution.RegisterCapabilitiesServer(handler, &capabilitiesService{server: s}) + remoteexecution.RegisterActionCacheServer(handler, &actionCacheService{server: s}) + remoteexecution.RegisterContentAddressableStorageServer(handler, &casService{server: s}) + remoteasset.RegisterFetchServer(handler, &assetService{server: s}) + bytestream.RegisterByteStreamServer(handler, &byteStreamService{server: s}) + return handler +} + +// requireDefaultInstance rejects instance names. The cache namespace is fixed by +// the configured key prefix, so honouring an instance name would silently share +// one namespace between callers that asked for different ones. +func requireDefaultInstance(name string) error { + if name != "" { + return status.Errorf(codes.InvalidArgument, "instance_name %q is not supported", name) + } + return nil +} + +func requireSHA256(function remoteexecution.DigestFunction_Value) error { + switch function { + case remoteexecution.DigestFunction_UNKNOWN, remoteexecution.DigestFunction_SHA256: + return nil + default: + return status.Errorf(codes.InvalidArgument, "digest function %s is not supported", function) + } +} + +func requireIdentity(compressor remoteexecution.Compressor_Value) error { + if compressor != remoteexecution.Compressor_IDENTITY { + return status.Errorf(codes.InvalidArgument, "compressor %s is not supported", compressor) + } + return nil +} + +func requestDigest(digest *remoteexecution.Digest, field string) (digestReference, error) { + reference, err := digestReferenceFrom(digest, field) + if err != nil { + return digestReference{}, status.Error(codes.InvalidArgument, err.Error()) + } + return reference, nil +} + +// grpcError translates a cache outcome into the status a REAPI client expects. +func grpcError(kind, digest string, err error) error { + switch { + case errors.Is(err, errCacheMiss): + return status.Errorf(codes.NotFound, "%s/%s is not in the cache", kind, digest) + case errors.Is(err, errPayloadMismatch): + return status.Errorf(codes.InvalidArgument, "payload does not hash to %s", digest) + case errors.Is(err, errPayloadTruncated): + return status.Errorf(codes.InvalidArgument, "payload size does not match %s/%s", kind, digest) + case errors.Is(err, errLocalFailure): + return status.Error(codes.Internal, "local cache unavailable") + default: + return status.Error(codes.Unavailable, "cache backend unavailable") + } +} + +type capabilitiesService struct { + remoteexecution.UnimplementedCapabilitiesServer + server *Server +} + +func (c *capabilitiesService) GetCapabilities( + _ context.Context, + request *remoteexecution.GetCapabilitiesRequest, +) (*remoteexecution.ServerCapabilities, error) { + if err := requireDefaultInstance(request.GetInstanceName()); err != nil { + return nil, err + } + c.server.stats.requests.Add(1) + identity := []remoteexecution.Compressor_Value{remoteexecution.Compressor_IDENTITY} + return remoteexecution.ServerCapabilities_builder{ + CacheCapabilities: remoteexecution.CacheCapabilities_builder{ + DigestFunctions: []remoteexecution.DigestFunction_Value{ + remoteexecution.DigestFunction_SHA256, + }, + ActionCacheUpdateCapabilities: remoteexecution.ActionCacheUpdateCapabilities_builder{ + UpdateEnabled: c.server.cfg.WriteEnabled, + }.Build(), + MaxBatchTotalSizeBytes: maxBatchSize, + MaxCasBlobSizeBytes: c.server.cfg.MaxBlobSize, + // The cache stores action results verbatim and never resolves a + // symlink, so it imposes no restriction on their targets. + SymlinkAbsolutePathStrategy: remoteexecution.SymlinkAbsolutePathStrategy_ALLOWED, + SupportedCompressors: identity, + SupportedBatchUpdateCompressors: identity, + }.Build(), + LowApiVersion: semVer(2, 0), + HighApiVersion: semVer(2, 3), + }.Build(), nil +} + +func semVer(major, minor int32) *semver.SemVer { + return semver.SemVer_builder{Major: major, Minor: minor}.Build() +} + +type actionCacheService struct { + remoteexecution.UnimplementedActionCacheServer + server *Server +} + +func (a *actionCacheService) GetActionResult( + ctx context.Context, + request *remoteexecution.GetActionResultRequest, +) (*remoteexecution.ActionResult, error) { + if err := requireDefaultInstance(request.GetInstanceName()); err != nil { + return nil, err + } + if err := requireSHA256(request.GetDigestFunction()); err != nil { + return nil, err + } + reference, err := requestDigest(request.GetActionDigest(), "action_digest") + if err != nil { + return nil, err + } + a.server.stats.requests.Add(1) + data, err := a.server.readObjectBytes(ctx, "ac", reference.hash) + if err != nil { + return nil, grpcError("ac", reference.hash, err) + } + result := &remoteexecution.ActionResult{} + if err := proto.Unmarshal(data, result); err != nil { + // The closure validation already parsed these bytes, so reaching here + // means the stored entry is unusable rather than merely absent. + a.server.stats.invalidActionResults.Add(1) + return nil, status.Errorf(codes.NotFound, "ac/%s is not in the cache", reference.hash) + } + return result, nil +} + +func (a *actionCacheService) UpdateActionResult( + ctx context.Context, + request *remoteexecution.UpdateActionResultRequest, +) (*remoteexecution.ActionResult, error) { + if err := requireDefaultInstance(request.GetInstanceName()); err != nil { + return nil, err + } + if err := requireSHA256(request.GetDigestFunction()); err != nil { + return nil, err + } + reference, err := requestDigest(request.GetActionDigest(), "action_digest") + if err != nil { + return nil, err + } + result := request.GetActionResult() + if result == nil { + return nil, status.Error(codes.InvalidArgument, "action_result is required") + } + data, err := proto.Marshal(result) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "action_result cannot be encoded: %v", err) + } + if int64(len(data)) > a.server.cfg.MaxBlobSize { + return nil, status.Error(codes.InvalidArgument, "action result exceeds the configured maximum size") + } + a.server.stats.requests.Add(1) + err = a.server.writeObject(ctx, "ac", reference.hash, bytes.NewReader(data), int64(len(data))) + if err != nil { + return nil, grpcError("ac", reference.hash, err) + } + return result, nil +} diff --git a/internal/server/grpc_asset.go b/internal/server/grpc_asset.go new file mode 100644 index 0000000..abc0540 --- /dev/null +++ b/internal/server/grpc_asset.go @@ -0,0 +1,382 @@ +package server + +import ( + "context" + "crypto/sha1" + "crypto/sha256" + "crypto/sha512" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "hash" + "io" + "net/http" + "net/url" + "os" + "strings" + + statuspb "google.golang.org/genproto/googleapis/rpc/status" + "google.golang.org/grpc/codes" + "lukechampine.com/blake3" + + remoteasset "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/asset/v1" + remoteexecution "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/execution/v2" +) + +// checksumQualifier carries the expected content hash as Subresource Integrity. +const checksumQualifier = "checksum.sri" + +const sha256Algorithm = "sha256" + +const blake3DigestSize = 32 + +// maxAssetRedirects bounds a redirect chain from an asset origin. +const maxAssetRedirects = 10 + +// checksumAlgorithms are the Subresource Integrity algorithms Bazel can emit. A +// weak one is accepted because it only has to match what the caller declared; +// content is stored under its sha256 either way, and Bazel verifies the same +// checksum itself after the download. +var checksumAlgorithms = map[string]func() hash.Hash{ + "sha1": sha1.New, + sha256Algorithm: sha256.New, + "sha384": sha512.New384, + "sha512": sha512.New, + "blake3": func() hash.Hash { return blake3.New(blake3DigestSize, nil) }, +} + +// assetChecksum is the content hash a caller declared for an asset. +type assetChecksum struct { + algorithm string + hash string +} + +func (c assetChecksum) String() string { + return c.algorithm + "-" + c.hash +} + +func defaultAssetClient() *http.Client { + return &http.Client{ + CheckRedirect: func(request *http.Request, via []*http.Request) error { + if request.URL.Scheme != "https" { + return fmt.Errorf("refusing a redirect to %s", request.URL.Scheme) + } + if len(via) >= maxAssetRedirects { + return errors.New("too many redirects") + } + stripSensitiveOnRedirect(request, via) + return nil + }, + } +} + +type assetService struct { + remoteasset.UnimplementedFetchServer + server *Server +} + +// FetchBlob backs Bazel's remote downloader, which caches the archives that +// repository rules download. Bazel never pushes those blobs back, so a hit is +// only ever possible if this server fetched the asset itself the first time. +func (a *assetService) FetchBlob( + ctx context.Context, + request *remoteasset.FetchBlobRequest, +) (*remoteasset.FetchBlobResponse, error) { + if err := requireDefaultInstance(request.GetInstanceName()); err != nil { + return nil, err + } + if err := requireSHA256(request.GetDigestFunction()); err != nil { + return nil, err + } + s := a.server + s.stats.requests.Add(1) + s.stats.assetRequests.Add(1) + uris := request.GetUris() + + checksum, err := parseChecksum(request.GetQualifiers()) + if err != nil { + s.stats.assetRejected.Add(1) + return fetchFailure(uris, err), nil + } + headers, err := parseAssetHeaders(request.GetQualifiers(), len(uris)) + if err != nil { + s.stats.assetRejected.Add(1) + return fetchFailure(uris, err), nil + } + // Bazel sets this to a future timestamp when a repository rule declares no + // checksum, precisely to forbid cached content. Nothing here records when an + // asset was fetched, so the honest answer is always a miss. + if request.HasOldestContentAccepted() { + s.stats.assetRejected.Add(1) + return fetchFailure(uris, errors.New("this cache cannot attest to when content was fetched")), nil + } + + if reference, found := s.cachedAsset(ctx, checksum); found { + s.stats.assetHits.Add(1) + return fetchSuccess("", reference), nil + } + uri, reference, err := s.fetchAsset(ctx, uris, checksum, headers) + if err != nil { + return fetchFailure(uris, err), nil + } + return fetchSuccess(uri, reference), nil +} + +func fetchSuccess(uri string, reference digestReference) *remoteasset.FetchBlobResponse { + return remoteasset.FetchBlobResponse_builder{ + Status: &statuspb.Status{Code: int32(codes.OK)}, + Uri: uri, + BlobDigest: digestProtoFor(reference), + DigestFunction: remoteexecution.DigestFunction_SHA256, + }.Build() +} + +// fetchFailure reports a miss inside the response, which is where the Remote +// Asset API puts per-asset outcomes. Bazel logs the message on its own, without +// saying which download produced it, so the resource is always named here. +func fetchFailure(uris []string, err error) *remoteasset.FetchBlobResponse { + return remoteasset.FetchBlobResponse_builder{ + Status: &statuspb.Status{ + Code: int32(codes.NotFound), + Message: fmt.Sprintf("%s: %s", describeAssets(uris), safeError(err)), + }, + }.Build() +} + +func describeAssets(uris []string) string { + if len(uris) == 0 { + return "asset with no uri" + } + described := safeURIString(uris[0]) + if len(uris) > 1 { + described = fmt.Sprintf("%s (and %d more)", described, len(uris)-1) + } + return described +} + +func digestProtoFor(reference digestReference) *remoteexecution.Digest { + return remoteexecution.Digest_builder{ + Hash: reference.hash, + SizeBytes: reference.size, + }.Build() +} + +// parseChecksum decodes checksum.sri, which Bazel sends as Subresource Integrity +// rather than hex. +func parseChecksum(qualifiers []*remoteasset.Qualifier) (assetChecksum, error) { + for _, qualifier := range qualifiers { + if qualifier.GetName() != checksumQualifier { + continue + } + value := qualifier.GetValue() + algorithm, encoded, found := strings.Cut(value, "-") + if !found || algorithm == "" || encoded == "" { + return assetChecksum{}, fmt.Errorf("%s %q is not subresource integrity", checksumQualifier, value) + } + newHash, supported := checksumAlgorithms[algorithm] + if !supported { + return assetChecksum{}, fmt.Errorf("checksum algorithm %q is not supported", algorithm) + } + sum, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + return assetChecksum{}, fmt.Errorf("%s %q is not base64", checksumQualifier, value) + } + if size := newHash().Size(); len(sum) != size { + return assetChecksum{}, fmt.Errorf( + "%s %q decodes to %d bytes, not the %d a %s digest needs", + checksumQualifier, value, len(sum), size, algorithm, + ) + } + return assetChecksum{algorithm: algorithm, hash: hex.EncodeToString(sum)}, nil + } + return assetChecksum{}, errors.New("no checksum was declared, so the download cannot be cached") +} + +// cachedAsset resolves the asset from the cache. A sha256 checksum addresses the +// content store directly; anything else has to go through an alias recorded when +// the asset was first fetched. +func (s *Server) cachedAsset(ctx context.Context, checksum assetChecksum) (digestReference, bool) { + if checksum.algorithm != sha256Algorithm { + return s.loadAlias(ctx, checksum) + } + if checksum.hash == emptySHA256Digest { + s.implicitEmptyCASHit() + return digestReference{hash: checksum.hash}, true + } + // Resolving rather than probing is deliberate: the client reads the blob over + // ByteStream immediately afterwards, so this both learns the size and warms + // the local copy. + object, err := s.readObject(ctx, "cas", checksum.hash) + if err != nil { + return digestReference{}, false + } + return digestReference{hash: checksum.hash, size: object.size}, true +} + +func (s *Server) fetchAsset( + ctx context.Context, + uris []string, + checksum assetChecksum, + headers assetHeaders, +) (string, digestReference, error) { + if len(uris) == 0 { + return "", digestReference{}, errors.New("no uris were supplied") + } + var last error + for index, uri := range uris { + reference, err := s.fetchAssetFrom(ctx, uri, checksum, headers.forURI(index)) + if err == nil { + return uri, reference, nil + } + s.stats.assetFetchErrors.Add(1) + s.cfg.Logger.Printf("fetching %s failed: %s", safeURIString(uri), safeError(err)) + last = err + } + if len(uris) > 1 { + return "", digestReference{}, fmt.Errorf("all %d uris failed, last: %w", len(uris), last) + } + return "", digestReference{}, last +} + +func (s *Server) fetchAssetFrom( + ctx context.Context, + uri string, + checksum assetChecksum, + headers http.Header, +) (digestReference, error) { + parsed, err := url.Parse(uri) + if err != nil { + return digestReference{}, errors.New("uri is not a valid URL") + } + if parsed.Scheme != "https" { + return digestReference{}, fmt.Errorf("refusing to fetch over %q", parsed.Scheme) + } + headers, err = permittedHeaders(headers, parsed, s.assetRoutes) + if err != nil { + return digestReference{}, err + } + + path, reference, err := s.downloadAsset(ctx, uri, checksum, headers) + if err != nil { + return digestReference{}, err + } + keep := false + defer func() { + if !keep { + _ = os.Remove(path) + } + }() + + file, err := os.Open(path) + if err != nil { + return digestReference{}, fmt.Errorf("reopen fetched asset: %w", err) + } + defer file.Close() + s.stats.operations.Add(1) + s.stats.bytesReceived.Add(uint64(reference.size)) + keep, err = s.storeObjectFile(ctx, "cas", reference.hash, file, path, reference.size) + if err != nil { + return digestReference{}, fmt.Errorf("publish fetched asset: %w", err) + } + if checksum.algorithm != sha256Algorithm { + // The blob is cached either way; without the alias the next build simply + // fetches it again, so this must not fail the request. + if err := s.saveAlias(ctx, checksum, reference); err != nil { + s.cfg.Logger.Printf("recording %s alias failed: %s", checksum.algorithm, safeError(err)) + } + } + return reference, nil +} + +// downloadAsset streams an origin response to a spool file, accepts it only if +// it matches the checksum the caller declared, and reports the sha256 digest the +// content is stored under. +func (s *Server) downloadAsset( + ctx context.Context, + uri string, + checksum assetChecksum, + headers http.Header, +) (string, digestReference, error) { + if err := s.acquire(ctx); err != nil { + return "", digestReference{}, err + } + defer s.release() + + fetchCtx, cancel := context.WithTimeout(ctx, s.cfg.BackendTimeout) + defer cancel() + request, err := http.NewRequestWithContext(fetchCtx, http.MethodGet, uri, nil) + if err != nil { + return "", digestReference{}, errors.New("uri cannot be requested") + } + for name, values := range headers { + for _, value := range values { + request.Header.Add(name, value) + } + } + response, err := s.cfg.AssetClient.Do(request) + if err != nil { + return "", digestReference{}, fmt.Errorf("fetch failed: %w", err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return "", digestReference{}, fmt.Errorf("origin returned HTTP %d", response.StatusCode) + } + s.stats.assetDownloads.Add(1) + + file, err := os.CreateTemp(s.cfg.CacheDir, "asset-*") + if err != nil { + return "", digestReference{}, fmt.Errorf("create asset spool: %w", err) + } + path := file.Name() + keep := false + defer func() { + if err := file.Close(); err != nil { + s.cfg.Logger.Printf("close asset spool: %v", err) + } + if !keep { + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + s.cfg.Logger.Printf("remove asset spool: %v", err) + } + } + }() + + // Storage is addressed by sha256 whatever the caller declared, so the content + // is hashed twice unless those happen to be the same function. + canonical := sha256.New() + declared := canonical + writers := []io.Writer{file, canonical} + if checksum.algorithm != sha256Algorithm { + declared = checksumAlgorithms[checksum.algorithm]() + writers = append(writers, declared) + } + + limit := s.cfg.MaxBlobSize + size, err := io.Copy(io.MultiWriter(writers...), io.LimitReader(response.Body, limit+1)) + if err != nil { + return "", digestReference{}, fmt.Errorf("fetch failed: %w", err) + } + if size > limit { + return "", digestReference{}, errors.New("content exceeds the configured maximum size") + } + actual := assetChecksum{algorithm: checksum.algorithm, hash: hex.EncodeToString(declared.Sum(nil))} + if actual != checksum { + return "", digestReference{}, fmt.Errorf("content is %s, not the requested %s", actual, checksum) + } + keep = true + return path, digestReference{hash: hex.EncodeToString(canonical.Sum(nil)), size: size}, nil +} + +// safeURI drops the credentials and query string a URI may carry before it +// reaches a log line or an error returned to the caller. +func safeURI(parsed *url.URL) string { + return parsed.Scheme + "://" + parsed.Host + parsed.Path +} + +func safeURIString(uri string) string { + parsed, err := url.Parse(uri) + if err != nil { + return "malformed uri" + } + return safeURI(parsed) +} diff --git a/internal/server/grpc_asset_test.go b/internal/server/grpc_asset_test.go new file mode 100644 index 0000000..adcd2e9 --- /dev/null +++ b/internal/server/grpc_asset_test.go @@ -0,0 +1,436 @@ +package server + +import ( + "bytes" + "crypto/sha256" + "encoding/base64" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/protobuf/types/known/timestamppb" + + remoteasset "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/asset/v1" +) + +func futureTimestamp() *timestamppb.Timestamp { + return timestamppb.New(time.Now().Add(time.Hour)) +} + +func subresourceIntegrity(data []byte) string { + sum := sha256.Sum256(data) + return sha256Algorithm + "-" + base64.StdEncoding.EncodeToString(sum[:]) +} + +func integrityWith(t *testing.T, algorithm string, data []byte) string { + t.Helper() + newHash, ok := checksumAlgorithms[algorithm] + if !ok { + t.Fatalf("unknown algorithm %q", algorithm) + } + hasher := newHash() + hasher.Write(data) + return algorithm + "-" + base64.StdEncoding.EncodeToString(hasher.Sum(nil)) +} + +func checksumQualifiers(value string) []*remoteasset.Qualifier { + return []*remoteasset.Qualifier{ + remoteasset.Qualifier_builder{Name: checksumQualifier, Value: value}.Build(), + } +} + +// assetOrigin stands in for an upstream that repository rules download from. +func assetOrigin(t *testing.T, body []byte) (*httptest.Server, *atomic.Int64) { + t.Helper() + var requests atomic.Int64 + origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + requests.Add(1) + _, _ = w.Write(body) + })) + t.Cleanup(origin.Close) + return origin, &requests +} + +func assetServer(t *testing.T, backend *memoryBackend, origin *httptest.Server) *Server { + t.Helper() + return testServer(t, backend, func(cfg *Config) { + if origin != nil { + cfg.AssetClient = origin.Client() + } + }) +} + +func fetchBlob( + t *testing.T, + server *Server, + request *remoteasset.FetchBlobRequest, +) *remoteasset.FetchBlobResponse { + t.Helper() + client := remoteasset.NewFetchClient(testGRPCConn(t, server)) + response, err := client.FetchBlob(t.Context(), request) + if err != nil { + t.Fatal(err) + } + return response +} + +func TestFetchBlobServesAnAssetAlreadyInTheCache(t *testing.T) { + asset := []byte("a cached repository archive") + reference := referenceFor(asset) + backend := newMemoryBackend() + backend.objects["test-v1-cas-"+reference.hash] = asset + origin, requests := assetOrigin(t, asset) + server := assetServer(t, backend, origin) + + response := fetchBlob(t, server, remoteasset.FetchBlobRequest_builder{ + Uris: []string{origin.URL + "/archive.tar.gz"}, + Qualifiers: checksumQualifiers(subresourceIntegrity(asset)), + }.Build()) + + if code := codes.Code(response.GetStatus().GetCode()); code != codes.OK { + t.Fatalf("status = %s (%s)", code, response.GetStatus().GetMessage()) + } + if got := response.GetBlobDigest(); got.GetHash() != reference.hash || got.GetSizeBytes() != reference.size { + t.Fatalf("blob digest = %v, want %v", got, reference) + } + if requests.Load() != 0 { + t.Fatal("a cached asset must not be fetched from its origin") + } +} + +func TestFetchBlobFetchesAndPublishesOnMiss(t *testing.T) { + asset := []byte("an archive that is not cached yet") + reference := referenceFor(asset) + backend := newMemoryBackend() + origin, requests := assetOrigin(t, asset) + server := assetServer(t, backend, origin) + request := remoteasset.FetchBlobRequest_builder{ + Uris: []string{origin.URL + "/archive.tar.gz"}, + Qualifiers: checksumQualifiers(subresourceIntegrity(asset)), + }.Build() + + response := fetchBlob(t, server, request) + if code := codes.Code(response.GetStatus().GetCode()); code != codes.OK { + t.Fatalf("status = %s (%s)", code, response.GetStatus().GetMessage()) + } + if response.GetBlobDigest().GetHash() != reference.hash { + t.Fatalf("blob digest = %v", response.GetBlobDigest()) + } + if response.GetUri() != origin.URL+"/archive.tar.gz" { + t.Fatalf("uri = %q", response.GetUri()) + } + server.objectsMu.RLock() + cached, ok := server.objects[server.objectKey("cas", reference.hash)] + server.objectsMu.RUnlock() + if !ok || !strings.HasPrefix(filepath.Base(cached.path), "asset-") { + t.Fatalf("cached asset was not retained from its download spool: %+v", cached) + } + if data, err := cached.readAll(); err != nil || !bytes.Equal(data, asset) { + t.Fatalf("cached asset data = %q, %v", data, err) + } + if uploads := spoolFiles(t, server.cfg.CacheDir); len(uploads) != 0 { + t.Fatalf("asset publication created a second upload spool: %v", uploads) + } + if err := server.packs.flush(t.Context(), true); err != nil { + t.Fatal(err) + } + if stats := server.Snapshot(); stats.AssetDownloads != 1 || stats.PackUploads != 1 || + stats.ManifestUploads != 1 || stats.Uploads != 2 { + t.Fatalf("unexpected stats: %+v", stats) + } + + // A second request is served from the cache the first one populated. + if response := fetchBlob(t, server, request); codes.Code(response.GetStatus().GetCode()) != codes.OK { + t.Fatalf("second fetch = %s", response.GetStatus().GetMessage()) + } + if requests.Load() != 1 { + t.Fatalf("origin was contacted %d times, want 1", requests.Load()) + } + // A hit costs no download, so without its own counter it leaves no trace at + // all and a busy cache is indistinguishable from an unused one. + stats := server.Snapshot() + if stats.AssetRequests != 2 || stats.AssetHits != 1 || stats.AssetDownloads != 1 { + t.Fatalf("unexpected stats: %+v", stats) + } +} + +func TestFetchBlobRejectsContentThatFailsItsChecksum(t *testing.T) { + expected := []byte("what the caller asked for") + origin, _ := assetOrigin(t, []byte("something else entirely")) + backend := newMemoryBackend() + server := assetServer(t, backend, origin) + + response := fetchBlob(t, server, remoteasset.FetchBlobRequest_builder{ + Uris: []string{origin.URL + "/archive.tar.gz"}, + Qualifiers: checksumQualifiers(subresourceIntegrity(expected)), + }.Build()) + + if code := codes.Code(response.GetStatus().GetCode()); code != codes.NotFound { + t.Fatalf("status = %s, want NotFound", code) + } + if len(backend.objects) != 0 { + t.Fatalf("unverified content was published: %v", backend.objects) + } + if assets := cacheFilesWithPrefix(t, server.cfg.CacheDir, "asset-"); len(assets) != 0 { + t.Fatalf("unverified asset spools were not cleaned up: %v", assets) + } + if stats := server.Snapshot(); stats.AssetFetchErrors != 1 { + t.Fatalf("unexpected stats: %+v", stats) + } +} + +// These messages surface to users as "WARNING: Remote Cache: NOT_FOUND: ...", +// often once per download, so they have to explain themselves on one line. +func TestChecksumRejectionsExplainThemselves(t *testing.T) { + for _, test := range []struct { + name string + value string + want string + }{ + { + name: "unknown algorithm", + value: "md5-" + base64.StdEncoding.EncodeToString(make([]byte, 16)), + want: `checksum algorithm "md5" is not supported`, + }, + { + name: "not subresource integrity", + value: "deadbeef", + want: `checksum.sri "deadbeef" is not subresource integrity`, + }, + { + name: "empty", + value: "", + want: `checksum.sri "" is not subresource integrity`, + }, + { + name: "not base64", + value: "sha256-not base64!", + want: `checksum.sri "sha256-not base64!" is not base64`, + }, + { + name: "wrong digest length", + value: "sha256-" + base64.StdEncoding.EncodeToString([]byte("short")), + want: `checksum.sri "sha256-c2hvcnQ=" decodes to 5 bytes, not the 32 a sha256 digest needs`, + }, + } { + t.Run(test.name, func(t *testing.T) { + _, err := parseChecksum(checksumQualifiers(test.value)) + if err == nil || err.Error() != test.want { + t.Fatalf("error = %v, want %q", err, test.want) + } + }) + } + + _, err := parseChecksum(nil) + want := "no checksum was declared, so the download cannot be cached" + if err == nil || err.Error() != want { + t.Fatalf("error = %v, want %q", err, want) + } +} + +// Bazel reports the message without saying which download produced it. +func TestFetchFailuresNameTheResource(t *testing.T) { + server := assetServer(t, newMemoryBackend(), nil) + + response := fetchBlob(t, server, remoteasset.FetchBlobRequest_builder{ + Uris: []string{"https://example.invalid/pkg.tgz?token=secret"}, + Qualifiers: checksumQualifiers("deadbeef"), + }.Build()) + message := response.GetStatus().GetMessage() + want := `https://example.invalid/pkg.tgz: checksum.sri "deadbeef" is not subresource integrity` + if message != want { + t.Fatalf("message = %q, want %q", message, want) + } + + // Several mirrors still name one resource, and never a query string. + response = fetchBlob(t, server, remoteasset.FetchBlobRequest_builder{ + Uris: []string{ + "https://example.invalid/a.tgz?sig=secret", + "https://mirror.invalid/a.tgz", + }, + Qualifiers: checksumQualifiers("deadbeef"), + }.Build()) + message = response.GetStatus().GetMessage() + if !strings.HasPrefix(message, "https://example.invalid/a.tgz (and 1 more): ") { + t.Fatalf("message = %q", message) + } + if strings.Contains(message, "secret") { + t.Fatalf("message leaked a query string: %q", message) + } +} + +// npm integrity is sha512, so without alias support none of it could be cached. +func TestFetchBlobCachesAssetsDeclaredWithAnyChecksum(t *testing.T) { + asset := []byte("a package tarball from a registry") + reference := referenceFor(asset) + + for _, algorithm := range []string{"sha1", "sha256", "sha384", "sha512", "blake3"} { + t.Run(algorithm, func(t *testing.T) { + backend := newMemoryBackend() + origin, requests := assetOrigin(t, asset) + server := assetServer(t, backend, origin) + request := remoteasset.FetchBlobRequest_builder{ + Uris: []string{origin.URL + "/pkg.tgz"}, + Qualifiers: checksumQualifiers(integrityWith(t, algorithm, asset)), + }.Build() + + response := fetchBlob(t, server, request) + if code := codes.Code(response.GetStatus().GetCode()); code != codes.OK { + t.Fatalf("status = %s (%s)", code, response.GetStatus().GetMessage()) + } + // Whatever the caller declared, the blob is addressed by sha256. + if got := response.GetBlobDigest().GetHash(); got != reference.hash { + t.Fatalf("blob digest = %s, want %s", got, reference.hash) + } + server.objectsMu.RLock() + cached, ok := server.objects[server.objectKey("cas", reference.hash)] + server.objectsMu.RUnlock() + if !ok { + t.Fatal("fetched asset was not retained in the local cache") + } + if data, err := cached.readAll(); err != nil || !bytes.Equal(data, asset) { + t.Fatalf("cached asset data = %q, %v", data, err) + } + + second := fetchBlob(t, server, request) + if code := codes.Code(second.GetStatus().GetCode()); code != codes.OK { + t.Fatalf("second fetch = %s", second.GetStatus().GetMessage()) + } + if requests.Load() != 1 { + t.Fatalf("origin was contacted %d times, want 1", requests.Load()) + } + }) + } +} + +// Packed mode is the interesting case for aliases: they must travel in a CARv2 +// pack rather than costing one Actions-cache creation each, and must survive a +// fresh runner that only has the published manifests. +func TestAssetAliasSurvivesAPackedRoundTrip(t *testing.T) { + asset := []byte("a registry tarball addressed by sha512") + reference := referenceFor(asset) + backend := newMemoryBackend() + origin, requests := assetOrigin(t, asset) + request := remoteasset.FetchBlobRequest_builder{ + Uris: []string{origin.URL + "/pkg.tgz"}, + Qualifiers: checksumQualifiers(integrityWith(t, "sha512", asset)), + }.Build() + + seed := testServer(t, backend, func(cfg *Config) { + cfg.Catalog = memoryCatalog{backend: backend} + cfg.PackSize = 1024 + cfg.PackFlushInterval = time.Hour + cfg.MaxManifests = 16 + cfg.AssetClient = origin.Client() + }) + if response := fetchBlob(t, seed, request); codes.Code(response.GetStatus().GetCode()) != codes.OK { + t.Fatalf("seed fetch = %s", response.GetStatus().GetMessage()) + } + closePackedServer(t, seed) + if stats := seed.Snapshot(); stats.PackUploads == 0 || stats.ManifestUploads == 0 { + t.Fatalf("nothing was published: %+v", stats) + } + + restored := testServer(t, backend, func(cfg *Config) { + cfg.Catalog = memoryCatalog{backend: backend} + cfg.PackSize = 1024 + cfg.PackFlushInterval = time.Hour + cfg.MaxManifests = 16 + cfg.AssetClient = origin.Client() + }) + defer closePackedServer(t, restored) + response := fetchBlob(t, restored, request) + if code := codes.Code(response.GetStatus().GetCode()); code != codes.OK { + t.Fatalf("restored fetch = %s (%s)", code, response.GetStatus().GetMessage()) + } + if got := response.GetBlobDigest().GetHash(); got != reference.hash { + t.Fatalf("blob digest = %s, want %s", got, reference.hash) + } + if requests.Load() != 1 { + t.Fatalf("origin was contacted %d times, want 1", requests.Load()) + } +} + +func TestFetchBlobRefusesUnverifiableOrInsecureRequests(t *testing.T) { + asset := []byte("an archive") + origin, requests := assetOrigin(t, asset) + + for _, test := range []struct { + name string + mutate func(*remoteasset.FetchBlobRequest_builder) + }{ + { + name: "no checksum", + mutate: func(b *remoteasset.FetchBlobRequest_builder) { b.Qualifiers = nil }, + }, + { + name: "checksum in an unknown algorithm", + mutate: func(b *remoteasset.FetchBlobRequest_builder) { + b.Qualifiers = checksumQualifiers("md5-" + strings.Repeat("A", 24)) + }, + }, + { + name: "plain http origin", + mutate: func(b *remoteasset.FetchBlobRequest_builder) { + b.Uris = []string{"http://127.0.0.1:1/archive.tar.gz"} + }, + }, + { + name: "no uris", + mutate: func(b *remoteasset.FetchBlobRequest_builder) { b.Uris = nil }, + }, + } { + t.Run(test.name, func(t *testing.T) { + server := assetServer(t, newMemoryBackend(), origin) + builder := remoteasset.FetchBlobRequest_builder{ + Uris: []string{origin.URL + "/archive.tar.gz"}, + Qualifiers: checksumQualifiers(subresourceIntegrity(asset)), + } + test.mutate(&builder) + + response := fetchBlob(t, server, builder.Build()) + if code := codes.Code(response.GetStatus().GetCode()); code != codes.NotFound { + t.Fatalf("status = %s, want NotFound", code) + } + }) + } + if requests.Load() != 0 { + t.Fatalf("origin was contacted %d times, want 0", requests.Load()) + } +} + +// Bazel sets oldest_content_accepted to a future timestamp when a repository +// rule declares no checksum, which forbids answering from cache. +func TestFetchBlobWillNotAnswerWhenFreshContentIsDemanded(t *testing.T) { + asset := []byte("a cached archive") + reference := referenceFor(asset) + backend := newMemoryBackend() + backend.objects["test-v1-cas-"+reference.hash] = asset + server := assetServer(t, backend, nil) + + response := fetchBlob(t, server, remoteasset.FetchBlobRequest_builder{ + Uris: []string{"https://example.invalid/archive.tar.gz"}, + Qualifiers: checksumQualifiers(subresourceIntegrity(asset)), + OldestContentAccepted: futureTimestamp(), + }.Build()) + + if code := codes.Code(response.GetStatus().GetCode()); code != codes.NotFound { + t.Fatalf("status = %s, want NotFound", code) + } +} + +func TestFetchBlobRejectsInstanceNames(t *testing.T) { + server := assetServer(t, newMemoryBackend(), nil) + client := remoteasset.NewFetchClient(testGRPCConn(t, server)) + + _, err := client.FetchBlob(t.Context(), remoteasset.FetchBlobRequest_builder{ + InstanceName: "other", + Uris: []string{"https://example.invalid/archive.tar.gz"}, + }.Build()) + assertCode(t, err, codes.InvalidArgument) +} diff --git a/internal/server/grpc_bytestream.go b/internal/server/grpc_bytestream.go new file mode 100644 index 0000000..fa7d3a6 --- /dev/null +++ b/internal/server/grpc_bytestream.go @@ -0,0 +1,235 @@ +package server + +import ( + "context" + "io" + "strconv" + "strings" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/google/bytestream" +) + +// byteStreamChunkSize is the payload size of one Read response. It trades gRPC +// framing overhead against the memory a single in-flight message costs. +const byteStreamChunkSize = 256 * 1024 + +type byteStreamService struct { + bytestream.UnimplementedByteStreamServer + server *Server +} + +func (b *byteStreamService) Read( + request *bytestream.ReadRequest, + stream grpc.ServerStreamingServer[bytestream.ReadResponse], +) error { + resource, err := parseReadResource(request.GetResourceName()) + if err != nil { + return err + } + offset, limit := request.GetReadOffset(), request.GetReadLimit() + if offset < 0 || limit < 0 { + return status.Error(codes.InvalidArgument, "read_offset and read_limit must not be negative") + } + + b.server.stats.requests.Add(1) + if isImplicitEmptyDigest(resource) { + b.server.implicitEmptyCASHit() + return nil + } + file, size, err := b.server.openObject(stream.Context(), "cas", resource.hash) + if err != nil { + return grpcError("cas", resource.hash, err) + } + defer file.Close() + + if offset > size { + return status.Errorf(codes.OutOfRange, "read_offset %d is past the end of the blob", offset) + } + if _, err := file.Seek(offset, io.SeekStart); err != nil { + b.server.cfg.Logger.Printf("seek cache object cas/%s: %v", resource.hash, err) + return status.Error(codes.Internal, "local cache unavailable") + } + reader := b.server.gateReader(stream.Context(), file) + if limit > 0 { + reader = io.LimitReader(reader, limit) + } + + buffer := make([]byte, byteStreamChunkSize) + for { + n, err := reader.Read(buffer) + if n > 0 { + response := bytestream.ReadResponse_builder{Data: buffer[:n]}.Build() + if sendErr := stream.Send(response); sendErr != nil { + return sendErr + } + b.server.stats.bytesServed.Add(uint64(n)) + } + if err == io.EOF { + return nil + } + if err != nil { + b.server.cfg.Logger.Printf("serve cache object cas/%s: %v", resource.hash, err) + return status.Error(codes.Internal, "local cache unavailable") + } + } +} + +func (b *byteStreamService) Write( + stream grpc.ClientStreamingServer[bytestream.WriteRequest, bytestream.WriteResponse], +) error { + first, err := stream.Recv() + if err == io.EOF { + return status.Error(codes.InvalidArgument, "write stream contained no requests") + } + if err != nil { + return err + } + resource, err := parseWriteResource(first.GetResourceName()) + if err != nil { + return err + } + if first.GetWriteOffset() != 0 { + return status.Error(codes.InvalidArgument, "resumed writes are not supported; write from offset 0") + } + + b.server.stats.requests.Add(1) + if resource.size > b.server.cfg.MaxBlobSize { + return status.Error(codes.InvalidArgument, "blob exceeds the configured maximum size") + } + body := &writeStreamReader{ + stream: stream, + pending: first.GetData(), + offset: int64(len(first.GetData())), + finished: first.GetFinishWrite(), + } + err = b.server.writeObject(stream.Context(), "cas", resource.hash, body, resource.size) + if err != nil { + // A stream-level failure is more specific than the truncation the + // object writer inferred from the short read, so it wins. + if body.err != nil { + return body.err + } + return grpcError("cas", resource.hash, err) + } + return stream.SendAndClose( + bytestream.WriteResponse_builder{CommittedSize: resource.size}.Build(), + ) +} + +// QueryWriteStatus reports that nothing is in flight. Uploads are spooled and +// only become visible once complete, so a client that lost its stream has to +// start again rather than resume. +func (b *byteStreamService) QueryWriteStatus( + _ context.Context, + request *bytestream.QueryWriteStatusRequest, +) (*bytestream.QueryWriteStatusResponse, error) { + b.server.stats.requests.Add(1) + if _, err := parseWriteResource(request.GetResourceName()); err != nil { + return nil, err + } + return nil, status.Error(codes.NotFound, "no write is in progress for this resource") +} + +// writeStreamReader adapts a ByteStream write stream to an io.Reader so that an +// upload is spooled and verified exactly once, by the shared object writer. +type writeStreamReader struct { + stream grpc.ClientStreamingServer[bytestream.WriteRequest, bytestream.WriteResponse] + pending []byte + offset int64 + finished bool + err error +} + +func (r *writeStreamReader) Read(p []byte) (int, error) { + for len(r.pending) == 0 { + if r.finished { + return 0, io.EOF + } + request, err := r.stream.Recv() + if err == io.EOF { + r.err = status.Error(codes.InvalidArgument, "write stream ended before finish_write") + return 0, r.err + } + if err != nil { + r.err = err + return 0, err + } + if request.GetWriteOffset() != r.offset { + r.err = status.Errorf( + codes.InvalidArgument, + "write_offset %d does not continue from %d", + request.GetWriteOffset(), + r.offset, + ) + return 0, r.err + } + r.pending = request.GetData() + r.offset += int64(len(r.pending)) + r.finished = request.GetFinishWrite() + } + n := copy(p, r.pending) + r.pending = r.pending[n:] + return n, nil +} + +// parseReadResource reads `{instance_name}/blobs/{hash}/{size}`. +func parseReadResource(name string) (digestReference, error) { + segments := strings.Split(name, "/") + for i, segment := range segments { + switch segment { + case "blobs": + return blobFromSegments(strings.Join(segments[:i], "/"), segments[i+1:]) + case "compressed-blobs": + return digestReference{}, errCompressedResource + } + } + return digestReference{}, unparsableResource(name) +} + +// parseWriteResource reads +// `{instance_name}/uploads/{uuid}/blobs/{hash}/{size}{/optional_metadata}`. +func parseWriteResource(name string) (digestReference, error) { + segments := strings.Split(name, "/") + for i, segment := range segments { + if segment != "uploads" || i+2 >= len(segments) { + continue + } + switch segments[i+2] { + case "blobs": + return blobFromSegments(strings.Join(segments[:i], "/"), segments[i+3:]) + case "compressed-blobs": + return digestReference{}, errCompressedResource + } + } + return digestReference{}, unparsableResource(name) +} + +func blobFromSegments(instance string, segments []string) (digestReference, error) { + if err := requireDefaultInstance(instance); err != nil { + return digestReference{}, err + } + if len(segments) < 2 { + return digestReference{}, status.Error(codes.InvalidArgument, "resource name has no blob digest") + } + if !digestPattern.MatchString(segments[0]) { + return digestReference{}, status.Error( + codes.InvalidArgument, + "resource name does not carry a lowercase SHA-256 digest", + ) + } + size, err := strconv.ParseInt(segments[1], 10, 64) + if err != nil || size < 0 { + return digestReference{}, status.Error(codes.InvalidArgument, "resource name has no valid blob size") + } + return digestReference{hash: segments[0], size: size}, nil +} + +var errCompressedResource = status.Error(codes.InvalidArgument, "compressed blobs are not supported") + +func unparsableResource(name string) error { + return status.Errorf(codes.InvalidArgument, "resource name %q does not name a CAS blob", name) +} diff --git a/internal/server/grpc_cas.go b/internal/server/grpc_cas.go new file mode 100644 index 0000000..4079413 --- /dev/null +++ b/internal/server/grpc_cas.go @@ -0,0 +1,296 @@ +package server + +import ( + "bytes" + "context" + "errors" + "fmt" + + "golang.org/x/sync/errgroup" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + + remoteexecution "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/execution/v2" +) + +// treePageSize bounds how many directories are packed into one GetTree response. +const treePageSize = 1024 + +type casService struct { + remoteexecution.UnimplementedContentAddressableStorageServer + server *Server +} + +// FindMissingBlobs is the reason this server speaks gRPC: Bazel probes the whole +// input closure of a build in a handful of calls instead of one HTTP HEAD each. +// The probes still run against the backend, so they are spread over the same +// concurrency budget as every other backend operation. +func (c *casService) FindMissingBlobs( + ctx context.Context, + request *remoteexecution.FindMissingBlobsRequest, +) (*remoteexecution.FindMissingBlobsResponse, error) { + if err := requireDefaultInstance(request.GetInstanceName()); err != nil { + return nil, err + } + if err := requireSHA256(request.GetDigestFunction()); err != nil { + return nil, err + } + digests := request.GetBlobDigests() + references := make([]digestReference, len(digests)) + for i, digest := range digests { + reference, err := requestDigest(digest, "blob_digests") + if err != nil { + return nil, err + } + references[i] = reference + } + + c.server.stats.requests.Add(1) + absent := make([]bool, len(digests)) + group, groupCtx := errgroup.WithContext(ctx) + group.SetLimit(c.server.cfg.MaxConcurrent) + for i, reference := range references { + if isImplicitEmptyDigest(reference) { + c.server.implicitEmptyCASHit() + continue + } + group.Go(func() error { + _, err := c.server.casPresence(groupCtx, reference.hash) + switch { + case err == nil: + return nil + case errors.Is(err, errCacheMiss): + absent[i] = true + return nil + default: + return grpcError("cas", reference.hash, err) + } + }) + } + if err := group.Wait(); err != nil { + return nil, err + } + + var missing []*remoteexecution.Digest + for i, isAbsent := range absent { + if isAbsent { + missing = append(missing, digests[i]) + } + } + return remoteexecution.FindMissingBlobsResponse_builder{MissingBlobDigests: missing}.Build(), nil +} + +func (c *casService) BatchUpdateBlobs( + ctx context.Context, + request *remoteexecution.BatchUpdateBlobsRequest, +) (*remoteexecution.BatchUpdateBlobsResponse, error) { + if err := requireDefaultInstance(request.GetInstanceName()); err != nil { + return nil, err + } + if err := requireSHA256(request.GetDigestFunction()); err != nil { + return nil, err + } + blobs := request.GetRequests() + var total int64 + for _, blob := range blobs { + total += int64(len(blob.GetData())) + } + if total > maxBatchSize { + return nil, status.Errorf( + codes.InvalidArgument, + "batch of %d bytes exceeds the %d byte limit", + total, + maxBatchSize, + ) + } + + c.server.stats.requests.Add(1) + responses := make([]*remoteexecution.BatchUpdateBlobsResponse_Response, len(blobs)) + for i, blob := range blobs { + digest := blob.GetDigest() + responses[i] = remoteexecution.BatchUpdateBlobsResponse_Response_builder{ + Digest: digest, + Status: status.Convert(c.updateBlob(ctx, blob)).Proto(), + }.Build() + } + return remoteexecution.BatchUpdateBlobsResponse_builder{Responses: responses}.Build(), nil +} + +func (c *casService) updateBlob( + ctx context.Context, + blob *remoteexecution.BatchUpdateBlobsRequest_Request, +) error { + if err := requireIdentity(blob.GetCompressor()); err != nil { + return err + } + reference, err := requestDigest(blob.GetDigest(), "digest") + if err != nil { + return err + } + data := blob.GetData() + if int64(len(data)) != reference.size { + return status.Errorf( + codes.InvalidArgument, + "blob is %d bytes; digest declares %d", + len(data), + reference.size, + ) + } + if reference.size > c.server.cfg.MaxBlobSize { + return status.Error(codes.InvalidArgument, "blob exceeds the configured maximum size") + } + err = c.server.writeObject(ctx, "cas", reference.hash, bytes.NewReader(data), reference.size) + if err != nil { + return grpcError("cas", reference.hash, err) + } + return nil +} + +func (c *casService) BatchReadBlobs( + ctx context.Context, + request *remoteexecution.BatchReadBlobsRequest, +) (*remoteexecution.BatchReadBlobsResponse, error) { + if err := requireDefaultInstance(request.GetInstanceName()); err != nil { + return nil, err + } + if err := requireSHA256(request.GetDigestFunction()); err != nil { + return nil, err + } + for _, compressor := range request.GetAcceptableCompressors() { + if err := requireIdentity(compressor); err != nil { + return nil, err + } + } + digests := request.GetDigests() + var total int64 + for _, digest := range digests { + total += digest.GetSizeBytes() + } + if total > maxBatchSize { + return nil, status.Errorf( + codes.InvalidArgument, + "batch of %d bytes exceeds the %d byte limit", + total, + maxBatchSize, + ) + } + + c.server.stats.requests.Add(1) + responses := make([]*remoteexecution.BatchReadBlobsResponse_Response, len(digests)) + for i, digest := range digests { + data, err := c.readBlob(ctx, digest) + responses[i] = remoteexecution.BatchReadBlobsResponse_Response_builder{ + Digest: digest, + Data: data, + Status: status.Convert(err).Proto(), + }.Build() + } + return remoteexecution.BatchReadBlobsResponse_builder{Responses: responses}.Build(), nil +} + +func (c *casService) readBlob(ctx context.Context, digest *remoteexecution.Digest) ([]byte, error) { + reference, err := requestDigest(digest, "digests") + if err != nil { + return nil, err + } + if isImplicitEmptyDigest(reference) { + c.server.implicitEmptyCASHit() + return nil, nil + } + data, err := c.server.readObjectBytes(ctx, "cas", reference.hash) + if err != nil { + return nil, grpcError("cas", reference.hash, err) + } + return data, nil +} + +// GetTree walks an output directory that was stored as individual Directory +// objects rather than as a single Tree. +func (c *casService) GetTree( + request *remoteexecution.GetTreeRequest, + stream grpc.ServerStreamingServer[remoteexecution.GetTreeResponse], +) error { + if err := requireDefaultInstance(request.GetInstanceName()); err != nil { + return err + } + if err := requireSHA256(request.GetDigestFunction()); err != nil { + return err + } + if request.GetPageToken() != "" { + return status.Error(codes.InvalidArgument, "page tokens are not supported") + } + root, err := requestDigest(request.GetRootDigest(), "root_digest") + if err != nil { + return err + } + + ctx := stream.Context() + c.server.stats.requests.Add(1) + queue := []digestReference{root} + visited := map[string]struct{}{root.hash: {}} + page := make([]*remoteexecution.Directory, 0, treePageSize) + for len(queue) > 0 { + reference := queue[0] + queue = queue[1:] + if len(visited) > maxActionResultObjects { + return status.Errorf( + codes.ResourceExhausted, + "tree references more than %d directories", + maxActionResultObjects, + ) + } + directory, err := c.loadDirectory(ctx, reference) + if err != nil { + return err + } + page = append(page, directory) + for _, child := range directory.GetDirectories() { + childReference, err := requestDigest(child.GetDigest(), "directory_node.digest") + if err != nil { + return err + } + if _, seen := visited[childReference.hash]; seen { + continue + } + visited[childReference.hash] = struct{}{} + queue = append(queue, childReference) + } + if len(page) == treePageSize { + if err := sendTreePage(stream, page); err != nil { + return err + } + page = page[:0] + } + } + if len(page) == 0 { + return nil + } + return sendTreePage(stream, page) +} + +func (c *casService) loadDirectory( + ctx context.Context, + reference digestReference, +) (*remoteexecution.Directory, error) { + data, err := c.server.readObjectBytes(ctx, "cas", reference.hash) + if err != nil { + return nil, grpcError("cas", reference.hash, err) + } + directory := &remoteexecution.Directory{} + if err := proto.Unmarshal(data, directory); err != nil { + return nil, status.Error( + codes.NotFound, + fmt.Sprintf("cas/%s is not a directory", reference.hash), + ) + } + return directory, nil +} + +func sendTreePage( + stream grpc.ServerStreamingServer[remoteexecution.GetTreeResponse], + page []*remoteexecution.Directory, +) error { + return stream.Send(remoteexecution.GetTreeResponse_builder{Directories: page}.Build()) +} diff --git a/internal/server/grpc_test.go b/internal/server/grpc_test.go new file mode 100644 index 0000000..d570764 --- /dev/null +++ b/internal/server/grpc_test.go @@ -0,0 +1,525 @@ +package server + +import ( + "context" + "errors" + "io" + "net" + "strconv" + "strings" + "testing" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/proto" + + remoteexecution "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/execution/v2" + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/google/bytestream" +) + +func testGRPCConn(t *testing.T, server *Server) *grpc.ClientConn { + t.Helper() + listener := bufconn.Listen(1024 * 1024) + handler := server.GRPCHandler() + go func() { _ = handler.Serve(listener) }() + t.Cleanup(handler.Stop) + + conn, err := grpc.NewClient( + "passthrough:///bufnet", + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { + return listener.DialContext(ctx) + }), + grpc.WithTransportCredentials(insecure.NewCredentials()), + ) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + return conn +} + +func assertCode(t *testing.T, err error, want codes.Code) { + t.Helper() + if status.Code(err) != want { + t.Fatalf("code = %s (%v), want %s", status.Code(err), err, want) + } +} + +func readResource(reference digestReference) string { + return "blobs/" + reference.hash + "/" + strconv.FormatInt(reference.size, 10) +} + +func writeResource(reference digestReference) string { + return "uploads/8c6ded1a-0f5e-4f2b-9c10-3a5f1d8b7e42/blobs/" + + reference.hash + "/" + strconv.FormatInt(reference.size, 10) +} + +func TestGRPCCapabilitiesAdvertiseSHA256AndWriteState(t *testing.T) { + for _, writeEnabled := range []bool{true, false} { + server := testServer(t, newMemoryBackend(), func(cfg *Config) { + cfg.WriteEnabled = writeEnabled + }) + client := remoteexecution.NewCapabilitiesClient(testGRPCConn(t, server)) + + capabilities, err := client.GetCapabilities( + t.Context(), + remoteexecution.GetCapabilitiesRequest_builder{}.Build(), + ) + if err != nil { + t.Fatal(err) + } + cache := capabilities.GetCacheCapabilities() + functions := cache.GetDigestFunctions() + if len(functions) != 1 || functions[0] != remoteexecution.DigestFunction_SHA256 { + t.Fatalf("digest functions = %v", functions) + } + if got := cache.GetActionCacheUpdateCapabilities().GetUpdateEnabled(); got != writeEnabled { + t.Fatalf("update_enabled = %t, want %t", got, writeEnabled) + } + if cache.GetMaxBatchTotalSizeBytes() != maxBatchSize { + t.Fatalf("max_batch_total_size_bytes = %d", cache.GetMaxBatchTotalSizeBytes()) + } + if capabilities.GetExecutionCapabilities() != nil { + t.Fatal("cache-only server advertised execution capabilities") + } + } +} + +func TestGRPCRejectsInstanceNames(t *testing.T) { + server := testServer(t, newMemoryBackend(), nil) + conn := testGRPCConn(t, server) + + _, err := remoteexecution.NewCapabilitiesClient(conn).GetCapabilities( + t.Context(), + remoteexecution.GetCapabilitiesRequest_builder{InstanceName: "other"}.Build(), + ) + assertCode(t, err, codes.InvalidArgument) + + _, err = remoteexecution.NewActionCacheClient(conn).GetActionResult( + t.Context(), + remoteexecution.GetActionResultRequest_builder{ + InstanceName: "other", + ActionDigest: digestProto(referenceFor([]byte("action"))), + }.Build(), + ) + assertCode(t, err, codes.InvalidArgument) +} + +func TestGRPCActionCacheRoundTripRequiresCompleteClosure(t *testing.T) { + output := []byte("grpc cached output") + outputReference := referenceFor(output) + actionDigest := digestProto(digestReference{hash: strings.Repeat("a", 64), size: 7}) + result := remoteexecution.ActionResult_builder{ + OutputFiles: []*remoteexecution.OutputFile{outputFileProto(outputReference, nil)}, + }.Build() + + t.Run("complete", func(t *testing.T) { + backend := newMemoryBackend() + backend.objects["test-v1-cas-"+outputReference.hash] = output + server := testServer(t, backend, nil) + client := remoteexecution.NewActionCacheClient(testGRPCConn(t, server)) + + _, err := client.UpdateActionResult(t.Context(), remoteexecution.UpdateActionResultRequest_builder{ + ActionDigest: actionDigest, + ActionResult: result, + }.Build()) + if err != nil { + t.Fatal(err) + } + got, err := client.GetActionResult(t.Context(), remoteexecution.GetActionResultRequest_builder{ + ActionDigest: actionDigest, + }.Build()) + if err != nil { + t.Fatal(err) + } + if !proto.Equal(got, result) { + t.Fatalf("action result = %v, want %v", got, result) + } + }) + + t.Run("missing output", func(t *testing.T) { + server := testServer(t, newMemoryBackend(), nil) + client := remoteexecution.NewActionCacheClient(testGRPCConn(t, server)) + + // The upload is accepted but never published, so the read misses. + if _, err := client.UpdateActionResult(t.Context(), remoteexecution.UpdateActionResultRequest_builder{ + ActionDigest: actionDigest, + ActionResult: result, + }.Build()); err != nil { + t.Fatal(err) + } + _, err := client.GetActionResult(t.Context(), remoteexecution.GetActionResultRequest_builder{ + ActionDigest: actionDigest, + }.Build()) + assertCode(t, err, codes.NotFound) + if stats := server.Snapshot(); stats.SkippedActionResultUploads != 1 { + t.Fatalf("unexpected stats: %+v", stats) + } + }) +} + +func TestGRPCFindMissingBlobsBatchesPresenceChecks(t *testing.T) { + present := []byte("present blob") + presentReference := referenceFor(present) + absentReference := referenceFor([]byte("absent blob")) + emptyReference := referenceFor(nil) + + backend := newMemoryBackend() + backend.objects["test-v1-cas-"+presentReference.hash] = present + server := testServer(t, backend, nil) + client := remoteexecution.NewContentAddressableStorageClient(testGRPCConn(t, server)) + + response, err := client.FindMissingBlobs(t.Context(), remoteexecution.FindMissingBlobsRequest_builder{ + BlobDigests: []*remoteexecution.Digest{ + digestProto(presentReference), + digestProto(absentReference), + digestProto(emptyReference), + }, + }.Build()) + if err != nil { + t.Fatal(err) + } + missing := response.GetMissingBlobDigests() + if len(missing) != 1 || missing[0].GetHash() != absentReference.hash { + t.Fatalf("missing = %v, want only %s", missing, absentReference.hash) + } + // All presence checks are answered from the manifest view or locally. + if calls := backend.existsCount(); calls != 0 { + t.Fatalf("backend existence checks = %d, want none", calls) + } +} + +func TestGRPCBatchUpdateAndReadBlobs(t *testing.T) { + blob := []byte("batched blob") + reference := referenceFor(blob) + mismatched := referenceFor([]byte("different blob")) + server := testServer(t, newMemoryBackend(), nil) + client := remoteexecution.NewContentAddressableStorageClient(testGRPCConn(t, server)) + + update, err := client.BatchUpdateBlobs(t.Context(), remoteexecution.BatchUpdateBlobsRequest_builder{ + Requests: []*remoteexecution.BatchUpdateBlobsRequest_Request{ + remoteexecution.BatchUpdateBlobsRequest_Request_builder{ + Digest: digestProto(reference), + Data: blob, + }.Build(), + remoteexecution.BatchUpdateBlobsRequest_Request_builder{ + Digest: digestProto(digestReference{hash: mismatched.hash, size: reference.size}), + Data: blob, + }.Build(), + }, + }.Build()) + if err != nil { + t.Fatal(err) + } + responses := update.GetResponses() + if len(responses) != 2 { + t.Fatalf("responses = %d, want 2", len(responses)) + } + if code := codes.Code(responses[0].GetStatus().GetCode()); code != codes.OK { + t.Fatalf("first upload status = %s", code) + } + if code := codes.Code(responses[1].GetStatus().GetCode()); code != codes.InvalidArgument { + t.Fatalf("mismatched upload status = %s, want InvalidArgument", code) + } + + read, err := client.BatchReadBlobs(t.Context(), remoteexecution.BatchReadBlobsRequest_builder{ + Digests: []*remoteexecution.Digest{ + digestProto(reference), + digestProto(referenceFor([]byte("never uploaded"))), + }, + }.Build()) + if err != nil { + t.Fatal(err) + } + items := read.GetResponses() + if len(items) != 2 { + t.Fatalf("responses = %d, want 2", len(items)) + } + if string(items[0].GetData()) != string(blob) { + t.Fatalf("blob = %q", items[0].GetData()) + } + if code := codes.Code(items[1].GetStatus().GetCode()); code != codes.NotFound { + t.Fatalf("absent blob status = %s, want NotFound", code) + } +} + +func TestGRPCBatchRejectsOversizedRequests(t *testing.T) { + server := testServer(t, newMemoryBackend(), nil) + client := remoteexecution.NewContentAddressableStorageClient(testGRPCConn(t, server)) + + _, err := client.BatchReadBlobs(t.Context(), remoteexecution.BatchReadBlobsRequest_builder{ + Digests: []*remoteexecution.Digest{ + digestProto(digestReference{hash: strings.Repeat("b", 64), size: maxBatchSize + 1}), + }, + }.Build()) + assertCode(t, err, codes.InvalidArgument) +} + +// Probing the same blobs over either transport must touch the same number of +// objects and the same number of backend entries; only the number of client +// calls differs, which is what makes batching visible in the statistics. +func TestAccountingSeparatesCallsFromObjectsAndBackendEntries(t *testing.T) { + present := []byte("present blob") + presentReference := referenceFor(present) + absent := referenceFor([]byte("absent blob")) + empty := referenceFor(nil) + + newServer := func(t *testing.T) *Server { + backend := newMemoryBackend() + backend.objects["test-v1-cas-"+presentReference.hash] = present + return testServer(t, backend, nil) + } + + t.Run("http", func(t *testing.T) { + server := newServer(t) + for _, reference := range []digestReference{presentReference, absent, empty} { + headCacheObject(server, "/cas/"+reference.hash) + } + stats := server.Snapshot() + if stats.Requests != 3 || stats.Operations != 3 || stats.BackendRequests != 0 { + t.Fatalf("unexpected stats: %+v", stats) + } + }) + + t.Run("grpc", func(t *testing.T) { + server := newServer(t) + client := remoteexecution.NewContentAddressableStorageClient(testGRPCConn(t, server)) + _, err := client.FindMissingBlobs(t.Context(), remoteexecution.FindMissingBlobsRequest_builder{ + BlobDigests: []*remoteexecution.Digest{ + digestProto(presentReference), + digestProto(absent), + digestProto(empty), + }, + }.Build()) + if err != nil { + t.Fatal(err) + } + stats := server.Snapshot() + if stats.Requests != 1 || stats.Operations != 3 || stats.BackendRequests != 0 { + t.Fatalf("unexpected stats: %+v", stats) + } + }) +} + +func TestGRPCByteStreamRoundTrip(t *testing.T) { + blob := []byte("a reasonably long byte stream payload") + reference := referenceFor(blob) + server := testServer(t, newMemoryBackend(), nil) + client := bytestream.NewByteStreamClient(testGRPCConn(t, server)) + + stream, err := client.Write(t.Context()) + if err != nil { + t.Fatal(err) + } + split := 10 + send := func(offset int64, data []byte, finish bool) { + t.Helper() + err := stream.Send(bytestream.WriteRequest_builder{ + ResourceName: writeResource(reference), + WriteOffset: offset, + Data: data, + FinishWrite: finish, + }.Build()) + if err != nil { + t.Fatal(err) + } + } + send(0, blob[:split], false) + send(int64(split), blob[split:], true) + response, err := stream.CloseAndRecv() + if err != nil { + t.Fatal(err) + } + if response.GetCommittedSize() != reference.size { + t.Fatalf("committed_size = %d, want %d", response.GetCommittedSize(), reference.size) + } + + for _, test := range []struct { + name string + offset int64 + limit int64 + want string + }{ + {name: "whole blob", want: string(blob)}, + {name: "from offset", offset: 2, want: string(blob[2:])}, + {name: "limited", limit: 6, want: string(blob[:6])}, + } { + t.Run(test.name, func(t *testing.T) { + reads, err := client.Read(t.Context(), bytestream.ReadRequest_builder{ + ResourceName: readResource(reference), + ReadOffset: test.offset, + ReadLimit: test.limit, + }.Build()) + if err != nil { + t.Fatal(err) + } + var got []byte + for { + chunk, err := reads.Recv() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + t.Fatal(err) + } + got = append(got, chunk.GetData()...) + } + if string(got) != test.want { + t.Fatalf("read = %q, want %q", got, test.want) + } + }) + } +} + +func TestGRPCByteStreamRejectsMalformedWrites(t *testing.T) { + blob := []byte("stream payload") + reference := referenceFor(blob) + server := testServer(t, newMemoryBackend(), nil) + client := bytestream.NewByteStreamClient(testGRPCConn(t, server)) + + write := func(t *testing.T, requests ...*bytestream.WriteRequest) error { + t.Helper() + stream, err := client.Write(t.Context()) + if err != nil { + t.Fatal(err) + } + for _, request := range requests { + if err := stream.Send(request); err != nil { + break + } + } + _, err = stream.CloseAndRecv() + return err + } + + t.Run("digest mismatch", func(t *testing.T) { + other := referenceFor([]byte("something else")) + err := write(t, bytestream.WriteRequest_builder{ + ResourceName: writeResource(digestReference{hash: other.hash, size: reference.size}), + Data: blob, + FinishWrite: true, + }.Build()) + assertCode(t, err, codes.InvalidArgument) + }) + + t.Run("non-contiguous offset", func(t *testing.T) { + err := write(t, + bytestream.WriteRequest_builder{ + ResourceName: writeResource(reference), + Data: blob[:4], + }.Build(), + bytestream.WriteRequest_builder{ + ResourceName: writeResource(reference), + WriteOffset: 99, + Data: blob[4:], + FinishWrite: true, + }.Build(), + ) + assertCode(t, err, codes.InvalidArgument) + }) + + t.Run("ended before finish_write", func(t *testing.T) { + err := write(t, bytestream.WriteRequest_builder{ + ResourceName: writeResource(reference), + Data: blob[:4], + }.Build()) + assertCode(t, err, codes.InvalidArgument) + }) + + t.Run("compressed resource", func(t *testing.T) { + err := write(t, bytestream.WriteRequest_builder{ + ResourceName: "uploads/id/compressed-blobs/zstd/" + reference.hash + "/14", + Data: blob, + FinishWrite: true, + }.Build()) + assertCode(t, err, codes.InvalidArgument) + }) +} + +func TestGRPCByteStreamReadRejectsOutOfRangeOffset(t *testing.T) { + blob := []byte("short") + reference := referenceFor(blob) + backend := newMemoryBackend() + backend.objects["test-v1-cas-"+reference.hash] = blob + server := testServer(t, backend, nil) + client := bytestream.NewByteStreamClient(testGRPCConn(t, server)) + + stream, err := client.Read(t.Context(), bytestream.ReadRequest_builder{ + ResourceName: readResource(reference), + ReadOffset: reference.size + 1, + }.Build()) + if err != nil { + t.Fatal(err) + } + _, err = stream.Recv() + assertCode(t, err, codes.OutOfRange) +} + +func TestGRPCQueryWriteStatusReportsNoProgress(t *testing.T) { + server := testServer(t, newMemoryBackend(), nil) + client := bytestream.NewByteStreamClient(testGRPCConn(t, server)) + + _, err := client.QueryWriteStatus(t.Context(), bytestream.QueryWriteStatusRequest_builder{ + ResourceName: writeResource(referenceFor([]byte("anything"))), + }.Build()) + assertCode(t, err, codes.NotFound) +} + +func TestGRPCGetTreeStreamsNestedDirectories(t *testing.T) { + file := referenceFor([]byte("nested file")) + child := marshalProto(t, remoteexecution.Directory_builder{ + Files: []*remoteexecution.FileNode{fileNodeProto(file)}, + }.Build()) + childReference := referenceFor(child) + root := marshalProto(t, remoteexecution.Directory_builder{ + Directories: []*remoteexecution.DirectoryNode{directoryNodeProto(childReference)}, + }.Build()) + rootReference := referenceFor(root) + + backend := newMemoryBackend() + backend.objects["test-v1-cas-"+rootReference.hash] = root + backend.objects["test-v1-cas-"+childReference.hash] = child + server := testServer(t, backend, nil) + client := remoteexecution.NewContentAddressableStorageClient(testGRPCConn(t, server)) + + stream, err := client.GetTree(t.Context(), remoteexecution.GetTreeRequest_builder{ + RootDigest: digestProto(rootReference), + }.Build()) + if err != nil { + t.Fatal(err) + } + var directories []*remoteexecution.Directory + for { + page, err := stream.Recv() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + t.Fatal(err) + } + directories = append(directories, page.GetDirectories()...) + } + if len(directories) != 2 { + t.Fatalf("directories = %d, want 2", len(directories)) + } + if got := directories[1].GetFiles(); len(got) != 1 || got[0].GetDigest().GetHash() != file.hash { + t.Fatalf("child directory = %v", directories[1]) + } +} + +func TestGRPCGetTreeRejectsMissingRoot(t *testing.T) { + server := testServer(t, newMemoryBackend(), nil) + client := remoteexecution.NewContentAddressableStorageClient(testGRPCConn(t, server)) + + stream, err := client.GetTree(t.Context(), remoteexecution.GetTreeRequest_builder{ + RootDigest: digestProto(referenceFor([]byte("absent root"))), + }.Build()) + if err != nil { + t.Fatal(err) + } + _, err = stream.Recv() + assertCode(t, err, codes.NotFound) +} diff --git a/internal/server/layout.go b/internal/server/layout.go new file mode 100644 index 0000000..2c05004 --- /dev/null +++ b/internal/server/layout.go @@ -0,0 +1,282 @@ +package server + +import ( + "context" + "errors" + "fmt" + "sort" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/cache" +) + +// LayoutPack is an existing pack as the manifest DAG declares it. Declared +// totals cover everything the pack holds, including copies that lost the merge. +type LayoutPack struct { + ID string + Key string + StoredSize int64 + DeclaredBytes int64 + DeclaredCount int + // Since is when the pack's contents took their current shape, if its + // manifest records it. Otherwise the cache entry's creation time stands in. + Since time.Time +} + +// LayoutEntry is the copy of a digest a reader would actually be served. +type LayoutEntry struct { + Kind string + Digest string + CID string + Block string + Encoding string + Pack string + Size int64 +} + +// LayoutManifest names a manifest that contributed to the merged view. +type LayoutManifest struct { + ID string + Key string + Pack string +} + +// Layout is the merged manifest view, built by the same tie-breaks a cache +// server uses so that anything reasoning about the stored layout resolves a +// digest to the copy readers get. +type Layout struct { + Packs []LayoutPack + Entries []LayoutEntry + Manifests []LayoutManifest + // Heads are the manifests no other manifest claims as a parent. A manifest + // published afterwards names them so the DAG stays connected. + Heads []string + // OrphanPacks are listed packs no live manifest declares. They are reported + // rather than acted on: a pack a concurrent job has published but not yet + // committed a manifest for is indistinguishable from a truly orphaned one. + OrphanPacks int + // UnmanifestedPacks are the subset of OrphanPacks that no manifest key names + // at all. A pack whose manifest merely failed to load is excluded, because + // another ref may still be reading it. + UnmanifestedPacks []LayoutPack + // OrphanManifests counts manifests whose pack is gone, which + // PacklessManifests lists. Readers leave them unread so they expire, and a + // reaping pass can remove them sooner. + OrphanManifests int + PacklessManifests []LayoutManifest + // UnreadableManifests were listed but could not be restored, because they + // belong to another ref's cache scope or were evicted. A plan then rests on + // the part of the layout this job can actually see. + UnreadableManifests int +} + +type LayoutOptions struct { + Backend cache.Backend + Catalog cache.Catalog + KeyPrefix string + MaxBlobSize int64 + Timeout time.Duration + Warn func(string, ...any) +} + +// ManifestKey names the cache entry a manifest is committed under. +func ManifestKey(prefix, packID, manifestID string) string { + return manifestKeyFor(prefix, packID, manifestID) +} + +// ManifestKeyPrefix is the key namespace every manifest is stored under. +func ManifestKeyPrefix(prefix string) string { + return manifestKeyPrefix(prefix) +} + +// PackKeyPrefix is the key namespace every pack is stored under. +func PackKeyPrefix(prefix string) string { + return packKeyFor(prefix, "") +} + +// ReadLayout discovers and merges the manifest DAG. It publishes nothing, and +// the listings it relies on read metadata only. +func ReadLayout(ctx context.Context, options LayoutOptions) (Layout, error) { + if options.Backend == nil || options.Catalog == nil { + return Layout{}, errors.New("reading the layout needs a backend and a catalog") + } + if options.Warn == nil { + options.Warn = func(string, ...any) {} + } + if options.MaxBlobSize <= 0 { + options.MaxBlobSize = 512 * 1024 * 1024 + } + + manifestKeys, err := options.Catalog.List(ctx, manifestKeyPrefix(options.KeyPrefix)) + if err != nil { + return Layout{}, err + } + packKeys, err := options.Catalog.List(ctx, packKeyFor(options.KeyPrefix, "")) + if err != nil { + return Layout{}, err + } + listedPacks := make(map[string]struct{}, len(packKeys)) + for _, key := range packKeys { + if id, ok := parsePackKey(options.KeyPrefix, key); ok { + listedPacks[id] = struct{}{} + } + } + + layout := Layout{} + decoded := make(map[string]manifest, len(manifestKeys)) + references := make(map[string]LayoutManifest, len(manifestKeys)) + // Every pack some manifest key names, whether or not that manifest could be + // read. A pack missing from this has no manifest at all, which is a very + // different thing from one whose manifest this job cannot restore. + manifested := make(map[string]struct{}, len(manifestKeys)) + for _, key := range manifestKeys { + packID, manifestID, ok := parseManifestKey(options.KeyPrefix, key) + if !ok { + continue + } + manifested[packID] = struct{}{} + if _, listed := listedPacks[packID]; !listed { + layout.OrphanManifests++ + layout.PacklessManifests = append(layout.PacklessManifests, + LayoutManifest{ID: manifestID, Key: key, Pack: packID}) + continue + } + value, err := loadManifestFrom(ctx, options, key, manifestID) + if err != nil { + // The REST listing reports entries this job's cache scope cannot + // restore, and entries evicted since it was taken, so this is routine. + // Skipping is safe because packs enter the layout only through a + // manifest that loaded: one that did not is never a deletion candidate. + layout.UnreadableManifests++ + options.Warn("skipping manifest %s: %s", manifestID, safeError(err)) + continue + } + if len(value.Packs) != 1 || value.Packs[0].ID != packID { + // Readers skip this deterministically, so the merged view matches + // theirs by skipping it too. + options.Warn("ignoring manifest %s: it does not commit the pack %s named by its key", manifestID, packID) + continue + } + decoded[manifestID] = value + references[manifestID] = LayoutManifest{ID: manifestID, Key: key, Pack: packID} + } + + packs := make(map[string]packDescriptor) + declaredBytes := make(map[string]int64) + declaredCount := make(map[string]int) + casWinners := make(map[string]manifestObject) + actionWinners := make(map[string]manifestAction) + conflicts := make(map[string]struct{}) + + ids := make([]string, 0, len(decoded)) + for id := range decoded { + ids = append(ids, id) + } + sort.Strings(ids) + heads := manifestHeads(decoded) + for _, id := range ids { + value := decoded[id] + for _, descriptor := range value.Packs { + if existing, found := packs[descriptor.ID]; !found || preferPack(descriptor, existing) { + packs[descriptor.ID] = descriptor + } + } + for _, object := range value.CAS { + declaredBytes[object.PackID] += object.Size + declaredCount[object.PackID]++ + if existing, found := casWinners[object.Digest]; !found || preferObject(object, existing) { + casWinners[object.Digest] = object + } + } + for _, action := range value.Actions { + declaredBytes[action.PackID] += action.Size + declaredCount[action.PackID]++ + existing, found := actionWinners[action.Digest] + if found && existing.CID != action.CID { + conflicts[action.Digest] = struct{}{} + } + if !found || preferAction(action, existing) { + actionWinners[action.Digest] = action + } + } + } + for packID := range listedPacks { + if _, declared := packs[packID]; declared { + continue + } + layout.OrphanPacks++ + if _, named := manifested[packID]; !named { + layout.UnmanifestedPacks = append(layout.UnmanifestedPacks, LayoutPack{ + ID: packID, + Key: packKeyFor(options.KeyPrefix, packID), + }) + } + } + sort.Slice(layout.UnmanifestedPacks, func(i, j int) bool { + return layout.UnmanifestedPacks[i].ID < layout.UnmanifestedPacks[j].ID + }) + sort.Slice(layout.PacklessManifests, func(i, j int) bool { + return layout.PacklessManifests[i].Key < layout.PacklessManifests[j].Key + }) + + for _, id := range ids { + layout.Manifests = append(layout.Manifests, references[id]) + if _, head := heads[id]; head { + layout.Heads = append(layout.Heads, id) + } + } + for _, descriptor := range packs { + pack := LayoutPack{ + ID: descriptor.ID, + Key: descriptor.Key, + StoredSize: descriptor.Size, + DeclaredBytes: declaredBytes[descriptor.ID], + DeclaredCount: declaredCount[descriptor.ID], + } + if descriptor.Since > 0 { + pack.Since = time.Unix(descriptor.Since, 0).UTC() + } + layout.Packs = append(layout.Packs, pack) + } + sort.Slice(layout.Packs, func(i, j int) bool { return layout.Packs[i].ID < layout.Packs[j].ID }) + + for _, object := range casWinners { + layout.Entries = append(layout.Entries, LayoutEntry{ + Kind: "cas", Digest: object.Digest, CID: object.CID, Block: object.Block, + Encoding: object.Encoding, Pack: object.PackID, Size: object.Size, + }) + } + if len(conflicts) > 0 { + options.Warn("%d action keys have more than one stored result; only the served copy is kept", len(conflicts)) + } + for _, action := range actionWinners { + layout.Entries = append(layout.Entries, LayoutEntry{ + Kind: "ac", Digest: action.Digest, CID: action.CID, Block: action.Block, + Encoding: action.Encoding, Pack: action.PackID, Size: action.Size, + }) + } + sort.Slice(layout.Entries, func(i, j int) bool { + if layout.Entries[i].Kind != layout.Entries[j].Kind { + return layout.Entries[i].Kind < layout.Entries[j].Kind + } + return layout.Entries[i].Digest < layout.Entries[j].Digest + }) + return layout, nil +} + +func loadManifestFrom(ctx context.Context, options LayoutOptions, key, id string) (manifest, error) { + var data bytesBuffer + loadCtx, cancel := context.WithTimeout(ctx, options.Timeout) + found, err := options.Backend.Load(loadCtx, key, &data) + cancel() + if err != nil { + return manifest{}, err + } + if !found { + return manifest{}, errors.New("manifest cache entry is missing") + } + if int64(data.Len()) > options.MaxBlobSize { + return manifest{}, fmt.Errorf("manifest exceeds the maximum object size") + } + return decodeManifest(data.Bytes(), id) +} diff --git a/internal/server/limiter.go b/internal/server/limiter.go index fa314f2..8a70987 100644 --- a/internal/server/limiter.go +++ b/internal/server/limiter.go @@ -6,11 +6,11 @@ import ( "time" ) -// intervalLimiter spaces reservations evenly to stay below GitHub's documented +// intervalLimiter spaces upload starts evenly to stay below GitHub's documented // 200 cache uploads/minute limit. It deliberately has no burst allowance. type intervalLimiter struct { mu sync.Mutex - next time.Time + last time.Time interval time.Duration } @@ -25,25 +25,37 @@ func (l *intervalLimiter) wait(ctx context.Context) (bool, error) { if l.interval == 0 { return false, nil } - l.mu.Lock() - now := time.Now() - slot := now - if l.next.After(now) { - slot = l.next + waited := false + for { + if err := ctx.Err(); err != nil { + return waited, err + } + delay := l.claimStart() + if delay <= 0 { + return waited, nil + } + waited = true + timer := time.NewTimer(delay) + select { + case <-ctx.Done(): + timer.Stop() + return true, ctx.Err() + case <-timer.C: + } } - l.next = slot.Add(l.interval) - l.mu.Unlock() +} - delay := time.Until(slot) - if delay <= 0 { - return false, nil +func (l *intervalLimiter) claimStart() time.Duration { + if l.interval == 0 { + return 0 } - timer := time.NewTimer(delay) - defer timer.Stop() - select { - case <-ctx.Done(): - return true, ctx.Err() - case <-timer.C: - return true, nil + l.mu.Lock() + defer l.mu.Unlock() + now := time.Now() + eligible := l.last.Add(l.interval) + if !l.last.IsZero() && now.Before(eligible) { + return time.Until(eligible) } + l.last = now + return 0 } diff --git a/internal/server/manifest.go b/internal/server/manifest.go index c53fb55..730e689 100644 --- a/internal/server/manifest.go +++ b/internal/server/manifest.go @@ -16,7 +16,14 @@ import ( "github.com/multiformats/go-multihash" ) -const manifestFormatVersion = 1 +// Format 2 adds per-block encoding. Readers still accept format 1, where every +// block is stored verbatim. +const ( + manifestFormatVersion = 2 + minManifestFormatVersion = 1 + + manifestMinDecodeBudget int64 = 10 << 20 +) type manifest struct { Version int64 @@ -26,25 +33,51 @@ type manifest struct { Actions []manifestAction } +func manifestHeads(manifests map[string]manifest) map[string]struct{} { + parents := make(map[string]struct{}) + for _, value := range manifests { + for _, parent := range value.Parents { + parents[parent] = struct{}{} + } + } + heads := make(map[string]struct{}, len(manifests)) + for id := range manifests { + if _, isParent := parents[id]; !isParent { + heads[id] = struct{}{} + } + } + return heads +} + +// Since, when set, is when the pack's contents took their current shape, in +// Unix seconds. A pack rewritten only to drop stale entries keeps its source's +// value, so dropping entries never makes a pack look newly shaped. Readers +// that predate it ignore it. type packDescriptor struct { - ID string - Key string - Size int64 + ID string + Key string + Size int64 + Since int64 } +// Block names the stored bytes, which differ from CID when Encoding is set. +// CID always addresses the object itself, so it stays the logical identity. type manifestObject struct { - Digest string - CID string - PackID string - Size int64 + Digest string + CID string + Block string + Encoding string + PackID string + Size int64 } type manifestAction struct { - Digest string - CID string - PackID string - Size int64 - ClosurePacks []string + Digest string + CID string + Block string + Encoding string + PackID string + Size int64 } func encodeManifest(value manifest) ([]byte, string, error) { @@ -74,7 +107,17 @@ func decodeManifest(data []byte, expectedCID string) (manifest, error) { return manifest{}, fmt.Errorf("manifest CID mismatch: expected %s, got %s", expectedCID, actual) } } - node, err := ipld.Decode(data, dagcbor.Decode) + // The decoder's default allocation budget (~10M units) rejects manifests for + // packs of many small objects. Well-formed DAG-CBOR is charged at most ~6 + // units per input byte, and the input is already in memory, so scaling the + // budget with its length admits any valid manifest while still bounding + // amplification. + budget := int64(len(data)) * 8 + if budget < manifestMinDecodeBudget { + budget = manifestMinDecodeBudget + } + decoder := dagcbor.DecodeOptions{AllowLinks: true, AllocationBudget: budget} + node, err := ipld.Decode(data, decoder.Decode) if err != nil { return manifest{}, fmt.Errorf("decode DAG-CBOR manifest: %w", err) } @@ -82,7 +125,7 @@ func decodeManifest(data []byte, expectedCID string) (manifest, error) { } func manifestToNode(value manifest) (datamodel.Node, error) { - if value.Version != manifestFormatVersion { + if value.Version < minManifestFormatVersion || value.Version > manifestFormatVersion { return nil, fmt.Errorf("unsupported manifest version %d", value.Version) } parents := append([]string(nil), value.Parents...) @@ -99,10 +142,10 @@ func manifestToNode(value manifest) (datamodel.Node, error) { if err != nil { return nil, err } - if err := assembleManifestActions(assembler, actions); err != nil { + if err := assembleManifestActions(assembler, actions, value.Version); err != nil { return nil, err } - if err := assembleManifestCAS(assembler, cas); err != nil { + if err := assembleManifestCAS(assembler, cas, value.Version); err != nil { return nil, err } if err := assembleManifestPacks(assembler, packs); err != nil { @@ -120,7 +163,7 @@ func manifestToNode(value manifest) (datamodel.Node, error) { return builder.Build(), nil } -func assembleManifestActions(assembler datamodel.MapAssembler, actions []manifestAction) error { +func assembleManifestActions(assembler datamodel.MapAssembler, actions []manifestAction, version int64) error { if err := assembler.AssembleKey().AssignString("actions"); err != nil { return err } @@ -128,23 +171,31 @@ func assembleManifestActions(assembler datamodel.MapAssembler, actions []manifes if err != nil { return err } + encoded := version >= manifestFormatVersion for _, action := range actions { - closure := append([]string(nil), action.ClosurePacks...) - sort.Strings(closure) - mapAssembler, err := list.AssembleValue().BeginMap(5) - if err != nil { - return err - } - for _, field := range []struct{ key, value string }{ + fields := []struct{ key, value string }{ {"cid", action.CID}, {"digest", action.Digest}, {"pack", action.PackID}, - } { + } + if encoded && (action.Encoding != blockEncodingRaw || action.Block != action.CID) { + fields = append(fields, + struct{ key, value string }{"block", action.Block}, + struct{ key, value string }{"encoding", action.Encoding}, + ) + } + mapAssembler, err := list.AssembleValue().BeginMap(int64(len(fields)) + 2) + if err != nil { + return err + } + sort.Slice(fields, func(i, j int) bool { return fields[i].key < fields[j].key }) + for _, field := range fields { if err := assembleString(mapAssembler, field.key, field.value); err != nil { return err } } - if err := assembleStringList(mapAssembler, "closure", closure); err != nil { + // Keep the field for format 2 readers, but do not retain unused IDs. + if err := assembleStringList(mapAssembler, "closure", nil); err != nil { return err } if err := assembleInt(mapAssembler, "size", action.Size); err != nil { @@ -157,7 +208,7 @@ func assembleManifestActions(assembler datamodel.MapAssembler, actions []manifes return list.Finish() } -func assembleManifestCAS(assembler datamodel.MapAssembler, objects []manifestObject) error { +func assembleManifestCAS(assembler datamodel.MapAssembler, objects []manifestObject, version int64) error { if err := assembler.AssembleKey().AssignString("cas"); err != nil { return err } @@ -165,16 +216,25 @@ func assembleManifestCAS(assembler datamodel.MapAssembler, objects []manifestObj if err != nil { return err } + encoded := version >= manifestFormatVersion for _, object := range objects { - mapAssembler, err := list.AssembleValue().BeginMap(4) - if err != nil { - return err - } - for _, field := range []struct{ key, value string }{ + fields := []struct{ key, value string }{ {"cid", object.CID}, {"digest", object.Digest}, {"pack", object.PackID}, - } { + } + if encoded && (object.Encoding != blockEncodingRaw || object.Block != object.CID) { + fields = append(fields, + struct{ key, value string }{"block", object.Block}, + struct{ key, value string }{"encoding", object.Encoding}, + ) + } + mapAssembler, err := list.AssembleValue().BeginMap(int64(len(fields)) + 1) + if err != nil { + return err + } + sort.Slice(fields, func(i, j int) bool { return fields[i].key < fields[j].key }) + for _, field := range fields { if err := assembleString(mapAssembler, field.key, field.value); err != nil { return err } @@ -198,7 +258,11 @@ func assembleManifestPacks(assembler datamodel.MapAssembler, packs []packDescrip return err } for _, pack := range packs { - mapAssembler, err := list.AssembleValue().BeginMap(3) + fields := int64(3) + if pack.Since > 0 { + fields++ + } + mapAssembler, err := list.AssembleValue().BeginMap(fields) if err != nil { return err } @@ -211,6 +275,11 @@ func assembleManifestPacks(assembler datamodel.MapAssembler, packs []packDescrip if err := assembleInt(mapAssembler, "size", pack.Size); err != nil { return err } + if pack.Since > 0 { + if err := assembleInt(mapAssembler, "since", pack.Since); err != nil { + return err + } + } if err := mapAssembler.Finish(); err != nil { return err } @@ -256,7 +325,7 @@ func nodeToManifest(node datamodel.Node) (manifest, error) { if err != nil { return manifest{}, err } - if version != manifestFormatVersion { + if version < minManifestFormatVersion || version > manifestFormatVersion { return manifest{}, fmt.Errorf("unsupported manifest version %d", version) } parents, err := nodeStringList(node, "parents") @@ -275,6 +344,17 @@ func nodeToManifest(node datamodel.Node) (manifest, error) { if err != nil { return manifest{}, err } + packIDs := make(map[string]string, len(packs)) + for _, pack := range packs { + packIDs[pack.ID] = pack.ID + } + // Reuse the descriptor's string storage for every entry in its pack. + for i := range cas { + cas[i].PackID = packIDs[cas[i].PackID] + } + for i := range actions { + actions[i].PackID = packIDs[actions[i].PackID] + } value := manifest{Version: version, Parents: parents, Packs: packs, CAS: cas, Actions: actions} if err := value.validate(); err != nil { return manifest{}, err @@ -288,7 +368,7 @@ func (value manifest) validate() error { } packIDs := make(map[string]struct{}, len(value.Packs)) for _, pack := range value.Packs { - if !digestPattern.MatchString(pack.ID) || pack.Size <= 0 || pack.Key == "" || pack.Key != packKeyFor("", pack.ID) && !stringsHasSuffix(pack.Key, "-car-pack-v1-"+pack.ID) { + if !digestPattern.MatchString(pack.ID) || pack.Size <= 0 || pack.Since < 0 || pack.Key == "" || pack.Key != packKeyFor("", pack.ID) && !stringsHasSuffix(pack.Key, "-car-pack-v1-"+pack.ID) { return errors.New("manifest has invalid pack descriptor") } if _, duplicate := packIDs[pack.ID]; duplicate { @@ -301,6 +381,9 @@ func (value manifest) validate() error { if !digestPattern.MatchString(object.Digest) || object.Size < 0 || !validRawCID(object.CID, object.Digest) { return errors.New("manifest has invalid CAS entry") } + if err := validateStoredBlock(object.CID, object.Block, object.Encoding); err != nil { + return err + } if _, ok := packIDs[object.PackID]; !ok { return errors.New("CAS entry references an undeclared pack") } @@ -314,14 +397,12 @@ func (value manifest) validate() error { if !digestPattern.MatchString(action.Digest) || action.Size < 0 || !validCID(action.CID) { return errors.New("manifest has invalid action entry") } + if err := validateStoredBlock(action.CID, action.Block, action.Encoding); err != nil { + return err + } if _, ok := packIDs[action.PackID]; !ok { return errors.New("action entry references an undeclared pack") } - for _, packID := range action.ClosurePacks { - if _, ok := packIDs[packID]; !ok && !digestPattern.MatchString(packID) { - return errors.New("action closure has invalid pack ID") - } - } if _, duplicate := seenActions[action.Digest]; duplicate { return errors.New("manifest repeats an action digest") } @@ -359,7 +440,13 @@ func nodePacks(node datamodel.Node) ([]packDescriptor, error) { if err != nil { return nil, err } - values = append(values, packDescriptor{ID: id, Key: key, Size: size}) + var since int64 + if _, err := item.LookupByString("since"); err == nil { + if since, err = nodeInt(item, "since"); err != nil { + return nil, err + } + } + values = append(values, packDescriptor{ID: id, Key: key, Size: size, Since: since}) } return values, nil } @@ -413,15 +500,61 @@ func nodeActions(node datamodel.Node) ([]manifestAction, error) { if err != nil { return nil, err } - closure, err := nodeStringList(item, "closure") + closure, err := item.LookupByString("closure") + if err != nil || closure.Kind() != datamodel.Kind_List { + return nil, errors.New("manifest closure must be a list") + } + closureIterator := closure.ListIterator() + for !closureIterator.Done() { + _, pack, err := closureIterator.Next() + if err != nil || pack.Kind() != datamodel.Kind_String { + return nil, errors.New("manifest closure must contain strings") + } + packID, err := pack.AsString() + if err != nil { + return nil, err + } + if !digestPattern.MatchString(packID) { + return nil, errors.New("action closure has invalid pack ID") + } + } + block, encoding, err := nodeBlockEncoding(item, contentCID) if err != nil { return nil, err } - values = append(values, manifestAction{Digest: digest, CID: contentCID, PackID: packID, Size: size, ClosurePacks: closure}) + values = append(values, manifestAction{ + Digest: digest, + CID: contentCID, + Block: block, + Encoding: encoding, + PackID: packID, + Size: size, + }) } return values, nil } +// nodeBlockEncoding reads the format 2 fields, defaulting to a verbatim block +// so a format 1 manifest keeps working. +func nodeBlockEncoding(node datamodel.Node, contentCID string) (string, string, error) { + encodingNode, err := node.LookupByString("encoding") + if err != nil { + return contentCID, blockEncodingRaw, nil + } + if encodingNode.Kind() != datamodel.Kind_String { + return "", "", errors.New("manifest encoding must be a string") + } + encoding, err := encodingNode.AsString() + if err != nil { + return "", "", err + } + block, err := nodeString(node, "block") + if err != nil { + return "", "", err + } + return block, encoding, nil +} + func nodeObject(node datamodel.Node) (manifestObject, error) { digest, err := nodeString(node, "digest") if err != nil { @@ -439,7 +572,18 @@ func nodeObject(node datamodel.Node) (manifestObject, error) { if err != nil { return manifestObject{}, err } - return manifestObject{Digest: digest, CID: contentCID, PackID: packID, Size: size}, nil + block, encoding, err := nodeBlockEncoding(node, contentCID) + if err != nil { + return manifestObject{}, err + } + return manifestObject{ + Digest: digest, + CID: contentCID, + Block: block, + Encoding: encoding, + PackID: packID, + Size: size, + }, nil } func nodeString(node datamodel.Node, key string) (string, error) { @@ -509,17 +653,49 @@ func validRawCID(value, digest string) bool { return err == nil && value == expected.String() } +// validateStoredBlock keeps the stored block and its encoding consistent: a +// verbatim block is addressed by the object's own CID, and an encoded one must +// name a different block. +func validateStoredBlock(contentCID, block, encoding string) error { + if !validBlockEncoding(encoding) { + return errors.New("manifest has unsupported block encoding") + } + if !validCID(block) { + return errors.New("manifest has invalid stored block CID") + } + if encoding == blockEncodingRaw && block != contentCID { + return errors.New("verbatim block must be addressed by the object CID") + } + if encoding != blockEncodingRaw && block == contentCID { + return errors.New("encoded block must not be addressed by the object CID") + } + return nil +} + func validCID(value string) bool { _, err := cid.Decode(value) return err == nil } +// carKeyPrefix is the namespace shared by pack and manifest keys, so a single +// catalog listing can enumerate both. +func carKeyPrefix(prefix string) string { + return prefix + "-car-" +} + func packKeyFor(prefix, id string) string { - return prefix + "-car-pack-v1-" + id + return carKeyPrefix(prefix) + "pack-v1-" + id +} + +func manifestKeyPrefix(prefix string) string { + return carKeyPrefix(prefix) + "manifest-v2-" } -func manifestKeyFor(prefix, id string) string { - return prefix + "-car-manifest-v1-" + id +// manifestKeyFor names a manifest after the pack it commits, so a reader can +// tell from a listing alone that a manifest has outlived its pack and is not +// worth downloading. +func manifestKeyFor(prefix, packID, manifestID string) string { + return manifestKeyPrefix(prefix) + packID + "-" + manifestID } func stringsHasSuffix(value, suffix string) bool { diff --git a/internal/server/manifest_test.go b/internal/server/manifest_test.go index 5a64449..a7447e3 100644 --- a/internal/server/manifest_test.go +++ b/internal/server/manifest_test.go @@ -16,12 +16,29 @@ func TestManifestDAGCBORRoundTripIsDeterministic(t *testing.T) { t.Fatal(err) } packID := digest([]byte("pack")) + compressedCID, err := rawCIDForData([]byte("compressed action bytes")) + if err != nil { + t.Fatal(err) + } value := manifest{ Version: manifestFormatVersion, Parents: []string{}, Packs: []packDescriptor{{ID: packID, Key: packKeyFor("test", packID), Size: 123}}, - CAS: []manifestObject{{Digest: casDigest, CID: casCID.String(), PackID: packID, Size: 3}}, - Actions: []manifestAction{{Digest: digest([]byte("action")), CID: actionCID.String(), PackID: packID, Size: 2, ClosurePacks: []string{packID}}}, + CAS: []manifestObject{{ + Digest: casDigest, + CID: casCID.String(), + Block: casCID.String(), + PackID: packID, + Size: 3, + }}, + Actions: []manifestAction{{ + Digest: digest([]byte("action")), + CID: actionCID.String(), + Block: compressedCID.String(), + Encoding: blockEncodingZstd, + PackID: packID, + Size: 2, + }}, } encoded, manifestCID, err := encodeManifest(value) if err != nil { @@ -40,6 +57,78 @@ func TestManifestDAGCBORRoundTripIsDeterministic(t *testing.T) { } } +func TestManifestFormatTwoOmitsRawBlockMetadataAndClosureValues(t *testing.T) { + packID := digest([]byte("pack")) + casData := []byte("raw cas") + casDigest := digest(casData) + casCID, err := rawCIDForDigest(casDigest) + if err != nil { + t.Fatal(err) + } + actionData := []byte{0x08, 0x01} + actionCID, err := rawCIDForData(actionData) + if err != nil { + t.Fatal(err) + } + value := manifest{ + Version: manifestFormatVersion, + Packs: []packDescriptor{{ID: packID, Key: packKeyFor("test", packID), Size: 128}}, + CAS: []manifestObject{{ + Digest: casDigest, CID: casCID.String(), Block: casCID.String(), + PackID: packID, Size: int64(len(casData)), + }}, + Actions: []manifestAction{{ + Digest: digest(actionData), CID: actionCID.String(), Block: actionCID.String(), + PackID: packID, Size: int64(len(actionData)), + }}, + } + node, err := manifestToNode(value) + if err != nil { + t.Fatal(err) + } + + casList, err := node.LookupByString("cas") + if err != nil { + t.Fatal(err) + } + _, casEntry, err := casList.ListIterator().Next() + if err != nil { + t.Fatal(err) + } + if _, err := casEntry.LookupByString("block"); err == nil { + t.Fatal("raw CAS entry contains redundant block field") + } + if _, err := casEntry.LookupByString("encoding"); err == nil { + t.Fatal("raw CAS entry contains redundant encoding field") + } + casBlock, casEncoding, err := nodeBlockEncoding(casEntry, casCID.String()) + if err != nil || casBlock != casCID.String() || casEncoding != blockEncodingRaw { + t.Fatalf("omitted raw CAS fields decode as %q/%q, err %v", casBlock, casEncoding, err) + } + + actionList, err := node.LookupByString("actions") + if err != nil { + t.Fatal(err) + } + _, actionEntry, err := actionList.ListIterator().Next() + if err != nil { + t.Fatal(err) + } + if _, err := actionEntry.LookupByString("block"); err == nil { + t.Fatal("raw action entry contains redundant block field") + } + if _, err := actionEntry.LookupByString("encoding"); err == nil { + t.Fatal("raw action entry contains redundant encoding field") + } + closure, err := nodeStringList(actionEntry, "closure") + if err != nil { + t.Fatal(err) + } + if len(closure) != 0 { + t.Fatalf("new action manifest carries unused closure IDs: %v", closure) + } +} + func TestManifestRejectsTamperedCID(t *testing.T) { value := manifest{Version: manifestFormatVersion} encoded, manifestCID, err := encodeManifest(value) @@ -51,3 +140,70 @@ func TestManifestRejectsTamperedCID(t *testing.T) { t.Fatal("tampered manifest was accepted") } } + +// A pack of many small objects yields a manifest past the DAG-CBOR decoder's +// default allocation budget; it must still round-trip. +func TestManifestWithManyEntriesDecodes(t *testing.T) { + packID := digest([]byte("pack")) + value := manifest{ + Version: manifestFormatVersion, + Parents: []string{}, + Packs: []packDescriptor{{ID: packID, Key: packKeyFor("test", packID), Size: 1}}, + } + for i := 0; i < 60000; i++ { + data := []byte{byte(i), byte(i >> 8), byte(i >> 16)} + casCID, err := rawCIDForData(data) + if err != nil { + t.Fatal(err) + } + value.CAS = append(value.CAS, manifestObject{ + Digest: digest(data), + CID: casCID.String(), + Block: casCID.String(), + PackID: packID, + Size: int64(len(data)), + }) + } + encoded, manifestCID, err := encodeManifest(value) + if err != nil { + t.Fatal(err) + } + decoded, err := decodeManifest(encoded, manifestCID) + if err != nil { + t.Fatalf("decode %d-byte manifest: %v", len(encoded), err) + } + if len(decoded.CAS) != len(value.CAS) { + t.Fatalf("decoded %d CAS entries, want %d", len(decoded.CAS), len(value.CAS)) + } +} + +// A pack's age is optional: manifests without it still decode, and one that +// records it survives a round trip unchanged. +func TestManifestCarriesAnOptionalPackAge(t *testing.T) { + packID := digest([]byte("pack")) + for _, since := range []int64{0, 1_790_000_000} { + value := manifest{ + Version: manifestFormatVersion, + Parents: []string{}, + Packs: []packDescriptor{{ID: packID, Key: packKeyFor("test", packID), Size: 1, Since: since}}, + } + encoded, manifestCID, err := encodeManifest(value) + if err != nil { + t.Fatal(err) + } + decoded, err := decodeManifest(encoded, manifestCID) + if err != nil { + t.Fatal(err) + } + if decoded.Packs[0].Since != since { + t.Fatalf("since = %d, want %d", decoded.Packs[0].Since, since) + } + reencoded, _, err := encodeManifest(decoded) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(encoded, reencoded) { + t.Fatal("a manifest with a pack age is not deterministic") + } + } +} diff --git a/internal/server/objects.go b/internal/server/objects.go new file mode 100644 index 0000000..09f67a7 --- /dev/null +++ b/internal/server/objects.go @@ -0,0 +1,382 @@ +package server + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "os" + "runtime" + "sync" + "sync/atomic" +) + +type lockedObjectReader struct { + *os.File + unlock func() + once sync.Once +} + +func (r *lockedObjectReader) Close() error { + err := r.File.Close() + r.once.Do(r.unlock) + return err +} + +type readSeekCloser struct { + *bytes.Reader +} + +func (readSeekCloser) Close() error { return nil } + +func (o object) open() (io.ReadSeekCloser, error) { + if o.inMemory { + return readSeekCloser{Reader: bytes.NewReader(o.data)}, nil + } + return os.Open(o.path) +} + +func (o object) readAll() ([]byte, error) { + if o.inMemory { + return bytes.Clone(o.data), nil + } + return os.ReadFile(o.path) +} + +// Transport-neutral outcomes of a cache operation. Cache policy — the fail-open +// decision, statistics, and redacted logging — is applied by the operations +// below so that every transport behaves identically; a transport only maps these +// onto its own status vocabulary. +var ( + errCacheMiss = errors.New("cache miss") + errBackendFailure = errors.New("cache backend unavailable") + errLocalFailure = errors.New("local cache unavailable") + errPayloadMismatch = errors.New("payload does not match the requested digest") + errPayloadTruncated = errors.New("payload size does not match the declared length") +) + +func (s *Server) objectKey(kind, digest string) string { + return s.cfg.KeyPrefix + "-" + kind + "-" + digest +} + +// recordMiss counts a miss against both the headline total and the bucket that +// explains it, so the breakdown can never drift from the total. +func (s *Server) recordMiss(bucket *atomic.Uint64) { + s.stats.misses.Add(1) + bucket.Add(1) +} + +// degrade reports a backend failure as a miss when the server is fail-open, so +// that a cache outage slows a build down instead of breaking it. +func (s *Server) degrade(failure error) error { + if s.cfg.FailOpen { + s.recordMiss(&s.stats.missesDegraded) + return errCacheMiss + } + return failure +} + +// readObject resolves an object and, for action results, validates that its CAS +// closure is still complete. +func (s *Server) readObject(ctx context.Context, kind, digest string) (object, error) { + s.objectFilesMu.RLock() + defer s.objectFilesMu.RUnlock() + return s.readObjectWithObjectFilesLock(ctx, kind, digest) +} + +func (s *Server) readObjectWithObjectFilesLock(ctx context.Context, kind, digest string) (object, error) { + s.stats.operations.Add(1) + obj, found, err := s.resolve(ctx, s.objectKey(kind, digest), kind, digest) + if err != nil { + s.stats.backendLoadErrors.Add(1) + s.cfg.Logger.Printf("backend load failed for %s/%s: %s", kind, digest, safeError(err)) + return object{}, s.degrade(errBackendFailure) + } + if !found { + if kind == "ac" { + s.recordMiss(&s.stats.missesAC) + } else { + s.recordMiss(&s.stats.missesCAS) + } + return object{}, errCacheMiss + } + if kind == "ac" { + if err := s.validateStoredActionResult(ctx, digest, obj); err != nil { + return object{}, err + } + } + return obj, nil +} + +// openObject resolves an object and opens it for serving. The caller closes the +// returned reader. A successful call counts a cache hit. +func (s *Server) openObject(ctx context.Context, kind, digest string) (io.ReadSeekCloser, int64, error) { + s.objectFilesMu.RLock() + unlock := true + defer func() { + if unlock { + s.objectFilesMu.RUnlock() + } + }() + obj, err := s.readObjectWithObjectFilesLock(ctx, kind, digest) + if err != nil { + return nil, 0, err + } + var reader io.ReadSeekCloser + if obj.inMemory { + reader, err = obj.open() + } else { + err = s.fileIO.do(ctx, func() (innerErr error) { + reader, innerErr = obj.open() + return innerErr + }) + } + if err != nil { + s.stats.backendLoadErrors.Add(1) + s.cfg.Logger.Printf("open local cache object %s/%s: %v", kind, digest, err) + if s.cfg.FailOpen { + s.recordMiss(&s.stats.missesDegraded) + return nil, 0, errCacheMiss + } + return nil, 0, errLocalFailure + } + if file, ok := reader.(*os.File); ok && runtime.GOOS == "windows" { + // Windows cannot unlink an open spool file. Keep the deletion lock + // until the transport closes its reader, not just until it opens it. + reader = &lockedObjectReader{File: file, unlock: s.objectFilesMu.RUnlock} + unlock = false + } + s.stats.hits.Add(1) + return reader, obj.size, nil +} + +// casPresence answers a presence probe from the manifest view without restoring +// the pack. Bazel issues these while building without needing the bytes. +func (s *Server) casPresence(ctx context.Context, digest string) (int64, error) { + s.stats.operations.Add(1) + size, found, err := s.presence(ctx, "cas", digest) + if err != nil { + s.cfg.Logger.Printf("presence check for cas/%s failed: %s", digest, safeError(err)) + } + if err != nil || !found { + s.recordMiss(&s.stats.missesPresence) + return 0, errCacheMiss + } + s.stats.hits.Add(1) + return size, nil +} + +// implicitEmptyCASHit records the zero-byte CAS digest, which every transport +// answers from the digest alone without consulting storage. +func (s *Server) implicitEmptyCASHit() { + s.stats.operations.Add(1) + s.stats.hits.Add(1) +} + +// readObjectBytes returns a whole object. Callers are responsible for bounding +// the size beforehand, so it suits action results, directories, and batched +// blobs rather than arbitrary CAS reads. +func (s *Server) readObjectBytes(ctx context.Context, kind, digest string) ([]byte, error) { + file, size, err := s.openObject(ctx, kind, digest) + if err != nil { + return nil, err + } + defer file.Close() + data := make([]byte, size) + if _, err := io.ReadFull(s.gateReader(ctx, file), data); err != nil { + s.cfg.Logger.Printf("read local cache object %s/%s: %v", kind, digest, err) + return nil, errLocalFailure + } + s.stats.bytesServed.Add(uint64(len(data))) + return data, nil +} + +func (s *Server) gateReader(ctx context.Context, reader io.Reader) io.Reader { + switch reader.(type) { + case *os.File, *lockedObjectReader: + return gatedReader{ctx: ctx, gate: s.fileIO, r: reader} + } + return reader +} + +func (s *Server) validateStoredActionResult(ctx context.Context, digest string, obj object) error { + err := s.validateActionResult(ctx, obj) + switch { + case err == nil: + s.stats.validatedActionResults.Add(1) + return nil + case errors.Is(err, errIncompleteActionResult): + s.stats.incompleteActionResults.Add(1) + s.recordMiss(&s.stats.missesRejected) + s.cfg.Logger.Printf("action result ac/%s is incomplete: %s", digest, safeError(err)) + return errCacheMiss + case errors.Is(err, errInvalidActionResult): + s.stats.invalidActionResults.Add(1) + s.recordMiss(&s.stats.missesRejected) + s.cfg.Logger.Printf("action result ac/%s is invalid: %s", digest, safeError(err)) + return errCacheMiss + default: + s.stats.backendLoadErrors.Add(1) + s.cfg.Logger.Printf("action result ac/%s validation failed: %s", digest, safeError(err)) + return s.degrade(errBackendFailure) + } +} + +// writeObject spools a payload, verifies it against the requested digest, and +// publishes it when writes are enabled. A nil error only means the caller's +// request was well formed: cache-side failures are absorbed by the fail-open +// policy and reported through the statistics instead. +func (s *Server) writeObject( + ctx context.Context, + kind, digest string, + body io.Reader, + size int64, +) error { + s.stats.operations.Add(1) + var file *os.File + err := s.fileIO.do(ctx, func() (err error) { + file, err = os.CreateTemp(s.cfg.CacheDir, "upload-*") + return err + }) + if err != nil { + s.cfg.Logger.Printf("create upload spool for %s/%s: %v", kind, digest, err) + return errLocalFailure + } + path := file.Name() + keep := false + defer func() { + _ = s.fileIO.do(context.Background(), func() error { + _ = file.Close() + if !keep { + _ = os.Remove(path) + } + return nil + }) + }() + + hasher := sha256.New() + writer := io.Writer(gatedWriter{ctx: ctx, gate: s.fileIO, w: file}) + if kind == "cas" { + writer = io.MultiWriter(writer, hasher) + } + n, err := io.Copy(writer, io.LimitReader(body, size+1)) + s.stats.bytesReceived.Add(uint64(n)) + if err != nil || n != size { + return errPayloadTruncated + } + if kind == "cas" && hex.EncodeToString(hasher.Sum(nil)) != digest { + return errPayloadMismatch + } + keep, err = s.storeObjectFile(ctx, kind, digest, file, path, n) + return err +} + +// storeObjectFile retains a verified spool locally and sends it through the +// normal publication path without copying or hashing it again. +func (s *Server) storeObjectFile( + ctx context.Context, + kind, digest string, + file *os.File, + path string, + size int64, +) (bool, error) { + keep := false + if runtime.GOOS == "windows" { + // Publication reads packed objects by path. Close the upload handle + // before staging can wake a worker that removes the original spool. + if err := s.fileIO.do(ctx, file.Close); err != nil { + s.cfg.Logger.Printf("close upload spool for %s/%s: %v", kind, digest, err) + return false, errLocalFailure + } + } + s.objectFilesMu.RLock() + key := s.objectKey(kind, digest) + s.objectsMu.Lock() + stored, exists := s.objects[key] + if !exists { + stored = object{path: path, size: size} + s.objects[key] = stored + keep = true + } + s.objectsMu.Unlock() + + if !s.cfg.WriteEnabled { + s.objectFilesMu.RUnlock() + s.stats.discardedUploads.Add(1) + return keep, nil + } + retained, err := s.stagePacked(ctx, kind, digest, stored) + s.objectFilesMu.RUnlock() + if !retained { + s.discardPackedObject(key, stored.path) + if stored.path == path { + keep = false + } + } + return keep, err +} + +// stagePacked hands an upload to the CARv2 pack writer, which publishes it as +// part of a later batch rather than as its own backend entry. +func (s *Server) stagePacked(ctx context.Context, kind, digest string, stored object) (bool, error) { + if kind == "cas" { + return s.packs.stageCAS(digest, stored), nil + } + closure, err := s.collectActionResultClosure(ctx, stored) + if err != nil { + return true, s.absorbActionResultFailure(digest, "staging", err) + } + if err := s.packs.stageAction(digest, stored, closure); err != nil { + return true, s.absorbSaveFailure(kind, digest, err) + } + s.stats.validatedActionResults.Add(1) + return true, nil +} + +func (s *Server) discardPackedObject(key, path string) { + s.objectFilesMu.Lock() + defer s.objectFilesMu.Unlock() + s.objectsMu.Lock() + if current, exists := s.objects[key]; exists && current.path == path { + delete(s.objects, key) + s.objectsMu.Unlock() + s.packs.removeLocalFile(path) + return + } + s.objectsMu.Unlock() +} + +// absorbActionResultFailure drops an action result that must not be published. +// The upload still succeeds from the client's point of view, because a build +// should not fail merely because its result was not cacheable. +func (s *Server) absorbActionResultFailure(digest, stage string, err error) error { + switch { + case errors.Is(err, errIncompleteActionResult): + s.stats.incompleteActionResults.Add(1) + s.stats.skippedActionResultUploads.Add(1) + s.cfg.Logger.Printf("not %s incomplete action result ac/%s: %s", stage, digest, safeError(err)) + case errors.Is(err, errInvalidActionResult): + s.stats.invalidActionResults.Add(1) + s.stats.skippedActionResultUploads.Add(1) + s.cfg.Logger.Printf("not %s invalid action result ac/%s: %s", stage, digest, safeError(err)) + default: + s.stats.backendLoadErrors.Add(1) + s.cfg.Logger.Printf("action result ac/%s failed validation while %s: %s", digest, stage, safeError(err)) + if !s.cfg.FailOpen { + return errBackendFailure + } + s.stats.skippedActionResultUploads.Add(1) + } + return nil +} + +func (s *Server) absorbSaveFailure(kind, digest string, err error) error { + s.stats.backendSaveErrors.Add(1) + s.cfg.Logger.Printf("backend save failed for %s/%s: %s", kind, digest, safeError(err)) + if s.cfg.FailOpen { + return nil + } + return errBackendFailure +} diff --git a/internal/server/pack_store.go b/internal/server/pack_store.go index f82c68a..ae0a9c7 100644 --- a/internal/server/pack_store.go +++ b/internal/server/pack_store.go @@ -19,22 +19,27 @@ import ( "github.com/ipld/go-car/v2/blockstore" ) -// packStore implements the CARv2/manifest-DAG storage mode. It keeps +// packStore implements CARv2/manifest-DAG storage. It keeps // uncommitted writes local, publishes a CARv2 pack first, and only then commits // the corresponding immutable DAG-CBOR manifest. A manifest therefore never // advertises data that a future runner cannot restore. type packStore struct { server *Server catalog cache.Catalog + codec *blockCodec keyPrefix string targetSize int64 flushInterval time.Duration + renewInterval time.Duration maxManifests int + // flushMu serialises flushes, so p.mu need not be held across uploads. + flushMu sync.Mutex mu sync.Mutex packs map[string]packDescriptor - cas map[string]manifestObject + declaredBytes map[string]int64 + cas map[string]casEntry actions map[string]manifestAction actionConflicts map[string]struct{} heads map[string]struct{} @@ -43,12 +48,19 @@ type packStore struct { pendingActions map[string]pendingAction pendingACOrder []string pendingBytes int64 - loadedPacks map[string]string + loadedPacks map[string]loadedPack loadingPacks map[string]*packLoad + listedPacks map[string]struct{} + packsListed bool + missingPacks map[string]struct{} + pendingRenewals map[string]struct{} + renewedPacks map[string]struct{} flushRequests chan struct{} + renewRequests chan struct{} stop chan struct{} closeOnce sync.Once + closeErr error workers sync.WaitGroup } @@ -58,37 +70,70 @@ type pendingAction struct { cid string } +type casEntry struct { + // Raw block IDs and content CIDs are reconstructed from the map's digest key. + block string + encoding string + packID string + size int64 +} + type packLoad struct { done chan struct{} - path string + pack loadedPack err error } +// loadedPack is a restored pack with one reader shared by every lookup. +// Reopening a pack indexes the whole archive, which made each packed read cost +// a full scan of its pack. +type loadedPack struct { + path string + store *blockstore.ReadOnly +} + +// errPackUnavailable marks a permanent answer about an immutable pack key: +// evicted, out of this job's cache scope, or corrupt. It is a cache miss rather +// than a backend outage, and it is never worth retrying within a job. +var errPackUnavailable = errors.New("pack is unavailable") + func newPackStore(server *Server) (*packStore, error) { if server.cfg.Catalog == nil { - return nil, errors.New("packed storage mode requires a manifest catalog") + return nil, errors.New("manifest catalog is required") + } + codec, err := newBlockCodec(server.cfg.PackCompression, server.cfg.PackCompressionLevel, server.cfg.MaxBlobSize) + if err != nil { + return nil, err } packs := &packStore{ server: server, catalog: server.cfg.Catalog, + codec: codec, keyPrefix: server.cfg.KeyPrefix, targetSize: server.cfg.PackSize, flushInterval: server.cfg.PackFlushInterval, + renewInterval: server.cfg.PackRenewInterval, maxManifests: server.cfg.MaxManifests, packs: make(map[string]packDescriptor), - cas: make(map[string]manifestObject), + declaredBytes: make(map[string]int64), + cas: make(map[string]casEntry), actions: make(map[string]manifestAction), actionConflicts: make(map[string]struct{}), heads: make(map[string]struct{}), pendingCAS: make(map[string]object), pendingActions: make(map[string]pendingAction), - loadedPacks: make(map[string]string), + loadedPacks: make(map[string]loadedPack), loadingPacks: make(map[string]*packLoad), + listedPacks: make(map[string]struct{}), + missingPacks: make(map[string]struct{}), + pendingRenewals: make(map[string]struct{}), + renewedPacks: make(map[string]struct{}), flushRequests: make(chan struct{}, 1), + renewRequests: make(chan struct{}, 1), stop: make(chan struct{}), } context, cancel := context.WithTimeout(context.Background(), server.cfg.BackendTimeout) - err := packs.discover(context) + err = packs.discover(context) cancel() if err != nil { server.stats.manifestDiscoveryErrors.Add(1) @@ -99,6 +144,8 @@ func newPackStore(server *Server) (*packStore, error) { } packs.workers.Add(1) go packs.flushWorker() + packs.workers.Add(1) + go packs.renewWorker() return packs, nil } @@ -123,24 +170,38 @@ func (p *packStore) flushWorker() { } func (p *packStore) close(ctx context.Context) error { - p.closeOnce.Do(func() { close(p.stop) }) - p.workers.Wait() - return p.flush(ctx, true) + p.closeOnce.Do(func() { + close(p.stop) + p.workers.Wait() + p.closeErr = p.flush(ctx, true) + p.renewPending(ctx) + p.codec.close() + p.server.objectFilesMu.Lock() + p.mu.Lock() + for _, pack := range p.loadedPacks { + _ = pack.store.Close() + p.removeLocalFile(pack.path) + } + p.mu.Unlock() + p.server.objectFilesMu.Unlock() + }) + return p.closeErr } -func (p *packStore) stageCAS(digest string, value object) { +func (p *packStore) stageCAS(digest string, value object) bool { p.mu.Lock() defer p.mu.Unlock() if _, exists := p.pendingCAS[digest]; exists { - return + return true } if _, exists := p.cas[digest]; exists { - return + return false } p.pendingCAS[digest] = value p.pendingCASOrder = append(p.pendingCASOrder, digest) p.pendingBytes += value.size p.requestFlushLocked() + return true } func (p *packStore) stageAction(digest string, value object, closure []digestReference) error { @@ -154,14 +215,7 @@ func (p *packStore) stageAction(digest string, value object, closure []digestRef } p.mu.Lock() defer p.mu.Unlock() - if existing, exists := p.pendingActions[digest]; exists { - if existing.cid != contentCID.String() { - // A single runner produced two different values for one action key. - // Do not publish either value; silently choosing one would make a - // non-deterministic action look cacheable. - delete(p.pendingActions, digest) - p.actionConflicts[digest] = struct{}{} - } + if _, exists := p.pendingActions[digest]; exists { return nil } p.pendingActions[digest] = pendingAction{ @@ -194,7 +248,7 @@ func (p *packStore) resolve(ctx context.Context, key, kind, digest string) (obje } p.mu.Lock() - var contentCID, packID string + var contentCID, blockCID, encoding, packID string var expectedSize int64 if kind == "cas" { entry, found := p.cas[digest] @@ -202,30 +256,52 @@ func (p *packStore) resolve(ctx context.Context, key, kind, digest string) (obje p.mu.Unlock() return object{}, false, nil } - contentCID, packID, expectedSize = entry.CID, entry.PackID, entry.Size - } else { - if _, conflict := p.actionConflicts[digest]; conflict { - p.server.stats.actionDigestConflicts.Add(1) + content, err := rawCIDForDigest(digest) + if err != nil { p.mu.Unlock() - return object{}, false, nil + return object{}, false, err } + contentCID = content.String() + blockCID, encoding = entry.block, entry.encoding + if blockCID == "" { + blockCID = contentCID + } + packID, expectedSize = entry.packID, entry.size + } else { entry, found := p.actions[digest] if !found { p.mu.Unlock() return object{}, false, nil } - contentCID, packID, expectedSize = entry.CID, entry.PackID, entry.Size + contentCID, blockCID, encoding = entry.CID, entry.Block, entry.Encoding + packID, expectedSize = entry.PackID, entry.Size } p.mu.Unlock() - path, err := p.loadPack(ctx, packID) + pack, err := p.loadPack(ctx, packID) + if err != nil { + if errors.Is(err, errPackUnavailable) { + return object{}, false, nil + } + return object{}, false, err + } + stored, err := blockFromStore(ctx, pack.store, blockCID) + if err != nil { + return object{}, false, err + } + data, err := p.codec.decode(stored, encoding, expectedSize) if err != nil { return object{}, false, err } - data, err := readCARBlock(ctx, path, contentCID, p.server.cfg.MaxBlobSize) + // The stored block was verified against its own CID; this proves the + // decoded bytes are the object the manifest promised. + decodedCID, err := rawCIDForData(data) if err != nil { return object{}, false, err } + if decodedCID.String() != contentCID { + return object{}, false, fmt.Errorf("packed %s/%s does not match its manifest CID", kind, digest) + } if int64(len(data)) != expectedSize { return object{}, false, fmt.Errorf("packed %s/%s has size %d; manifest declares %d", kind, digest, len(data), expectedSize) } @@ -235,103 +311,216 @@ func (p *packStore) resolve(ctx context.Context, key, kind, digest string) (obje return object{}, false, fmt.Errorf("packed CAS integrity check failed for %s", digest) } } - value, err = p.materialize(key, data) - if err != nil { - return object{}, false, err + return object{data: data, inMemory: true, size: int64(len(data))}, true, nil +} + +// presence answers a CAS presence check from the manifest view alone, without +// restoring the pack, and schedules a retention renewal for it. +// packFor names the pack an entry is served from, or nothing when the entry is +// not mapped by the merged manifest view. +func (p *packStore) packFor(kind, digest string) string { + p.mu.Lock() + defer p.mu.Unlock() + if kind == "cas" { + if entry, found := p.cas[digest]; found { + return entry.packID + } + return "" + } + if entry, found := p.actions[digest]; found { + return entry.PackID } - return value, true, nil + return "" } -func (p *packStore) exists(ctx context.Context, digest string) (bool, error) { - _, found, err := p.resolve(ctx, p.keyPrefix+"-cas-"+digest, "cas", digest) - return found, err +func (p *packStore) presence(digest string) (int64, bool) { + p.mu.Lock() + defer p.mu.Unlock() + entry, found := p.cas[digest] + if !found { + return 0, false + } + if !p.packRestorableLocked(entry.packID) { + return 0, false + } + p.scheduleRenewalLocked(entry.packID) + return entry.size, true } -func (p *packStore) materialize(key string, data []byte) (object, error) { - p.server.objectsMu.RLock() - existing, exists := p.server.objects[key] - p.server.objectsMu.RUnlock() - if exists { - return existing, nil +// packRestorableLocked reports whether a pack is still believed to be +// restorable, using only what discovery and earlier downloads already proved. +func (p *packStore) packRestorableLocked(packID string) bool { + if _, loaded := p.loadedPacks[packID]; loaded { + return true } - file, err := os.CreateTemp(p.server.cfg.CacheDir, "packed-object-*") - if err != nil { - return object{}, err + if _, missing := p.missingPacks[packID]; missing { + return false } - path := file.Name() - if err := file.Chmod(0o600); err != nil { - _ = file.Close() - return object{}, err + if _, known := p.packs[packID]; !known { + return false } - _, err = file.Write(data) - if err == nil { - err = file.Sync() + if _, listed := p.listedPacks[packID]; p.packsListed && !listed { + return false } - if closeErr := file.Close(); err == nil { - err = closeErr + return true +} + +// scheduleRenewalLocked queues one renewal per pack per job. Reading an entry +// is what resets its GitHub retention, so a pack that only ever answers +// presence checks would otherwise be evicted while Bazel still depends on it. +func (p *packStore) scheduleRenewalLocked(packID string) { + if _, renewed := p.renewedPacks[packID]; renewed { + return } - if err != nil { - return object{}, err + if _, loaded := p.loadedPacks[packID]; loaded { + return } - value := object{path: path, size: int64(len(data))} - p.server.objectsMu.Lock() - if existing, exists := p.server.objects[key]; exists { - p.server.objectsMu.Unlock() - return existing, nil + if _, pending := p.pendingRenewals[packID]; pending { + return + } + p.pendingRenewals[packID] = struct{}{} + select { + case p.renewRequests <- struct{}{}: + default: } - p.server.objects[key] = value - p.server.objectsMu.Unlock() - return value, nil } -func (p *packStore) loadPack(ctx context.Context, packID string) (string, error) { +func (p *packStore) renewWorker() { + defer p.workers.Done() + for { + select { + case <-p.stop: + return + case <-p.renewRequests: + } + // Hold the batch briefly: a pack Bazel downloads within the window is + // renewed by that download, which saves the API call entirely. + timer := time.NewTimer(p.renewInterval) + select { + case <-p.stop: + timer.Stop() + return + case <-timer.C: + } + context, cancel := context.WithTimeout(context.Background(), p.server.cfg.BackendTimeout) + p.renewPending(context) + cancel() + } +} + +// renewPending touches each queued pack once. The touch resolves cache +// metadata without transferring the pack, and doubles as a liveness probe. +func (p *packStore) renewPending(ctx context.Context) { p.mu.Lock() - if path, exists := p.loadedPacks[packID]; exists { + renewals := make([]packDescriptor, 0, len(p.pendingRenewals)) + for packID := range p.pendingRenewals { + delete(p.pendingRenewals, packID) + if _, renewed := p.renewedPacks[packID]; renewed { + continue + } + descriptor, known := p.packs[packID] + if !known { + continue + } + // Marked before the call so a failing pack is not retried all job. + p.renewedPacks[packID] = struct{}{} + renewals = append(renewals, descriptor) + } + p.mu.Unlock() + + for _, descriptor := range renewals { + found, err := p.server.backendExists(ctx, descriptor.Key) + if err != nil { + p.server.cfg.Logger.Printf("renewing pack %s failed: %s", descriptor.ID, safeError(err)) + continue + } + if !found { + p.mu.Lock() + p.missingPacks[descriptor.ID] = struct{}{} + p.mu.Unlock() + p.server.cfg.Logger.Printf("pack %s vanished before renewal; its entries are cache misses", descriptor.ID) + continue + } + p.server.stats.packRenewals.Add(1) + } +} + +func (p *packStore) loadPack(ctx context.Context, packID string) (loadedPack, error) { + p.mu.Lock() + if pack, exists := p.loadedPacks[packID]; exists { p.mu.Unlock() - return path, nil + return pack, nil } if loading, exists := p.loadingPacks[packID]; exists { done := loading.done p.mu.Unlock() select { case <-ctx.Done(): - return "", ctx.Err() + return loadedPack{}, ctx.Err() case <-done: - return loading.path, loading.err + return loading.pack, loading.err } } descriptor, exists := p.packs[packID] if !exists { p.mu.Unlock() - return "", fmt.Errorf("manifest references unavailable pack %s", packID) + return loadedPack{}, fmt.Errorf("manifest references unknown pack %s: %w", packID, errPackUnavailable) + } + if _, unavailable := p.missingPacks[packID]; unavailable { + p.mu.Unlock() + p.server.stats.packLoadsSkipped.Add(1) + return loadedPack{}, fmt.Errorf("pack %s is not restorable in this job: %w", packID, errPackUnavailable) + } + // The catalog lists every ref, so a pack absent from it is definitely gone. + // A listed pack may still be out of this job's cache scope, which only a + // failed download can reveal. + if _, listed := p.listedPacks[packID]; p.packsListed && !listed { + p.missingPacks[packID] = struct{}{} + p.mu.Unlock() + p.server.stats.packLoadsSkipped.Add(1) + p.server.cfg.Logger.Printf("pack %s is absent from the cache listing; its entries are cache misses", packID) + return loadedPack{}, fmt.Errorf("pack %s is not restorable in this job: %w", packID, errPackUnavailable) } loading := &packLoad{done: make(chan struct{})} p.loadingPacks[packID] = loading p.mu.Unlock() - path, err := p.downloadPack(ctx, descriptor) + pack, err := p.downloadPack(ctx, descriptor) p.mu.Lock() if err == nil { - p.loadedPacks[packID] = path - loading.path = path + p.loadedPacks[packID] = pack + loading.pack = pack + // The download already reset this entry's retention. + p.renewedPacks[packID] = struct{}{} + delete(p.pendingRenewals, packID) + } + if errors.Is(err, errPackUnavailable) { + p.missingPacks[packID] = struct{}{} + p.server.cfg.Logger.Printf("pack %s cannot be restored; its entries are cache misses: %s", packID, safeError(err)) } loading.err = err delete(p.loadingPacks, packID) close(loading.done) p.mu.Unlock() - return path, err + return pack, err } -func (p *packStore) downloadPack(ctx context.Context, descriptor packDescriptor) (string, error) { +func (p *packStore) downloadPack(ctx context.Context, descriptor packDescriptor) (loadedPack, error) { if err := p.server.acquire(ctx); err != nil { - return "", err + return loadedPack{}, err } defer p.server.release() file, err := os.CreateTemp(p.server.cfg.CacheDir, "pack-download-*") if err != nil { - return "", err + return loadedPack{}, err } path := file.Name() + keep := false + defer func() { + if !keep { + p.removeLocalFile(path) + } + }() limited := &maxWriter{writer: file, remaining: p.server.cfg.MaxBlobSize} backendCtx, cancel := context.WithTimeout(ctx, p.server.cfg.BackendTimeout) found, err := p.server.cfg.Backend.Load(backendCtx, descriptor.Key, limited) @@ -340,71 +529,112 @@ func (p *packStore) downloadPack(ctx context.Context, descriptor packDescriptor) err = closeErr } if err != nil { - return "", err + return loadedPack{}, err } if !found { - return "", fmt.Errorf("pack %s is missing", descriptor.ID) + return loadedPack{}, fmt.Errorf("pack %s is missing: %w", descriptor.ID, errPackUnavailable) } p.server.stats.backendDownloads.Add(1) p.server.stats.packDownloads.Add(1) + p.server.usage.packRestored(descriptor.ID, descriptor.Size, p.declaredBytesFor(descriptor.ID)) info, err := os.Stat(path) if err != nil { - return "", err + return loadedPack{}, err } if info.Size() != descriptor.Size { - return "", fmt.Errorf("pack %s has size %d; manifest declares %d", descriptor.ID, info.Size(), descriptor.Size) + return loadedPack{}, fmt.Errorf("pack %s has size %d; manifest declares %d: %w", descriptor.ID, info.Size(), descriptor.Size, errPackUnavailable) } verify, err := os.Open(path) if err != nil { - return "", err + return loadedPack{}, err } actual, hashErr := hashFile(verify) closeErr := verify.Close() if hashErr != nil { - return "", hashErr + return loadedPack{}, hashErr } if closeErr != nil { - return "", closeErr + return loadedPack{}, closeErr } if actual != descriptor.ID { - return "", fmt.Errorf("pack integrity check failed: expected %s, got %s", descriptor.ID, actual) + return loadedPack{}, fmt.Errorf("pack integrity check failed: expected %s, got %s: %w", descriptor.ID, actual, errPackUnavailable) } - return path, nil + // The bytes match the pack's content ID, so an archive that cannot be + // opened will never open and its entries are permanent misses. + store, err := openPackReader(path, p.server.cfg.MaxBlobSize) + if err != nil { + return loadedPack{}, fmt.Errorf("pack %s cannot be read: %w: %w", descriptor.ID, err, errPackUnavailable) + } + keep = true + return loadedPack{path: path, store: store}, nil } func (p *packStore) flush(ctx context.Context, all bool) error { - p.mu.Lock() - defer p.mu.Unlock() + p.flushMu.Lock() + defer p.flushMu.Unlock() for { - flushed, err := p.flushOneLocked(ctx) + flushed, err := p.flushOne(ctx) if err != nil || !flushed || !all { return err } } } -func (p *packStore) flushOneLocked(ctx context.Context) (bool, error) { +// flushOne holds p.mu only between backend calls. Holding it across an upload +// stalls every read, and deadlocks with a pack download that holds a backend +// slot while it waits for p.mu. +func (p *packStore) flushOne(ctx context.Context) (bool, error) { + p.mu.Lock() casDigests := p.selectCASLocked() selectedCAS := make(map[string]struct{}, len(casDigests)) for _, digest := range casDigests { selectedCAS[digest] = struct{}{} } actionDigests := p.selectActionsLocked(selectedCAS) + casValues := make([]object, len(casDigests)) + for i, digest := range casDigests { + casValues[i] = p.pendingCAS[digest] + } + actionValues := make([]pendingAction, len(actionDigests)) + for i, digest := range actionDigests { + actionValues[i] = p.pendingActions[digest] + } + p.mu.Unlock() if len(casDigests) == 0 && len(actionDigests) == 0 { return false, nil } - packPath, entries, packSize, packID, err := p.buildPackLocked(ctx, casDigests, actionDigests) + packPath, entries, packSize, packID, err := p.buildPack(ctx, casDigests, casValues, actionDigests, actionValues) if err != nil { return false, err } + packRetained := false + defer func() { + if !packRetained { + p.removeLocalFile(packPath) + } + }() + packReader, err := openPackReader(packPath, p.server.cfg.MaxBlobSize) + if err != nil { + return false, fmt.Errorf("open newly built CARv2 pack: %w", err) + } + readerRetained := false + defer func() { + if !readerRetained { + _ = packReader.Close() + } + }() pack := packDescriptor{ID: packID, Key: packKeyFor(p.keyPrefix, packID), Size: packSize} if err := p.publishFile(ctx, pack.Key, packPath, packSize); err != nil { + p.server.stats.backendSaveErrors.Add(1) return false, fmt.Errorf("publish CARv2 pack: %w", err) } p.server.stats.packUploads.Add(1) - manifestValue := p.manifestForPackLocked(pack, entries, selectedCAS) + p.mu.Lock() + p.listedPacks[pack.ID] = struct{}{} + manifestValue := p.manifestForPackLocked(pack, entries) + p.mu.Unlock() manifestData, manifestID, err := encodeManifest(manifestValue) if err != nil { return false, err @@ -413,12 +643,20 @@ func (p *packStore) flushOneLocked(ctx context.Context) (bool, error) { if err != nil { return false, err } - if err := p.publishFile(ctx, manifestKeyFor(p.keyPrefix, manifestID), manifestPath, int64(len(manifestData))); err != nil { + defer p.removeLocalFile(manifestPath) + if err := p.publishFile(ctx, manifestKeyFor(p.keyPrefix, pack.ID, manifestID), manifestPath, int64(len(manifestData))); err != nil { + p.server.stats.backendSaveErrors.Add(1) return false, fmt.Errorf("publish manifest commit point: %w", err) } p.server.stats.manifestUploads.Add(1) + p.mu.Lock() p.applyManifestLocked(manifestID, manifestValue) + p.loadedPacks[pack.ID] = loadedPack{path: packPath, store: packReader} p.removePendingLocked(casDigests, actionDigests) + p.mu.Unlock() + readerRetained = true + packRetained = true + p.discardPackedObjects(casDigests, casValues, actionDigests, actionValues) return true, nil } @@ -427,15 +665,37 @@ type packedEntries struct { actions []manifestAction } -func (p *packStore) buildPackLocked(ctx context.Context, casDigests, actionDigests []string) (string, packedEntries, int64, string, error) { +// encodeBlock compresses one block and returns the bytes to store, the +// encoding to record, and the CID addressing those bytes. +func (p *packStore) encodeBlock(data []byte, contentCID cid.Cid) ([]byte, string, cid.Cid, error) { + stored, encoding := p.codec.encode(data) + if encoding == blockEncodingRaw { + return data, blockEncodingRaw, contentCID, nil + } + blockCID, err := rawCIDForData(stored) + if err != nil { + return nil, "", cid.Undef, err + } + p.server.stats.compressedBlocks.Add(1) + p.server.stats.compressionSavedBytes.Add(uint64(len(data) - len(stored))) + return stored, encoding, blockCID, nil +} + +func (p *packStore) buildPack( + ctx context.Context, + casDigests []string, + casValues []object, + actionDigests []string, + actionValues []pendingAction, +) (string, packedEntries, int64, string, error) { type blockEntry struct { cid cid.Cid data []byte } blocksToWrite := make([]blockEntry, 0, len(casDigests)+len(actionDigests)) entries := packedEntries{} - for _, digest := range casDigests { - value := p.pendingCAS[digest] + for i, digest := range casDigests { + value := casValues[i] data, err := os.ReadFile(value.path) if err != nil { return "", packedEntries{}, 0, "", err @@ -444,11 +704,21 @@ func (p *packStore) buildPackLocked(ctx context.Context, casDigests, actionDiges if err != nil { return "", packedEntries{}, 0, "", err } - blocksToWrite = append(blocksToWrite, blockEntry{cid: contentCID, data: data}) - entries.cas = append(entries.cas, manifestObject{Digest: digest, CID: contentCID.String(), Size: value.size}) - } - for _, digest := range actionDigests { - value := p.pendingActions[digest] + stored, encoding, blockCID, err := p.encodeBlock(data, contentCID) + if err != nil { + return "", packedEntries{}, 0, "", err + } + blocksToWrite = append(blocksToWrite, blockEntry{cid: blockCID, data: stored}) + entries.cas = append(entries.cas, manifestObject{ + Digest: digest, + CID: contentCID.String(), + Block: blockCID.String(), + Encoding: encoding, + Size: value.size, + }) + } + for i, digest := range actionDigests { + value := actionValues[i] data, err := os.ReadFile(value.object.path) if err != nil { return "", packedEntries{}, 0, "", err @@ -457,8 +727,18 @@ func (p *packStore) buildPackLocked(ctx context.Context, casDigests, actionDiges if err != nil { return "", packedEntries{}, 0, "", err } - blocksToWrite = append(blocksToWrite, blockEntry{cid: contentCID, data: data}) - entries.actions = append(entries.actions, manifestAction{Digest: digest, CID: value.cid, Size: value.object.size}) + stored, encoding, blockCID, err := p.encodeBlock(data, contentCID) + if err != nil { + return "", packedEntries{}, 0, "", err + } + blocksToWrite = append(blocksToWrite, blockEntry{cid: blockCID, data: stored}) + entries.actions = append(entries.actions, manifestAction{ + Digest: digest, + CID: value.cid, + Block: blockCID.String(), + Encoding: encoding, + Size: value.object.size, + }) } if len(blocksToWrite) == 0 { return "", packedEntries{}, 0, "", errors.New("cannot build an empty CARv2 pack") @@ -467,7 +747,13 @@ func (p *packStore) buildPackLocked(ctx context.Context, casDigests, actionDiges if err != nil { return "", packedEntries{}, 0, "", err } - store, err := blockstore.OpenReadWrite(path, []cid.Cid{blocksToWrite[0].cid}, blockstore.UseWholeCIDs(true)) + keep := false + defer func() { + if !keep { + p.removeLocalFile(path) + } + }() + store, err := openPackWriter(path, blocksToWrite[0].cid) if err != nil { return "", packedEntries{}, 0, "", err } @@ -501,34 +787,19 @@ func (p *packStore) buildPackLocked(ctx context.Context, casDigests, actionDiges if closeErr != nil { return "", packedEntries{}, 0, "", closeErr } + keep = true return path, entries, info.Size(), packID, nil } func (p *packStore) manifestForPackLocked( pack packDescriptor, entries packedEntries, - selectedCAS map[string]struct{}, ) manifest { for index := range entries.cas { entries.cas[index].PackID = pack.ID } for index := range entries.actions { entries.actions[index].PackID = pack.ID - closure := make(map[string]struct{}) - pending := p.pendingActions[entries.actions[index].Digest] - for _, reference := range pending.closure { - if isImplicitEmptyDigest(reference) { - continue - } - if _, selected := selectedCAS[reference.hash]; selected { - closure[pack.ID] = struct{}{} - continue - } - if previous, found := p.cas[reference.hash]; found { - closure[previous.PackID] = struct{}{} - } - } - entries.actions[index].ClosurePacks = sortedStringsFromSet(closure) } return manifest{ Version: manifestFormatVersion, @@ -621,6 +892,45 @@ func (p *packStore) removePendingLocked(casDigests, actionDigests []string) { p.pendingACOrder = filterPending(p.pendingACOrder, p.pendingActions) } +func (p *packStore) discardPackedObjects( + casDigests []string, + casValues []object, + actionDigests []string, + actionValues []pendingAction, +) { + paths := make(map[string]struct{}, len(casValues)+len(actionValues)) + p.server.objectFilesMu.Lock() + defer p.server.objectFilesMu.Unlock() + p.server.objectsMu.Lock() + for i, digest := range casDigests { + key := p.server.objectKey("cas", digest) + if current, exists := p.server.objects[key]; exists && current.path == casValues[i].path { + delete(p.server.objects, key) + paths[current.path] = struct{}{} + } + } + for i, digest := range actionDigests { + key := p.server.objectKey("ac", digest) + if current, exists := p.server.objects[key]; exists && current.path == actionValues[i].object.path { + delete(p.server.objects, key) + paths[current.path] = struct{}{} + } + } + p.server.objectsMu.Unlock() + for path := range paths { + p.removeLocalFile(path) + } +} + +func (p *packStore) removeLocalFile(path string) { + err := p.server.fileIO.do(context.Background(), func() error { + return os.Remove(path) + }) + if err != nil && !errors.Is(err, os.ErrNotExist) { + p.server.cfg.Logger.Printf("remove local packed-cache file: %v", err) + } +} + func filterPending[T any](order []string, values map[string]T) []string { filtered := order[:0] for _, key := range order { @@ -631,29 +941,112 @@ func filterPending[T any](order []string, values map[string]T) []string { return filtered } +// manifestReference is a listed manifest that is still worth downloading. +type manifestReference struct { + key string + packID string + id string +} + func (p *packStore) discover(ctx context.Context) error { - keys, err := p.catalog.List(ctx, manifestKeyFor(p.keyPrefix, ""), p.maxManifests) + started := time.Now() + // Listing reads metadata only: unlike a download it does not extend an + // entry's lifetime, so both listings are unbounded and max-manifests is + // spent on downloads instead. Manifests are listed first, so the pack + // listing below cannot miss a pack that a concurrent writer published + // before its manifest. + manifestKeys, err := p.catalog.List(ctx, manifestKeyPrefix(p.keyPrefix)) + if err != nil { + return err + } + p.server.stats.manifestsDiscovered.Add(uint64(len(manifestKeys))) + // A truncated pack listing would look like eviction and suppress valid + // downloads, so this one must be complete. + packKeys, err := p.catalog.List(ctx, packKeyFor(p.keyPrefix, "")) if err != nil { return err } - p.server.stats.manifestsDiscovered.Add(uint64(len(keys))) - manifests := make(map[string]manifest, len(keys)) - parents := make(map[string]struct{}) - for _, key := range keys { - manifestID, ok := parseManifestKey(p.keyPrefix, key) + for _, key := range packKeys { + if id, ok := parsePackKey(p.keyPrefix, key); ok { + p.listedPacks[id] = struct{}{} + } + } + listed := time.Since(started) + p.packsListed = true + p.server.stats.packsDiscovered.Add(uint64(len(p.listedPacks))) + + live := make([]manifestReference, 0, len(manifestKeys)) + orphaned := 0 + for _, key := range manifestKeys { + packID, manifestID, ok := parseManifestKey(p.keyPrefix, key) if !ok { continue } - value, err := p.loadManifest(ctx, key, manifestID) - if err != nil { - p.server.stats.manifestLoadErrors.Add(1) - p.server.cfg.Logger.Printf("ignoring unavailable manifest %s: %s", manifestID, safeError(err)) + // Every mapping a manifest introduces lives in the pack named by its + // key, so an orphaned manifest has nothing left to offer. Leaving it + // unread is what lets it expire instead of being renewed forever. + if _, listed := p.listedPacks[packID]; !listed { + orphaned++ continue } - manifests[manifestID] = value - for _, parent := range value.Parents { - parents[parent] = struct{}{} + live = append(live, manifestReference{key: key, packID: packID, id: manifestID}) + } + if orphaned > 0 { + p.server.stats.manifestsOrphaned.Add(uint64(orphaned)) + p.server.cfg.Logger.Printf("skipped %d manifests whose packs are gone; unread manifests expire on their own", orphaned) + } + // Applying the limit after the orphan filter keeps the budget on manifests + // that can still contribute cache hits. + if len(live) > p.maxManifests { + skipped := len(live) - p.maxManifests + p.server.stats.manifestsSkipped.Add(uint64(skipped)) + p.server.cfg.Logger.Printf( + "%d live manifests exceed the max-manifests limit of %d; the %d oldest are treated as cache misses", + len(live), p.maxManifests, skipped) + live = live[:p.maxManifests] + } + + // Each manifest costs a backend round trip, and nothing is served until they + // are all in, so loading them one at a time makes startup scale with the + // size of the cache. + loaded := make([]*manifest, len(live)) + reads := make(chan struct{}, manifestReadConcurrency(p.server.cfg.MaxConcurrent)) + var loading sync.WaitGroup + for i := range live { + loading.Add(1) + go func(i int) { + defer loading.Done() + select { + case reads <- struct{}{}: + defer func() { <-reads }() + case <-ctx.Done(): + p.server.stats.manifestLoadErrors.Add(1) + return + } + value, err := p.loadManifest(ctx, live[i].key, live[i].id) + if err != nil { + p.server.stats.manifestLoadErrors.Add(1) + p.server.cfg.Logger.Printf("ignoring unavailable manifest %s: %s", live[i].id, safeError(err)) + return + } + loaded[i] = &value + }(i) + } + loading.Wait() + loadedIn := time.Since(started) - listed + + manifests := make(map[string]manifest, len(live)) + for i, reference := range live { + value := loaded[i] + if value == nil { + continue } + if len(value.Packs) != 1 || value.Packs[0].ID != reference.packID { + p.server.stats.manifestLoadErrors.Add(1) + p.server.cfg.Logger.Printf("ignoring manifest %s: it does not commit the pack %s named by its key", reference.id, reference.packID) + continue + } + manifests[reference.id] = *value } ids := make([]string, 0, len(manifests)) for id := range manifests { @@ -662,18 +1055,35 @@ func (p *packStore) discover(ctx context.Context) error { sort.Strings(ids) for _, id := range ids { p.applyManifestLocked(id, manifests[id]) - if _, parent := parents[id]; !parent { - p.heads[id] = struct{}{} - } + } + p.heads = manifestHeads(manifests) + // Nothing is served until this returns, so a slow backend shows up as the + // server taking a long time to start for no visible reason. + p.server.cfg.Logger.Printf( + "discovered %d packs and read %d of %d manifests in %s (listing %s, reading %s)", + len(p.listedPacks), len(manifests), len(live), + time.Since(started).Round(time.Millisecond), + listed.Round(time.Millisecond), loadedIn.Round(time.Millisecond)) + if conflicts := len(p.actionConflicts); conflicts > 0 { + p.server.cfg.Logger.Printf( + "warning: %d action keys have more than one stored result; serving the copy in the lowest pack ID. Overlapping writers or non-hermetic actions cause this", + conflicts) } return nil } +// manifestReadConcurrency bounds the startup manifest reads. They are small +// metadata fetches issued before the server accepts traffic, so they are not +// held to the blob-transfer limit; a larger --max-concurrent still raises it. +func manifestReadConcurrency(maxConcurrent int) int { + const atStartup = 16 + if maxConcurrent > atStartup { + return maxConcurrent + } + return atStartup +} + func (p *packStore) loadManifest(ctx context.Context, key, id string) (manifest, error) { - if err := p.server.acquire(ctx); err != nil { - return manifest{}, err - } - defer p.server.release() var data bytesBuffer backendCtx, cancel := context.WithTimeout(ctx, p.server.cfg.BackendTimeout) found, err := p.server.cfg.Backend.Load(backendCtx, key, &data) @@ -692,24 +1102,46 @@ func (p *packStore) loadManifest(ctx context.Context, key, id string) (manifest, } func (p *packStore) applyManifestLocked(id string, value manifest) { + var declared int64 for _, descriptor := range value.Packs { - if existing, found := p.packs[descriptor.ID]; !found || descriptor.Key < existing.Key { + if existing, found := p.packs[descriptor.ID]; !found || preferPack(descriptor, existing) { p.packs[descriptor.ID] = descriptor } } for _, object := range value.CAS { - if existing, found := p.cas[object.Digest]; !found || object.PackID < existing.PackID { - p.cas[object.Digest] = object + declared += object.Size + existing, found := p.cas[object.Digest] + if !found || object.PackID < existing.packID { + block := object.Block + if object.Encoding == blockEncodingRaw { + block = "" + } + p.cas[object.Digest] = casEntry{ + block: block, encoding: object.Encoding, + packID: p.packs[object.PackID].ID, size: object.Size, + } } } for _, action := range value.Actions { - if existing, found := p.actions[action.Digest]; found { - if existing.CID != action.CID { + declared += action.Size + action.PackID = p.packs[action.PackID].ID + existing, found := p.actions[action.Digest] + if found && existing.CID != action.CID { + if _, counted := p.actionConflicts[action.Digest]; !counted { p.actionConflicts[action.Digest] = struct{}{} + p.server.stats.actionDigestConflicts.Add(1) } - continue } - p.actions[action.Digest] = action + if !found || preferAction(action, existing) { + p.actions[action.Digest] = action + } + } + // Two manifests naming one pack describe identical content, so the first + // wins rather than the total being counted twice. + if len(value.Packs) == 1 { + if _, known := p.declaredBytes[value.Packs[0].ID]; !known { + p.declaredBytes[value.Packs[0].ID] = declared + } } for _, parent := range value.Parents { delete(p.heads, parent) @@ -717,18 +1149,72 @@ func (p *packStore) applyManifestLocked(id string, value manifest) { p.heads[id] = struct{}{} } -func parseManifestKey(prefix, key string) (string, bool) { - head := manifestKeyFor(prefix, "") +// declaredBytesFor is the uncompressed content a pack holds. Its stored size is +// compressed, so only this is comparable with the object sizes a job used. +func (p *packStore) declaredBytesFor(packID string) int64 { + p.mu.Lock() + defer p.mu.Unlock() + return p.declaredBytes[packID] +} + +// preferPack and preferObject are the merge tie-breaks. Anything that reasons +// about the stored layout has to resolve a digest to the same copy a reader +// would be served, so the rules live in exactly one place. +func preferPack(candidate, existing packDescriptor) bool { + return candidate.Key < existing.Key +} + +func preferObject(candidate, existing manifestObject) bool { + return candidate.PackID < existing.PackID +} + +// preferAction picks one of several stored results for an action key. Any of +// them is a valid REAPI answer; refusing all of them would make the key a +// permanent miss, since every re-execution uploads yet another distinct result. +func preferAction(candidate, existing manifestAction) bool { + if candidate.PackID != existing.PackID { + return candidate.PackID < existing.PackID + } + return candidate.CID < existing.CID +} + +func parseManifestKey(prefix, key string) (string, string, bool) { + head := manifestKeyPrefix(prefix) + if len(key) <= len(head) || key[:len(head)] != head { + return "", "", false + } + rest := key[len(head):] + const packIDLength = 64 + if len(rest) <= packIDLength+1 || rest[packIDLength] != '-' { + return "", "", false + } + packID, manifestID := rest[:packIDLength], rest[packIDLength+1:] + if !digestPattern.MatchString(packID) || !validCID(manifestID) { + return "", "", false + } + return packID, manifestID, true +} + +func parsePackKey(prefix, key string) (string, bool) { + head := packKeyFor(prefix, "") if len(key) <= len(head) || key[:len(head)] != head { return "", false } id := key[len(head):] - return id, validCID(id) + return id, digestPattern.MatchString(id) } const rawCIDSectionOverheadBytes = 64 -func readCARBlock(ctx context.Context, path, contentCID string, maxBlobSize int64) ([]byte, error) { +// openPackWriter starts a CARv2 pack. Every writer uses the same options, so a +// pack a later pass rebuilds is framed exactly like the one it replaces. +func openPackWriter(path string, root cid.Cid) (*blockstore.ReadWrite, error) { + return blockstore.OpenReadWrite(path, []cid.Cid{root}, blockstore.UseWholeCIDs(true)) +} + +// openPackReader opens a pack for reading. Callers that move many blocks hold +// one open rather than reopening and re-indexing the archive per block. +func openPackReader(path string, maxBlobSize int64) (*blockstore.ReadOnly, error) { // CAR sections include the block CID as well as the payload. Packs use // CIDv1/raw/SHA-256 CIDs, so a small fixed allowance above the configured // payload limit safely admits every block this cache is allowed to store. @@ -740,7 +1226,10 @@ func readCARBlock(ctx context.Context, path, contentCID string, maxBlobSize int6 if err != nil { return nil, fmt.Errorf("open CARv2 pack: %w", err) } - defer store.Close() + return store, nil +} + +func blockFromStore(ctx context.Context, store *blockstore.ReadOnly, contentCID string) ([]byte, error) { content, err := cid.Decode(contentCID) if err != nil { return nil, err @@ -763,16 +1252,9 @@ func writePrivateTemp(directory, pattern string, data []byte) (string, error) { return "", err } path := file.Name() - if err := file.Chmod(0o600); err != nil { - _ = file.Close() - return "", err - } if len(data) > 0 { _, err = file.Write(data) } - if err == nil { - err = file.Sync() - } if closeErr := file.Close(); err == nil { err = closeErr } diff --git a/internal/server/pack_store_test.go b/internal/server/pack_store_test.go index c84fab2..a12fa1b 100644 --- a/internal/server/pack_store_test.go +++ b/internal/server/pack_store_test.go @@ -3,8 +3,12 @@ package server import ( "bytes" "context" + "errors" "net/http" + "net/http/httptest" + "os" "sort" + "strconv" "strings" "testing" "time" @@ -16,7 +20,7 @@ type memoryCatalog struct { backend *memoryBackend } -func (c memoryCatalog) List(_ context.Context, prefix string, limit int) ([]string, error) { +func (c memoryCatalog) List(_ context.Context, prefix string) ([]string, error) { c.backend.mu.Lock() defer c.backend.mu.Unlock() keys := make([]string, 0) @@ -26,14 +30,31 @@ func (c memoryCatalog) List(_ context.Context, prefix string, limit int) ([]stri } } sort.Strings(keys) - if len(keys) > limit { - return nil, context.DeadlineExceeded - } return keys, nil } var _ cache.Catalog = memoryCatalog{} +// phantomCatalog reports keys the backend cannot serve, as GitHub's REST +// listing does for packs outside the running job's cache scope. +type phantomCatalog struct { + memoryCatalog + phantom []string +} + +func (c phantomCatalog) List(ctx context.Context, prefix string) ([]string, error) { + keys, err := c.memoryCatalog.List(ctx, prefix) + if err != nil { + return nil, err + } + for _, key := range c.phantom { + if strings.HasPrefix(key, prefix) { + keys = append(keys, key) + } + } + return keys, nil +} + func testPackedServer(t *testing.T, backend *memoryBackend) *Server { return testPackedServerWithMaxBlob(t, backend, 1024) } @@ -41,11 +62,11 @@ func testPackedServer(t *testing.T, backend *memoryBackend) *Server { func testPackedServerWithMaxBlob(t *testing.T, backend *memoryBackend, maxBlobSize int64) *Server { t.Helper() return testServer(t, backend, func(cfg *Config) { - cfg.StorageMode = "packs" cfg.Catalog = memoryCatalog{backend: backend} cfg.MaxBlobSize = maxBlobSize cfg.PackSize = 1024 cfg.PackFlushInterval = time.Hour + cfg.PackCompression = true cfg.MaxManifests = 100 }) } @@ -59,12 +80,27 @@ func closePackedServer(t *testing.T, server *Server) { } } +func cacheFilesWithPrefix(t *testing.T, dir, prefix string) []string { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + var paths []string + for _, entry := range entries { + if strings.HasPrefix(entry.Name(), prefix) { + paths = append(paths, entry.Name()) + } + } + return paths +} + func TestPackedStoreRoundTripCommitsPackBeforeManifest(t *testing.T) { backend := newMemoryBackend() seed := testPackedServer(t, backend) output := []byte("packed output") outputReference := referenceFor(output) - actionResult := bytesField(2, outputFileProto(outputReference, nil)) + actionResult := actionResultProto(t, outputReference) actionDigest := digest([]byte("packed action")) if response := putCacheObject(seed, "/cas/"+outputReference.hash, output); response.Code != http.StatusNoContent { t.Fatalf("CAS PUT = %d", response.Code) @@ -92,6 +128,119 @@ func TestPackedStoreRoundTripCommitsPackBeforeManifest(t *testing.T) { } } +func TestPackedStoreIndexesRawCASWithoutRedundantBlockID(t *testing.T) { + server := testPackedServer(t, newMemoryBackend()) + payload := []byte("raw object") + objectDigest := digest(payload) + if response := putCacheObject(server, "/cas/"+objectDigest, payload); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d, body = %s", response.Code, response.Body.String()) + } + if err := server.packs.flush(context.Background(), true); err != nil { + t.Fatal(err) + } + server.packs.mu.Lock() + entry, found := server.packs.cas[objectDigest] + server.packs.mu.Unlock() + if !found { + t.Fatal("flushed CAS object is absent from the packed index") + } + if entry.block != "" || entry.encoding != blockEncodingRaw || entry.size != int64(len(payload)) { + t.Fatalf("raw CAS index entry retains redundant metadata: %+v", entry) + } + if response := readCacheObject(server, "/cas/"+objectDigest); response.Code != http.StatusOK || response.Body.String() != string(payload) { + t.Fatalf("CAS GET = %d, body = %q", response.Code, response.Body.String()) + } + closePackedServer(t, server) +} + +func TestPackedStoreFlushReplacesUploadSpoolsWithLocalPack(t *testing.T) { + server := testPackedServer(t, newMemoryBackend()) + payload := []byte("keep only the committed pack") + digest := digest(payload) + if response := putCacheObject(server, "/cas/"+digest, payload); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d, body = %s", response.Code, response.Body.String()) + } + if got := len(cacheFilesWithPrefix(t, server.cfg.CacheDir, "upload-")); got != 1 { + t.Fatalf("upload spools before flush = %d, want 1", got) + } + + if err := server.packs.flush(context.Background(), true); err != nil { + t.Fatal(err) + } + if got := cacheFilesWithPrefix(t, server.cfg.CacheDir, "upload-"); len(got) != 0 { + t.Fatalf("flush left upload spools: %v", got) + } + if got := cacheFilesWithPrefix(t, server.cfg.CacheDir, "manifest-"); len(got) != 0 { + t.Fatalf("flush left manifest spools: %v", got) + } + if got := len(cacheFilesWithPrefix(t, server.cfg.CacheDir, "pack-")); got != 1 { + t.Fatalf("local packs after flush = %d, want 1", got) + } + if response := readCacheObject(server, "/cas/"+digest); response.Code != http.StatusOK || response.Body.String() != string(payload) { + t.Fatalf("CAS GET after flush = %d, body = %q", response.Code, response.Body.String()) + } + if stats := server.Snapshot(); stats.PackDownloads != 0 { + t.Fatalf("newly flushed pack was downloaded again: %+v", stats) + } + if response := putCacheObject(server, "/cas/"+digest, payload); response.Code != http.StatusNoContent { + t.Fatalf("duplicate CAS PUT = %d, body = %s", response.Code, response.Body.String()) + } + if got := cacheFilesWithPrefix(t, server.cfg.CacheDir, "upload-"); len(got) != 0 { + t.Fatalf("duplicate of a committed CAS left upload spools: %v", got) + } + + closePackedServer(t, server) + if got := cacheFilesWithPrefix(t, server.cfg.CacheDir, "pack-"); len(got) != 0 { + t.Fatalf("close left local pack files: %v", got) + } +} + +func TestPackedStoreFailedDownloadRemovesSpool(t *testing.T) { + server := testPackedServer(t, newMemoryBackend()) + defer closePackedServer(t, server) + + _, err := server.packs.downloadPack(context.Background(), packDescriptor{ + ID: strings.Repeat("0", 64), + Key: "missing-pack", + }) + if err == nil { + t.Fatal("download of a missing pack succeeded") + } + if got := cacheFilesWithPrefix(t, server.cfg.CacheDir, "pack-download-"); len(got) != 0 { + t.Fatalf("failed download left spool files: %v", got) + } +} + +func TestPackedStoreFailedFlushRemovesTemporaryPack(t *testing.T) { + backend := newMemoryBackend() + server := testPackedServer(t, backend) + payload := []byte("retry after a backend failure") + if response := putCacheObject(server, "/cas/"+digest(payload), payload); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d, body = %s", response.Code, response.Body.String()) + } + backend.mu.Lock() + backend.saveErr = errors.New("backend unavailable") + backend.mu.Unlock() + + if err := server.packs.flush(context.Background(), true); err == nil { + t.Fatal("flush succeeded while the backend was unavailable") + } + if got := cacheFilesWithPrefix(t, server.cfg.CacheDir, "pack-"); len(got) != 0 { + t.Fatalf("failed flush left pack files: %v", got) + } + if got := cacheFilesWithPrefix(t, server.cfg.CacheDir, "manifest-"); len(got) != 0 { + t.Fatalf("failed flush left manifest files: %v", got) + } + if got := len(cacheFilesWithPrefix(t, server.cfg.CacheDir, "upload-")); got != 1 { + t.Fatalf("failed flush discarded pending upload spools: got %d, want 1", got) + } + + backend.mu.Lock() + backend.saveErr = nil + backend.mu.Unlock() + closePackedServer(t, server) +} + func TestPackedStoreRestoresCASLargerThanCARDefaultSectionLimit(t *testing.T) { const payloadSize = (8 << 20) + 1 const maxBlobSize = payloadSize + 1024 @@ -148,7 +297,7 @@ func TestPackedStoreMergesConcurrentManifestHeads(t *testing.T) { } } -func TestPackedStoreTreatsMissingPackAsActionCacheMiss(t *testing.T) { +func TestPackedStoreLeavesOrphanedManifestsUnread(t *testing.T) { backend := newMemoryBackend() seed := testPackedServer(t, backend) actionDigest := digest([]byte("action")) @@ -157,6 +306,7 @@ func TestPackedStoreTreatsMissingPackAsActionCacheMiss(t *testing.T) { } closePackedServer(t, seed) + // Emulate GitHub evicting the large pack while its small manifest survives. backend.mu.Lock() for key := range backend.objects { if strings.Contains(key, "-car-pack-v1-") { @@ -164,14 +314,306 @@ func TestPackedStoreTreatsMissingPackAsActionCacheMiss(t *testing.T) { } } backend.mu.Unlock() + + loadsBeforeDiscovery := backend.loadCount() restore := testPackedServer(t, backend) defer closePackedServer(t, restore) + if backend.loadCount() != loadsBeforeDiscovery { + t.Fatal("an orphaned manifest was downloaded, which would renew its lifetime") + } if response := readCacheObject(restore, "/ac/"+actionDigest); response.Code != http.StatusNotFound { - t.Fatalf("missing pack action result = %d", response.Code) + t.Fatalf("orphaned action result = %d", response.Code) + } + stats := restore.Snapshot() + if stats.ManifestsDiscovered != 1 || stats.ManifestsOrphaned != 1 || stats.BackendLoadErrors != 0 { + t.Fatalf("unexpected orphaned-manifest stats: %+v", stats) + } +} + +func TestPackedStoreRetriesAnUnrestorablePackOnlyOnce(t *testing.T) { + backend := newMemoryBackend() + seed := testPackedServer(t, backend) + body := []byte("out of scope payload") + if response := putCacheObject(seed, "/cas/"+digest(body), body); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + closePackedServer(t, seed) + + // A pack listed for the repository can still be outside this job's cache + // scope, which only a failed download reveals. + var packKey string + backend.mu.Lock() + for key := range backend.objects { + if strings.Contains(key, "-car-pack-v1-") { + packKey = key + } + } + delete(backend.objects, packKey) + backend.mu.Unlock() + if packKey == "" { + t.Fatal("no pack was published") + } + + restore := testServer(t, backend, func(cfg *Config) { + cfg.Catalog = phantomCatalog{memoryCatalog{backend: backend}, []string{packKey}} + cfg.PackSize = 1024 + cfg.PackFlushInterval = time.Hour + cfg.MaxManifests = 100 + }) + defer closePackedServer(t, restore) + for attempt := 0; attempt < 2; attempt++ { + if response := readCacheObject(restore, "/cas/"+digest(body)); response.Code != http.StatusNotFound { + t.Fatalf("attempt %d = %d", attempt, response.Code) + } + } + stats := restore.Snapshot() + if stats.ManifestsOrphaned != 0 || stats.PackLoadsSkipped != 1 { + t.Fatalf("an unrestorable pack was not memoized: %+v", stats) } } -func TestPackedStoreRejectsConflictingActionResults(t *testing.T) { +func TestPackedStoreDiscoversPacksAndManifests(t *testing.T) { + backend := newMemoryBackend() + seed := testPackedServer(t, backend) + body := []byte("listed payload") + if response := putCacheObject(seed, "/cas/"+digest(body), body); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + closePackedServer(t, seed) + + restore := testPackedServer(t, backend) + defer closePackedServer(t, restore) + stats := restore.Snapshot() + if stats.PacksDiscovered != 1 || stats.ManifestsDiscovered != 1 { + t.Fatalf("unexpected discovery stats: %+v", stats) + } + if response := readCacheObject(restore, "/cas/"+digest(body)); response.Code != http.StatusOK { + t.Fatalf("CAS GET = %d", response.Code) + } +} + +func TestPackedStoreLimitsDownloadedManifestsWithoutCountingPacks(t *testing.T) { + backend := newMemoryBackend() + payloads := [][]byte{[]byte("one"), []byte("two"), []byte("three")} + for _, body := range payloads { + writer := testPackedServer(t, backend) + if response := putCacheObject(writer, "/cas/"+digest(body), body); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + closePackedServer(t, writer) + } + + restore := testServer(t, backend, func(cfg *Config) { + cfg.Catalog = memoryCatalog{backend: backend} + cfg.PackSize = 1024 + cfg.PackFlushInterval = time.Hour + cfg.MaxManifests = 2 + }) + defer closePackedServer(t, restore) + stats := restore.Snapshot() + if stats.PacksDiscovered != 3 || stats.ManifestsDiscovered != 3 || stats.ManifestsSkipped != 1 { + t.Fatalf("unexpected bounded-discovery stats: %+v", stats) + } + for _, body := range payloads { + readCacheObject(restore, "/cas/"+digest(body)) + } + stats = restore.Snapshot() + if stats.Hits != 2 || stats.Misses != 1 { + t.Fatalf("max-manifests should bound manifest reads, not the pack listing: %+v", stats) + } +} + +func TestPackedStoreDoesNotSpendTheManifestLimitOnOrphans(t *testing.T) { + backend := newMemoryBackend() + payloads := [][]byte{[]byte("one"), []byte("two"), []byte("three")} + packKeys := make(map[string]string, len(payloads)) + known := make(map[string]bool) + for _, body := range payloads { + writer := testPackedServer(t, backend) + if response := putCacheObject(writer, "/cas/"+digest(body), body); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + closePackedServer(t, writer) + backend.mu.Lock() + for key := range backend.objects { + if strings.Contains(key, "-car-pack-v1-") && !known[key] { + known[key] = true + packKeys[string(body)] = key + } + } + backend.mu.Unlock() + } + + // Two of the three manifests are orphaned. A budget of one must be spent on + // the manifest that can still produce a hit. + backend.mu.Lock() + delete(backend.objects, packKeys["one"]) + delete(backend.objects, packKeys["two"]) + backend.mu.Unlock() + + restore := testServer(t, backend, func(cfg *Config) { + cfg.Catalog = memoryCatalog{backend: backend} + cfg.PackSize = 1024 + cfg.PackFlushInterval = time.Hour + cfg.MaxManifests = 1 + }) + defer closePackedServer(t, restore) + stats := restore.Snapshot() + if stats.ManifestsDiscovered != 3 || stats.ManifestsOrphaned != 2 || stats.ManifestsSkipped != 0 { + t.Fatalf("orphans consumed the manifest budget: %+v", stats) + } + if response := readCacheObject(restore, "/cas/"+digest([]byte("three"))); response.Code != http.StatusOK { + t.Fatalf("live manifest was not read: %d", response.Code) + } + if response := readCacheObject(restore, "/cas/"+digest([]byte("one"))); response.Code != http.StatusNotFound { + t.Fatalf("orphaned mapping = %d", response.Code) + } +} + +func TestPackedStorePresenceCheckRenewsPackWithoutDownloadingIt(t *testing.T) { + backend := newMemoryBackend() + seed := testPackedServer(t, backend) + payloads := [][]byte{[]byte("presence one"), []byte("presence two")} + for _, body := range payloads { + if response := putCacheObject(seed, "/cas/"+digest(body), body); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + } + closePackedServer(t, seed) + + restore := testPackedServer(t, backend) + loadsAfterDiscovery := backend.loadCount() + for _, body := range payloads { + response := headCacheObject(restore, "/cas/"+digest(body)) + if response.Code != http.StatusOK { + t.Fatalf("HEAD = %d", response.Code) + } + if got := response.Header().Get("Content-Length"); got != strconv.Itoa(len(body)) { + t.Fatalf("Content-Length = %q", got) + } + if response.Body.Len() != 0 { + t.Fatal("HEAD returned a body") + } + } + if backend.loadCount() != loadsAfterDiscovery { + t.Fatal("a presence check restored the pack") + } + if backend.existsCount() != 0 { + t.Fatal("renewal was issued immediately instead of being batched") + } + + closePackedServer(t, restore) + if backend.existsCount() != 1 { + t.Fatalf("expected one renewal for the shared pack, got %d", backend.existsCount()) + } + if stats := restore.Snapshot(); stats.PackRenewals != 1 || stats.PackDownloads != 0 { + t.Fatalf("unexpected renewal stats: %+v", stats) + } +} + +func TestPackedStoreSkipsRenewalWhenThePackIsDownloaded(t *testing.T) { + backend := newMemoryBackend() + seed := testPackedServer(t, backend) + body := []byte("downloaded soon after") + if response := putCacheObject(seed, "/cas/"+digest(body), body); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + closePackedServer(t, seed) + + restore := testPackedServer(t, backend) + if response := headCacheObject(restore, "/cas/"+digest(body)); response.Code != http.StatusOK { + t.Fatalf("HEAD = %d", response.Code) + } + if response := readCacheObject(restore, "/cas/"+digest(body)); response.Code != http.StatusOK { + t.Fatalf("GET = %d", response.Code) + } + closePackedServer(t, restore) + if backend.existsCount() != 0 { + t.Fatalf("the download should have covered the renewal, got %d calls", backend.existsCount()) + } + if stats := restore.Snapshot(); stats.PackRenewals != 0 || stats.PackDownloads != 1 { + t.Fatalf("unexpected stats: %+v", stats) + } +} + +// seedPackedClosure publishes an output blob and then, in a separate job, an +// action result referencing it, so the two land in different packs. +func seedPackedClosure(t *testing.T, backend *memoryBackend, output []byte, actionDigest string) string { + t.Helper() + reference := referenceFor(output) + blobWriter := testPackedServer(t, backend) + if response := putCacheObject(blobWriter, "/cas/"+reference.hash, output); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + closePackedServer(t, blobWriter) + var blobPackKey string + backend.mu.Lock() + for key := range backend.objects { + if strings.Contains(key, "-car-pack-v1-") { + blobPackKey = key + } + } + backend.mu.Unlock() + if blobPackKey == "" { + t.Fatal("no pack was published for the output") + } + + actionWriter := testPackedServer(t, backend) + if response := putCacheObject(actionWriter, "/ac/"+actionDigest, actionResultProto(t, reference)); response.Code != http.StatusNoContent { + t.Fatalf("AC PUT = %d", response.Code) + } + closePackedServer(t, actionWriter) + return blobPackKey +} + +func TestPackedStoreRefusesActionResultWithAnEvictedOutputPack(t *testing.T) { + backend := newMemoryBackend() + actionDigest := digest([]byte("action with evicted output")) + blobPackKey := seedPackedClosure(t, backend, []byte("evicted output"), actionDigest) + + backend.mu.Lock() + delete(backend.objects, blobPackKey) + backend.mu.Unlock() + + restore := testPackedServer(t, backend) + defer closePackedServer(t, restore) + if response := readCacheObject(restore, "/ac/"+actionDigest); response.Code != http.StatusNotFound { + t.Fatalf("action result with an evicted output = %d", response.Code) + } + if stats := restore.Snapshot(); stats.IncompleteActionResults != 1 { + t.Fatalf("closure was not checked before serving: %+v", stats) + } +} + +func TestPackedStoreActionResultHitRenewsItsClosurePacks(t *testing.T) { + backend := newMemoryBackend() + actionDigest := digest([]byte("action with a remote output")) + seedPackedClosure(t, backend, []byte("output kept in another pack"), actionDigest) + // The publishing job presence-checks the output too, so count from here. + renewalsAfterSeeding := backend.existsCount() + + restore := testPackedServer(t, backend) + if response := readCacheObject(restore, "/ac/"+actionDigest); response.Code != http.StatusOK { + t.Fatalf("AC GET = %d", response.Code) + } + stats := restore.Snapshot() + if stats.PackDownloads != 1 || stats.ValidatedActionResults != 1 { + t.Fatalf("serving an action result should restore only its own pack: %+v", stats) + } + if backend.existsCount() != renewalsAfterSeeding { + t.Fatal("renewal was issued immediately instead of being batched") + } + + closePackedServer(t, restore) + if backend.existsCount() != renewalsAfterSeeding+1 { + t.Fatalf("the closure pack was not renewed, got %d calls", backend.existsCount()-renewalsAfterSeeding) + } + if stats := restore.Snapshot(); stats.PackRenewals != 1 { + t.Fatalf("unexpected renewal stats: %+v", stats) + } +} + +func TestPackedStoreServesOneOfConflictingActionResults(t *testing.T) { backend := newMemoryBackend() writerA := testPackedServer(t, backend) writerB := testPackedServer(t, backend) @@ -185,12 +627,96 @@ func TestPackedStoreRejectsConflictingActionResults(t *testing.T) { closePackedServer(t, writerA) closePackedServer(t, writerB) - restore := testPackedServer(t, backend) - defer closePackedServer(t, restore) - if response := readCacheObject(restore, "/ac/"+actionDigest); response.Code != http.StatusNotFound { - t.Fatalf("conflicting action result = %d", response.Code) + var served []byte + for range 2 { + restore := testPackedServer(t, backend) + response := readCacheObject(restore, "/ac/"+actionDigest) + if response.Code != http.StatusOK { + t.Fatalf("conflicting action result = %d", response.Code) + } + if restore.Snapshot().ActionDigestConflicts != 1 { + t.Fatalf("conflict was not reported: %+v", restore.Snapshot()) + } + if served != nil && !bytes.Equal(served, response.Body.Bytes()) { + t.Fatalf("restores disagree on the served result: %x and %x", served, response.Body.Bytes()) + } + served = response.Body.Bytes() + closePackedServer(t, restore) } - if restore.Snapshot().ActionDigestConflicts != 1 { - t.Fatalf("conflict was not reported: %+v", restore.Snapshot()) + + servedCID, err := rawCIDForData(served) + if err != nil { + t.Fatal(err) + } + var inLayout bool + for _, entry := range readLayout(t, backend).Entries { + if entry.Kind == "ac" && entry.Digest == actionDigest && entry.CID == servedCID.String() { + inLayout = true + } + } + if !inLayout { + t.Fatal("the layout does not resolve the action to the served result") + } +} + +func TestPackedStoreServesReadsWhileAFlushIsUploading(t *testing.T) { + memory := newMemoryBackend() + seed := testPackedServer(t, memory) + restored := []byte("restored while uploading") + if response := putCacheObject(seed, "/cas/"+digest(restored), restored); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + closePackedServer(t, seed) + + backend := &blockingSaveBackend{ + memoryBackend: memory, + started: make(chan struct{}), + release: make(chan struct{}), + } + server := testServer(t, backend, func(cfg *Config) { + cfg.Catalog = memoryCatalog{backend: memory} + cfg.PackSize = 1024 + cfg.PackFlushInterval = time.Hour + cfg.MaxManifests = 100 + cfg.BackendTimeout = time.Minute + }) + staged := []byte("staged for the next pack") + if response := putCacheObject(server, "/cas/"+digest(staged), staged); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + flushed := make(chan error, 1) + go func() { flushed <- server.packs.flush(context.Background(), true) }() + <-backend.started + + read := make(chan *httptest.ResponseRecorder, 1) + go func() { read <- readCacheObject(server, "/cas/"+digest(restored)) }() + select { + case response := <-read: + if response.Code != http.StatusOK || response.Body.String() != string(restored) { + t.Fatalf("CAS GET = %d, body = %q", response.Code, response.Body.String()) + } + case <-time.After(10 * time.Second): + t.Fatal("a pack read waited for an unrelated upload") + } + + close(backend.release) + if err := <-flushed; err != nil { + t.Fatal(err) + } + closePackedServer(t, server) +} + +func TestManifestReadConcurrencyRaisesButNeverLowers(t *testing.T) { + for _, test := range []struct { + maxConcurrent int + want int + }{ + {maxConcurrent: 1, want: 16}, + {maxConcurrent: 4, want: 16}, + {maxConcurrent: 64, want: 64}, + } { + if got := manifestReadConcurrency(test.maxConcurrent); got != test.want { + t.Errorf("manifestReadConcurrency(%d) = %d, want %d", test.maxConcurrent, got, test.want) + } } } diff --git a/internal/server/reapi_digest.go b/internal/server/reapi_digest.go new file mode 100644 index 0000000..7f1f09f --- /dev/null +++ b/internal/server/reapi_digest.go @@ -0,0 +1,28 @@ +package server + +import ( + "fmt" + + remoteexecution "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/execution/v2" +) + +const emptySHA256Digest = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + +// digestReferenceFrom validates a decoded REAPI digest and converts it to the +// internal representation. name identifies the enclosing field in error messages. +func digestReferenceFrom(digest *remoteexecution.Digest, name string) (digestReference, error) { + if digest == nil { + return digestReference{}, fmt.Errorf("%s is missing", name) + } + if !digestPattern.MatchString(digest.GetHash()) { + return digestReference{}, fmt.Errorf("%s.hash is not a lowercase SHA-256 digest", name) + } + if digest.GetSizeBytes() < 0 { + return digestReference{}, fmt.Errorf("%s.size_bytes is negative", name) + } + return digestReference{hash: digest.GetHash(), size: digest.GetSizeBytes()}, nil +} + +func isImplicitEmptyDigest(reference digestReference) bool { + return reference.hash == emptySHA256Digest && reference.size == 0 +} diff --git a/internal/server/reapi_directory.go b/internal/server/reapi_directory.go index f6a53c0..ed567cd 100644 --- a/internal/server/reapi_directory.go +++ b/internal/server/reapi_directory.go @@ -5,122 +5,86 @@ import ( "encoding/hex" "errors" "fmt" + "slices" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + + remoteexecution "github.com/cre4ture/bazel-github-actions-cache-v2/internal/proto/gen/build/bazel/remote/execution/v2" +) + +var ( + treeRootField = treeFieldNumber("root") + treeChildrenField = treeFieldNumber("children") ) +func treeFieldNumber(name protoreflect.Name) protowire.Number { + field := (&remoteexecution.Tree{}).ProtoReflect().Descriptor().Fields().ByName(name) + if field == nil { + panic("build.bazel.remote.execution.v2.Tree has no field " + string(name)) + } + return protowire.Number(field.Number()) +} + type parsedDirectory struct { files []digestReference directories []digestReference } func parseDirectory(data []byte) (parsedDirectory, error) { + message := &remoteexecution.Directory{} + if err := proto.Unmarshal(data, message); err != nil { + return parsedDirectory{}, fmt.Errorf("directory: %w", err) + } var directory parsedDirectory - err := visitWireFields(data, func(field wireField) error { - switch field.number { - case 1: - message, err := field.message("directory.files") - if err != nil { - return err - } - reference, err := parseNodeDigest(message, "file_node") - if err != nil { - return err - } - directory.files = append(directory.files, reference) - case 2: - message, err := field.message("directory.directories") - if err != nil { - return err - } - reference, err := parseNodeDigest(message, "directory_node") - if err != nil { - return err - } - directory.directories = append(directory.directories, reference) - } - return nil - }) - return directory, err -} - -func parseNodeDigest(data []byte, nodeName string) (digestReference, error) { - var digest *digestReference - err := visitWireFields(data, func(field wireField) error { - if field.number != 2 { - return nil - } - message, err := field.message(nodeName + ".digest") + for _, file := range message.GetFiles() { + reference, err := digestReferenceFrom(file.GetDigest(), "file_node.digest") if err != nil { - return err + return parsedDirectory{}, err } - reference, err := parseDigest(message) + directory.files = append(directory.files, reference) + } + for _, child := range message.GetDirectories() { + reference, err := digestReferenceFrom(child.GetDigest(), "directory_node.digest") if err != nil { - return fmt.Errorf("%s.digest: %w", nodeName, err) + return parsedDirectory{}, err } - if digest != nil { - return fmt.Errorf("%s.digest is repeated", nodeName) - } - digest = &reference - return nil - }) - if err != nil { - return digestReference{}, err - } - if digest == nil { - return digestReference{}, fmt.Errorf("%s has no digest", nodeName) + directory.directories = append(directory.directories, reference) } - return *digest, nil + return directory, nil } func parseTree(data []byte) ([]digestReference, error) { - var directories []parsedDirectory - childDigests := make(map[string]int64) - rootSeen := false - - err := visitWireFields(data, func(field wireField) error { - if field.number != 1 && field.number != 2 { - return nil - } - message, err := field.message("tree.directory") - if err != nil { - return err - } - if field.number == 1 { - if rootSeen { - return errors.New("tree.root is repeated") - } - rootSeen = true - } else { - sum := sha256.Sum256(message) - hash := hex.EncodeToString(sum[:]) - if existingSize, exists := childDigests[hash]; exists && existingSize != int64(len(message)) { - return fmt.Errorf("tree child %s has inconsistent sizes", hash) - } - childDigests[hash] = int64(len(message)) - } - directory, err := parseDirectory(message) - if err != nil { - return fmt.Errorf("tree.directory: %w", err) - } - directories = append(directories, directory) - return nil - }) + roots, children, err := splitTree(data) if err != nil { return nil, err } - if !rootSeen { + if len(roots) == 0 { return nil, errors.New("tree has no root directory") } + if len(roots) > 1 { + return nil, errors.New("tree.root is repeated") + } + childDigests := make(map[string]int64, len(children)) + for _, child := range children { + sum := sha256.Sum256(child) + childDigests[hex.EncodeToString(sum[:])] = int64(len(child)) + } files := newDigestCollection() - for _, directory := range directories { + for _, encoded := range slices.Concat(roots, children) { + directory, err := parseDirectory(encoded) + if err != nil { + return nil, fmt.Errorf("tree.directory: %w", err) + } for _, file := range directory.files { if err := files.add(file); err != nil { return nil, err } } for _, child := range directory.directories { - size, exists := childDigests[child.hash] - if !exists || size != child.size { + if size, exists := childDigests[child.hash]; !exists || size != child.size { return nil, fmt.Errorf( "tree references missing child directory %s/%d", child.hash, @@ -131,3 +95,37 @@ func parseTree(data []byte) ([]digestReference, error) { } return files.values, nil } + +// splitTree returns the encoded root and child Directory messages of a Tree. A +// Directory digest covers the exact bytes its producer emitted, so the embedded +// messages have to be hashed as received; re-encoding the decoded messages is not +// guaranteed to reproduce those bytes. +func splitTree(data []byte) (roots [][]byte, children [][]byte, err error) { + for len(data) > 0 { + number, wireType, consumed := protowire.ConsumeTag(data) + if consumed < 0 { + return nil, nil, protowire.ParseError(consumed) + } + data = data[consumed:] + + if wireType == protowire.BytesType && (number == treeRootField || number == treeChildrenField) { + value, n := protowire.ConsumeBytes(data) + if n < 0 { + return nil, nil, protowire.ParseError(n) + } + if number == treeRootField { + roots = append(roots, value) + } else { + children = append(children, value) + } + consumed = n + } else { + consumed = protowire.ConsumeFieldValue(number, wireType, data) + if consumed < 0 { + return nil, nil, protowire.ParseError(consumed) + } + } + data = data[consumed:] + } + return roots, children, nil +} diff --git a/internal/server/reapi_wire.go b/internal/server/reapi_wire.go deleted file mode 100644 index 76b758c..0000000 --- a/internal/server/reapi_wire.go +++ /dev/null @@ -1,112 +0,0 @@ -package server - -import ( - "errors" - "fmt" - "math" - - "google.golang.org/protobuf/encoding/protowire" -) - -const emptySHA256Digest = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" - -func parseDigest(data []byte) (digestReference, error) { - var hash string - var size int64 - var hashSeen bool - var sizeSeen bool - err := visitWireFields(data, func(field wireField) error { - switch field.number { - case 1: - value, err := field.message("digest.hash") - if err != nil { - return err - } - if hashSeen { - return errors.New("digest.hash is repeated") - } - hashSeen = true - hash = string(value) - case 2: - if field.wireType != protowire.VarintType { - return errors.New("digest.size_bytes has the wrong wire type") - } - if sizeSeen { - return errors.New("digest.size_bytes is repeated") - } - if field.varintValue > math.MaxInt64 { - return errors.New("digest.size_bytes is negative or overflows int64") - } - sizeSeen = true - size = int64(field.varintValue) - } - return nil - }) - if err != nil { - return digestReference{}, err - } - if !hashSeen || !digestPattern.MatchString(hash) { - return digestReference{}, errors.New("digest.hash is not a lowercase SHA-256 digest") - } - return digestReference{hash: hash, size: size}, nil -} - -func isImplicitEmptyDigest(reference digestReference) bool { - return reference.hash == emptySHA256Digest && reference.size == 0 -} - -type wireField struct { - number protowire.Number - wireType protowire.Type - bytesValue []byte - varintValue uint64 -} - -func (f wireField) message(name string) ([]byte, error) { - if f.wireType != protowire.BytesType { - return nil, fmt.Errorf("%s has the wrong wire type", name) - } - return f.bytesValue, nil -} - -func visitWireFields(data []byte, visit func(wireField) error) error { - for len(data) > 0 { - number, wireType, consumed := protowire.ConsumeTag(data) - if consumed < 0 { - return protowire.ParseError(consumed) - } - if number < 1 { - return errors.New("protobuf field number must be positive") - } - data = data[consumed:] - - field := wireField{number: number, wireType: wireType} - switch wireType { - case protowire.BytesType: - value, n := protowire.ConsumeBytes(data) - if n < 0 { - return protowire.ParseError(n) - } - field.bytesValue = value - consumed = n - case protowire.VarintType: - value, n := protowire.ConsumeVarint(data) - if n < 0 { - return protowire.ParseError(n) - } - field.varintValue = value - consumed = n - default: - consumed = protowire.ConsumeFieldValue(number, wireType, data) - if consumed < 0 { - return protowire.ParseError(consumed) - } - } - - if err := visit(field); err != nil { - return err - } - data = data[consumed:] - } - return nil -} diff --git a/internal/server/repack.go b/internal/server/repack.go new file mode 100644 index 0000000..a623b43 --- /dev/null +++ b/internal/server/repack.go @@ -0,0 +1,362 @@ +package server + +import ( + "context" + "errors" + "fmt" + "os" + "sync" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/cache" + blocks "github.com/ipfs/go-block-format" + "github.com/ipfs/go-cid" + "github.com/ipld/go-car/v2/blockstore" +) + +// Repacker rebuilds packs out of existing ones. It only ever adds: a new pack +// and its manifest leave the originals readable, so failing part way through +// costs storage rather than cache hits. +// +// Publish may be called concurrently. Calls that need the same source pack +// share one download of it. +type Repacker struct { + options RepackOptions + packs map[string]LayoutPack + limiter *intervalLimiter + + mu sync.Mutex + sources map[string]*sourcePack +} + +// sourcePack is a pack being copied out of, held open so that moving its blocks +// does not reopen and re-index the archive once per block. ready closes once +// the download has finished, successfully or not. +type sourcePack struct { + ready chan struct{} + path string + store *blockstore.ReadOnly + err error +} + +type RepackOptions struct { + Backend cache.Backend + CacheDir string + KeyPrefix string + MaxBlobSize int64 + Timeout time.Duration + // UploadsPerMinute spaces publications evenly, as the cache server does. + // GitHub documents a 200/minute cache upload limit. + UploadsPerMinute int + // Parents are the manifest heads a published manifest descends from. + Parents []string + // Packs supplies the source pack descriptors entries are copied out of. + Packs []LayoutPack +} + +func NewRepacker(options RepackOptions) (*Repacker, error) { + if options.Backend == nil { + return nil, errors.New("repacking needs a backend") + } + if options.CacheDir == "" { + return nil, errors.New("repacking needs a spool directory") + } + if options.MaxBlobSize <= 0 { + options.MaxBlobSize = 512 * 1024 * 1024 + } + if options.UploadsPerMinute <= 0 { + options.UploadsPerMinute = 180 + } + // The cache server creates its spool in New; a repacker has no equivalent, so + // it makes its own. + if err := os.MkdirAll(options.CacheDir, 0o700); err != nil { + return nil, fmt.Errorf("prepare the repacking spool: %w", err) + } + packs := make(map[string]LayoutPack, len(options.Packs)) + for _, pack := range options.Packs { + packs[pack.ID] = pack + } + return &Repacker{ + options: options, + sources: make(map[string]*sourcePack), + packs: packs, + limiter: newIntervalLimiter(options.UploadsPerMinute), + }, nil +} + +// Release drops a source pack this repacker no longer needs, freeing the local +// copy. Calling it for a pack still to be read simply costs a second download, +// but it must not race a Publish that is reading the pack. +func (r *Repacker) Release(packID string) { + r.mu.Lock() + source, held := r.sources[packID] + delete(r.sources, packID) + r.mu.Unlock() + if !held { + return + } + <-source.ready + if source.store != nil { + _ = source.store.Close() + os.Remove(source.path) + } +} + +// Publish writes the entries into one new pack and commits a manifest for it. +// Entries still name the pack they are being copied out of. A non-zero since +// is recorded as when the pack's contents took their shape; zero leaves the +// pack's own creation time to stand for it. +func (r *Repacker) Publish(ctx context.Context, entries []LayoutEntry, since time.Time) (LayoutPack, string, error) { + if len(entries) == 0 { + return LayoutPack{}, "", errors.New("cannot publish an empty pack") + } + type block struct { + id cid.Cid + data []byte + } + gathered := make([]block, 0, len(entries)) + for _, entry := range entries { + data, err := r.readBlock(ctx, entry) + if err != nil { + return LayoutPack{}, "", err + } + blockCID, err := cid.Decode(entry.Block) + if err != nil { + return LayoutPack{}, "", err + } + gathered = append(gathered, block{id: blockCID, data: data}) + } + + path, err := writePrivateTemp(r.options.CacheDir, "repack-*", nil) + if err != nil { + return LayoutPack{}, "", err + } + defer os.Remove(path) + store, err := openPackWriter(path, gathered[0].id) + if err != nil { + return LayoutPack{}, "", err + } + for _, item := range gathered { + value, err := blocks.NewBlockWithCid(item.data, item.id) + if err != nil { + store.Discard() + return LayoutPack{}, "", err + } + if err := store.Put(ctx, value); err != nil { + store.Discard() + return LayoutPack{}, "", err + } + } + if err := store.Finalize(); err != nil { + return LayoutPack{}, "", err + } + + info, err := os.Stat(path) + if err != nil { + return LayoutPack{}, "", err + } + file, err := os.Open(path) + if err != nil { + return LayoutPack{}, "", err + } + packID, hashErr := hashFile(file) + closeErr := file.Close() + if hashErr != nil { + return LayoutPack{}, "", hashErr + } + if closeErr != nil { + return LayoutPack{}, "", closeErr + } + + pack := LayoutPack{ + ID: packID, + Key: packKeyFor(r.options.KeyPrefix, packID), + StoredSize: info.Size(), + } + if !since.IsZero() { + pack.Since = since.UTC().Truncate(time.Second) + } + // The pack goes first so no manifest ever advertises data a reader cannot + // restore, which is the same ordering the cache server commits with. + if err := r.publishFile(ctx, pack.Key, path, pack.StoredSize); err != nil { + return LayoutPack{}, "", fmt.Errorf("publish rebuilt pack: %w", err) + } + + manifestID, err := r.publishManifest(ctx, pack, entries) + if err != nil { + return LayoutPack{}, "", err + } + return pack, manifestID, nil +} + +func (r *Repacker) publishManifest(ctx context.Context, pack LayoutPack, entries []LayoutEntry) (string, error) { + value := manifest{ + Version: manifestFormatVersion, + Parents: append([]string(nil), r.options.Parents...), + Packs: []packDescriptor{{ID: pack.ID, Key: pack.Key, Size: pack.StoredSize, Since: unixOrZero(pack.Since)}}, + } + for _, entry := range entries { + switch entry.Kind { + case "cas": + value.CAS = append(value.CAS, manifestObject{ + Digest: entry.Digest, CID: entry.CID, Block: entry.Block, + Encoding: entry.Encoding, PackID: pack.ID, Size: entry.Size, + }) + case "ac": + value.Actions = append(value.Actions, manifestAction{ + Digest: entry.Digest, CID: entry.CID, Block: entry.Block, + Encoding: entry.Encoding, PackID: pack.ID, Size: entry.Size, + }) + default: + return "", fmt.Errorf("unknown entry kind %q", entry.Kind) + } + } + data, manifestID, err := encodeManifest(value) + if err != nil { + return "", err + } + // Decoding is what enforces the manifest's own invariants, so round-tripping + // here refuses to publish a commit point a reader would reject. + if _, err := decodeManifest(data, manifestID); err != nil { + return "", fmt.Errorf("rebuilt manifest is not readable: %w", err) + } + path, err := writePrivateTemp(r.options.CacheDir, "repack-manifest-*", data) + if err != nil { + return "", err + } + defer os.Remove(path) + key := manifestKeyFor(r.options.KeyPrefix, pack.ID, manifestID) + if err := r.publishFile(ctx, key, path, int64(len(data))); err != nil { + return "", fmt.Errorf("publish rebuilt manifest: %w", err) + } + return manifestID, nil +} + +func unixOrZero(at time.Time) int64 { + if at.IsZero() { + return 0 + } + return at.Unix() +} + +func (r *Repacker) readBlock(ctx context.Context, entry LayoutEntry) ([]byte, error) { + source, err := r.source(ctx, entry.Pack) + if err != nil { + return nil, err + } + // Reading by the block CID verifies the stored bytes, so a copy can never + // launder a corrupt block into a new pack. + return blockFromStore(ctx, source.store, entry.Block) +} + +func (r *Repacker) source(ctx context.Context, packID string) (*sourcePack, error) { + r.mu.Lock() + source, found := r.sources[packID] + if !found { + source = &sourcePack{ready: make(chan struct{})} + r.sources[packID] = source + } + r.mu.Unlock() + if found { + select { + case <-source.ready: + case <-ctx.Done(): + return nil, ctx.Err() + } + if source.err != nil { + return nil, source.err + } + return source, nil + } + + source.path, source.store, source.err = r.load(ctx, packID) + if source.err != nil { + // Forgotten so that a later call retries rather than inheriting a + // failure that may have been this call's cancelled context. + r.mu.Lock() + if r.sources[packID] == source { + delete(r.sources, packID) + } + r.mu.Unlock() + } + close(source.ready) + if source.err != nil { + return nil, source.err + } + return source, nil +} + +func (r *Repacker) load(ctx context.Context, packID string) (string, *blockstore.ReadOnly, error) { + descriptor, known := r.packs[packID] + if !known { + return "", nil, fmt.Errorf("no descriptor for source pack %s", packID) + } + path, err := writePrivateTemp(r.options.CacheDir, "source-*", nil) + if err != nil { + return "", nil, err + } + file, err := os.OpenFile(path, os.O_WRONLY, 0o600) + if err != nil { + os.Remove(path) + return "", nil, err + } + loadCtx, cancel := context.WithTimeout(ctx, r.options.Timeout) + found, loadErr := r.options.Backend.Load(loadCtx, descriptor.Key, file) + cancel() + closeErr := file.Close() + if loadErr != nil || closeErr != nil || !found { + os.Remove(path) + if loadErr != nil { + return "", nil, loadErr + } + if closeErr != nil { + return "", nil, closeErr + } + return "", nil, fmt.Errorf("source pack %s is gone", packID) + } + info, err := os.Stat(path) + if err != nil { + os.Remove(path) + return "", nil, err + } + if info.Size() != descriptor.StoredSize { + os.Remove(path) + return "", nil, fmt.Errorf("source pack %s has size %d; the manifest declares %d", + packID, info.Size(), descriptor.StoredSize) + } + store, err := openPackReader(path, r.options.MaxBlobSize) + if err != nil { + os.Remove(path) + return "", nil, err + } + return path, store, nil +} + +func (r *Repacker) publishFile(ctx context.Context, key, path string, size int64) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + if _, err := r.limiter.wait(ctx); err != nil { + return err + } + saveCtx, cancel := context.WithTimeout(ctx, r.options.Timeout) + defer cancel() + return r.options.Backend.Save(saveCtx, key, file, size) +} + +// Close removes the source packs this repacker spooled locally. No Publish may +// be running. +func (r *Repacker) Close() error { + r.mu.Lock() + held := make([]string, 0, len(r.sources)) + for packID := range r.sources { + held = append(held, packID) + } + r.mu.Unlock() + for _, packID := range held { + r.Release(packID) + } + return nil +} diff --git a/internal/server/repack_test.go b/internal/server/repack_test.go new file mode 100644 index 0000000..f3b95ec --- /dev/null +++ b/internal/server/repack_test.go @@ -0,0 +1,510 @@ +package server + +import ( + "bytes" + "context" + "net/http" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +func readLayout(t *testing.T, backend *memoryBackend) Layout { + t.Helper() + layout, err := ReadLayout(context.Background(), LayoutOptions{ + Backend: backend, + Catalog: memoryCatalog{backend: backend}, + KeyPrefix: "test-v1", + MaxBlobSize: 1 << 20, + Timeout: 5 * time.Second, + Warn: func(string, ...any) {}, + }) + if err != nil { + t.Fatal(err) + } + if len(layout.Entries) == 0 { + t.Fatal("the layout is empty, so anything built on it proves nothing") + } + return layout +} + +func seedPacked(t *testing.T, backend *memoryBackend, blobs ...[]byte) { + t.Helper() + writer := testPackedServer(t, backend) + for _, blob := range blobs { + if response := putCacheObject(writer, "/cas/"+digest(blob), blob); response.Code != http.StatusNoContent { + t.Fatalf("seed PUT = %d", response.Code) + } + } + closePackedServer(t, writer) +} + +func addChildManifestSortingBeforeParent(t *testing.T, backend *memoryBackend) (string, string) { + t.Helper() + layout := readLayout(t, backend) + if len(layout.Manifests) != 1 { + t.Fatalf("seed manifests = %d, want 1", len(layout.Manifests)) + } + parentReference := layout.Manifests[0] + backend.mu.Lock() + parentData := bytes.Clone(backend.objects[parentReference.Key]) + backend.mu.Unlock() + parent, err := decodeManifest(parentData, parentReference.ID) + if err != nil { + t.Fatal(err) + } + + for since := int64(1); since <= 10_000; since++ { + child := parent + child.Parents = []string{parentReference.ID} + child.Packs = append([]packDescriptor(nil), parent.Packs...) + child.Packs[0].Since = since + data, id, err := encodeManifest(child) + if err != nil { + t.Fatal(err) + } + if id >= parentReference.ID { + continue + } + key := manifestKeyFor("test-v1", child.Packs[0].ID, id) + backend.mu.Lock() + backend.objects[key] = bytes.Clone(data) + backend.mu.Unlock() + return parentReference.ID, id + } + t.Fatal("could not construct a child manifest that sorts before its parent") + return "", "" +} + +// dropOriginals removes everything the layout was read from. Packs are content +// addressed, so a rebuild that reproduces one exactly shares its key; the +// caller must not have produced such a pack. +func dropOriginals(t *testing.T, backend *memoryBackend, layout Layout, keep map[string]struct{}) { + t.Helper() + for _, original := range layout.Packs { + if _, protected := keep[original.Key]; protected { + t.Fatalf("the rebuild reproduced pack %s exactly, so the test proves nothing", original.ID) + } + backend.remove(original.Key) + } + for _, reference := range layout.Manifests { + backend.remove(reference.Key) + } +} + +// The layout has to resolve a digest to the same copy a reader is served, or a +// plan built on it would delete the wrong pack. +func TestReadLayoutMatchesWhatAServerResolves(t *testing.T) { + backend := newMemoryBackend() + blobs := [][]byte{[]byte("first output"), []byte("second output")} + seedPacked(t, backend, blobs...) + + layout := readLayout(t, backend) + if len(layout.Packs) != 1 { + t.Fatalf("packs = %+v", layout.Packs) + } + if len(layout.Entries) != len(blobs) { + t.Fatalf("entries = %+v", layout.Entries) + } + if len(layout.Heads) != 1 { + t.Fatalf("heads = %v", layout.Heads) + } + + reader := testPackedServer(t, backend) + defer closePackedServer(t, reader) + for _, entry := range layout.Entries { + if got := reader.packFor(entry.Kind, entry.Digest); got != entry.Pack { + t.Fatalf("layout puts %s in %s, the server reads it from %s", entry.Digest, entry.Pack, got) + } + } +} + +func TestManifestHeadsAreIndependentOfCIDOrdering(t *testing.T) { + backend := newMemoryBackend() + seedPacked(t, backend, []byte("parent manifest output")) + parentID, childID := addChildManifestSortingBeforeParent(t, backend) + if childID >= parentID { + t.Fatalf("child ID %s does not sort before parent ID %s", childID, parentID) + } + + layout := readLayout(t, backend) + if len(layout.Heads) != 1 || layout.Heads[0] != childID { + t.Fatalf("layout heads = %v, want only child %s", layout.Heads, childID) + } + + writer := testPackedServer(t, backend) + writer.packs.mu.Lock() + var discoveredHeads []string + for head := range writer.packs.heads { + discoveredHeads = append(discoveredHeads, head) + } + writer.packs.mu.Unlock() + sort.Strings(discoveredHeads) + if len(discoveredHeads) != 1 || discoveredHeads[0] != childID { + t.Fatalf("discovered heads = %v, want only child %s", discoveredHeads, childID) + } + + next := []byte("next manifest output") + if response := putCacheObject(writer, "/cas/"+digest(next), next); response.Code != http.StatusNoContent { + t.Fatalf("next CAS PUT = %d", response.Code) + } + closePackedServer(t, writer) + + backend.mu.Lock() + var committed manifest + foundCommitted := false + for key, data := range backend.objects { + _, id, ok := parseManifestKey("test-v1", key) + if !ok || id == parentID || id == childID { + continue + } + value, decodeErr := decodeManifest(data, id) + if decodeErr != nil { + backend.mu.Unlock() + t.Fatal(decodeErr) + } + committed = value + foundCommitted = true + break + } + backend.mu.Unlock() + if !foundCommitted { + t.Fatal("close did not publish a new manifest") + } + if len(committed.Parents) != 1 || committed.Parents[0] != childID { + t.Fatalf("new manifest parents = %v, want only child %s", committed.Parents, childID) + } +} + +// The REST listing reports entries this job's cache scope cannot restore, so a +// layout has to be buildable from the part that is visible. +func TestReadLayoutSkipsManifestsItCannotRestore(t *testing.T) { + backend := newMemoryBackend() + blob := []byte("an output this job can see") + seedPacked(t, backend, blob) + + phantomPack := strings.Repeat("f", 64) + // A real manifest ID, so the key parses and the load is what fails. + realManifest := readLayout(t, backend).Manifests[0].ID + phantomManifest := manifestKeyFor("test-v1", phantomPack, realManifest) + layout, err := ReadLayout(context.Background(), LayoutOptions{ + Backend: backend, + Catalog: phantomCatalog{ + memoryCatalog{backend: backend}, + []string{packKeyFor("test-v1", phantomPack), phantomManifest}, + }, + KeyPrefix: "test-v1", + MaxBlobSize: 1 << 20, + Timeout: 5 * time.Second, + Warn: func(string, ...any) {}, + }) + if err != nil { + t.Fatal(err) + } + if layout.UnreadableManifests != 1 { + t.Fatalf("unreadable = %d, want 1", layout.UnreadableManifests) + } + if len(layout.Entries) != 1 || layout.Entries[0].Digest != digest(blob) { + t.Fatalf("entries = %+v", layout.Entries) + } + // The pack behind an unreadable manifest must not become a deletion + // candidate, so it must not appear in the layout at all. + for _, pack := range layout.Packs { + if pack.ID == phantomPack { + t.Fatal("a pack whose manifest could not be read entered the layout") + } + } +} + +// A repacked entry has to be byte-identical and servable from its new pack +// once the original is gone. +func TestRepackerRepublishesEntriesReadably(t *testing.T) { + backend := newMemoryBackend() + blobs := [][]byte{[]byte("output that moves"), []byte("output that also moves")} + // Seeded one per pack, so merging them produces a pack that did not exist. + for _, blob := range blobs { + seedPacked(t, backend, blob) + } + layout := readLayout(t, backend) + if len(layout.Packs) != 2 { + t.Fatalf("packs = %+v, want one per blob", layout.Packs) + } + + repacker, err := NewRepacker(RepackOptions{ + Backend: backend, + CacheDir: t.TempDir(), + KeyPrefix: "test-v1", + MaxBlobSize: 1 << 20, + Timeout: 5 * time.Second, + Parents: layout.Heads, + Packs: layout.Packs, + }) + if err != nil { + t.Fatal(err) + } + defer repacker.Close() + + pack, manifestID, err := repacker.Publish(context.Background(), layout.Entries, time.Time{}) + if err != nil { + t.Fatal(err) + } + if manifestID == "" { + t.Fatal("no manifest was committed") + } + + // Removing the originals is what forces reads through the rebuilt pack; the + // merge prefers the lowest pack ID, so leaving them would prove nothing. + dropOriginals(t, backend, layout, map[string]struct{}{pack.Key: {}}) + + reader := testPackedServer(t, backend) + defer closePackedServer(t, reader) + for _, blob := range blobs { + response := readCacheObject(reader, "/cas/"+digest(blob)) + if response.Code != http.StatusOK { + t.Fatalf("reading %s from the rebuilt pack = %d", digest(blob), response.Code) + } + if response.Body.String() != string(blob) { + t.Fatalf("rebuilt pack served %q, want %q", response.Body.String(), blob) + } + if got := reader.packFor("cas", digest(blob)); got != pack.ID { + t.Fatalf("entry is served from %s, want the rebuilt %s", got, pack.ID) + } + } +} + +// Splitting into several packs must leave every entry readable from exactly the +// pack the plan put it in. +func TestRepackerSplitsEntriesAcrossPacks(t *testing.T) { + backend := newMemoryBackend() + blobs := [][]byte{[]byte("alpha output"), []byte("beta output"), []byte("gamma output")} + seedPacked(t, backend, blobs...) + layout := readLayout(t, backend) + + repacker, err := NewRepacker(RepackOptions{ + Backend: backend, + CacheDir: t.TempDir(), + KeyPrefix: "test-v1", + MaxBlobSize: 1 << 20, + Timeout: 5 * time.Second, + Parents: layout.Heads, + Packs: layout.Packs, + }) + if err != nil { + t.Fatal(err) + } + defer repacker.Close() + + placement := make(map[string]string) + keep := make(map[string]struct{}) + for _, entry := range layout.Entries { + pack, _, err := repacker.Publish(context.Background(), []LayoutEntry{entry}, time.Time{}) + if err != nil { + t.Fatal(err) + } + placement[entry.Digest] = pack.ID + keep[pack.Key] = struct{}{} + } + dropOriginals(t, backend, layout, keep) + + reader := testPackedServer(t, backend) + defer closePackedServer(t, reader) + for _, blob := range blobs { + if response := readCacheObject(reader, "/cas/"+digest(blob)); response.Code != http.StatusOK { + t.Fatalf("reading %s = %d", digest(blob), response.Code) + } + if got := reader.packFor("cas", digest(blob)); got != placement[digest(blob)] { + t.Fatalf("%s is served from %s, want %s", digest(blob), got, placement[digest(blob)]) + } + } +} + +// The optimiser passes a spool path that does not exist yet, because it never +// goes through New, which is what creates one for a cache server. +func TestRepackerCreatesItsSpoolDirectory(t *testing.T) { + backend := newMemoryBackend() + blob := []byte("an output to move") + seedPacked(t, backend, blob) + layout := readLayout(t, backend) + + spool := filepath.Join(t.TempDir(), "missing", "spool") + repacker, err := NewRepacker(RepackOptions{ + Backend: backend, + CacheDir: spool, + KeyPrefix: "test-v1", + MaxBlobSize: 1 << 20, + Timeout: 5 * time.Second, + Parents: layout.Heads, + Packs: layout.Packs, + }) + if err != nil { + t.Fatal(err) + } + defer repacker.Close() + + if _, _, err := repacker.Publish(context.Background(), layout.Entries, time.Time{}); err != nil { + t.Fatal(err) + } +} + +func TestRepackerRejectsAMissingSourcePack(t *testing.T) { + backend := newMemoryBackend() + seedPacked(t, backend, []byte("an output")) + layout := readLayout(t, backend) + for _, original := range layout.Packs { + backend.remove(original.Key) + } + + repacker, err := NewRepacker(RepackOptions{ + Backend: backend, + CacheDir: t.TempDir(), + KeyPrefix: "test-v1", + MaxBlobSize: 1 << 20, + Timeout: 5 * time.Second, + Packs: layout.Packs, + }) + if err != nil { + t.Fatal(err) + } + defer repacker.Close() + + if _, _, err := repacker.Publish(context.Background(), layout.Entries, time.Time{}); err == nil { + t.Fatal("published from a pack that is gone") + } +} + +// Concurrent publications that copy out of the same source pack must share one +// download of it, and all stay readable. +func TestRepackerPublishesConcurrentlyFromSharedSources(t *testing.T) { + backend := newMemoryBackend() + blobs := make([][]byte, 0, 8) + for index := range 8 { + blobs = append(blobs, []byte("shared source output "+strconv.Itoa(index))) + } + seedPacked(t, backend, blobs...) + layout := readLayout(t, backend) + if len(layout.Packs) != 1 { + t.Fatalf("seeded %d packs, want one shared source", len(layout.Packs)) + } + + repacker, err := NewRepacker(RepackOptions{ + Backend: backend, + CacheDir: t.TempDir(), + KeyPrefix: "test-v1", + MaxBlobSize: 1 << 20, + Timeout: 5 * time.Second, + Parents: layout.Heads, + Packs: layout.Packs, + }) + if err != nil { + t.Fatal(err) + } + defer repacker.Close() + + backend.mu.Lock() + loadsBefore := backend.loads + backend.mu.Unlock() + keep := make(map[string]struct{}) + var mu sync.Mutex + var wait sync.WaitGroup + errs := make(chan error, len(layout.Entries)) + for _, entry := range layout.Entries { + wait.Add(1) + go func() { + defer wait.Done() + pack, _, err := repacker.Publish(context.Background(), []LayoutEntry{entry}, time.Time{}) + if err != nil { + errs <- err + return + } + mu.Lock() + keep[pack.Key] = struct{}{} + mu.Unlock() + }() + } + wait.Wait() + close(errs) + for err := range errs { + t.Fatal(err) + } + backend.mu.Lock() + loads := backend.loads - loadsBefore + backend.mu.Unlock() + if loads != 1 { + t.Fatalf("the shared source was downloaded %d times", loads) + } + repacker.Release(layout.Packs[0].ID) + dropOriginals(t, backend, layout, keep) + + reader := testPackedServer(t, backend) + defer closePackedServer(t, reader) + for _, blob := range blobs { + if response := readCacheObject(reader, "/cas/"+digest(blob)); response.Code != http.StatusOK { + t.Fatalf("reading %s = %d", digest(blob), response.Code) + } + } +} + +// Reaping needs the manifests whose pack is gone by key, not just a count. +func TestReadLayoutListsManifestsWhosePackIsGone(t *testing.T) { + backend := newMemoryBackend() + seedPacked(t, backend, []byte("evicted output")) + seedPacked(t, backend, []byte("surviving output")) + before := readLayout(t, backend) + if len(before.Packs) != 2 { + t.Fatalf("seeded %d packs, want 2", len(before.Packs)) + } + evicted := before.Packs[0] + backend.remove(evicted.Key) + + after := readLayout(t, backend) + if after.OrphanManifests != 1 || len(after.PacklessManifests) != 1 { + t.Fatalf("orphaned %d, listed %+v", after.OrphanManifests, after.PacklessManifests) + } + if got := after.PacklessManifests[0]; got.Pack != evicted.ID || + !strings.HasPrefix(got.Key, ManifestKeyPrefix("test-v1")) { + t.Fatalf("listed %+v, want the manifest of %s", got, evicted.ID) + } +} + +// Dropping stale entries must not make a pack look newly shaped, or the +// age-gated reshaping would never reach it. The age travels in the manifest. +func TestRepackerCarriesAPackAgeThroughItsManifest(t *testing.T) { + backend := newMemoryBackend() + seedPacked(t, backend, []byte("aged output")) + layout := readLayout(t, backend) + if !layout.Packs[0].Since.IsZero() { + t.Fatalf("a server-written pack recorded since %v", layout.Packs[0].Since) + } + + repacker, err := NewRepacker(RepackOptions{ + Backend: backend, + CacheDir: t.TempDir(), + KeyPrefix: "test-v1", + MaxBlobSize: 1 << 20, + Timeout: 5 * time.Second, + Parents: layout.Heads, + Packs: layout.Packs, + }) + if err != nil { + t.Fatal(err) + } + defer repacker.Close() + since := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC) + if _, _, err := repacker.Publish(context.Background(), layout.Entries, since); err != nil { + t.Fatal(err) + } + // The rebuild of a one-entry pack reproduces its bytes, so only the old + // manifest goes. + for _, reference := range layout.Manifests { + backend.remove(reference.Key) + } + + after := readLayout(t, backend) + if len(after.Packs) != 1 || !after.Packs[0].Since.Equal(since) { + t.Fatalf("packs = %+v, want one shaped at %v", after.Packs, since) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index bb8e321..a9ac6af 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -17,6 +17,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "github.com/cre4ture/bazel-github-actions-cache-v2/internal/cache" @@ -29,29 +30,49 @@ var ( jwtPattern = regexp.MustCompile(`[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}`) ) +// defaultPackRenewInterval batches retention renewals long enough that a pack +// Bazel downloads shortly after a presence check costs no extra API call. +const defaultPackRenewInterval = 15 * time.Second + +// defaultPackCompressionLevel favours flush latency over ratio: blocks are +// compressed once on the upload path, and level 3 already captures most of the +// available saving on cache content. +const defaultPackCompressionLevel = 3 + type Config struct { - Backend cache.Backend - Catalog cache.Catalog - CacheDir string - KeyPrefix string - StorageMode string - PackSize int64 - PackFlushInterval time.Duration - MaxManifests int - WriteEnabled bool - FailOpen bool - MaxBlobSize int64 - MaxConcurrent int - UploadsPerMinute int - BackendTimeout time.Duration - ShutdownToken string - Shutdown func() - Logger *log.Logger + Backend cache.Backend + Catalog cache.Catalog + CacheDir string + KeyPrefix string + PackSize int64 + PackFlushInterval time.Duration + PackRenewInterval time.Duration + PackCompression bool + PackCompressionLevel int64 + MaxManifests int + WriteEnabled bool + FailOpen bool + MaxBlobSize int64 + MaxConcurrent int + UploadsPerMinute int + BackendTimeout time.Duration + ShutdownToken string + Shutdown func() + Logger *log.Logger + // AssetClient fetches remote assets from their origin. A nil client gets a + // default that refuses to be redirected off HTTPS. + AssetClient *http.Client + // AssetHeaderRoutes are the URI patterns whose credentials may be forwarded + // to an origin. Empty refuses every one of them, so an authenticated asset + // is left to Bazel rather than cached where the whole repository reads it. + AssetHeaderRoutes []string } type object struct { - path string - size int64 + path string + data []byte + inMemory bool + size int64 } type publication struct { @@ -62,14 +83,18 @@ type publication struct { type Server struct { cfg Config stats counters + objectFilesMu sync.RWMutex objectsMu sync.RWMutex objects map[string]object publicationsMu sync.Mutex published map[string]struct{} publishing map[string]*publication sem chan struct{} + fileIO *ioGate limiter *intervalLimiter packs *packStore + usage *usageRecorder + assetRoutes []assetRoute } func New(cfg Config) (*Server, error) { @@ -94,63 +119,109 @@ func New(cfg Config) (*Server, error) { if cfg.BackendTimeout <= 0 { return nil, errors.New("backend timeout must be positive") } - if cfg.StorageMode == "" { - cfg.StorageMode = "objects" + if cfg.Catalog == nil { + return nil, errors.New("manifest catalog is required") } - if cfg.StorageMode != "objects" && cfg.StorageMode != "packs" { - return nil, errors.New("storage mode must be objects or packs") + if cfg.PackSize <= 0 || cfg.PackSize > 32*1024*1024 { + return nil, errors.New("pack size must be between 1 byte and 32 MiB") } - if cfg.StorageMode == "packs" { - if cfg.Catalog == nil { - return nil, errors.New("packed storage mode requires a manifest catalog") - } - if cfg.PackSize <= 0 || cfg.PackSize > 32*1024*1024 { - return nil, errors.New("pack size must be between 1 byte and 32 MiB") - } - if cfg.PackFlushInterval <= 0 { - return nil, errors.New("pack flush interval must be positive") - } - if cfg.MaxManifests <= 0 { - return nil, errors.New("maximum manifests must be positive") - } + if cfg.PackFlushInterval <= 0 { + return nil, errors.New("pack flush interval must be positive") + } + if cfg.PackRenewInterval <= 0 { + cfg.PackRenewInterval = defaultPackRenewInterval + } + if cfg.PackCompressionLevel == 0 { + cfg.PackCompressionLevel = defaultPackCompressionLevel + } + if cfg.PackCompressionLevel < 1 || cfg.PackCompressionLevel > 19 { + return nil, errors.New("pack compression level must be between 1 and 19") + } + if cfg.MaxManifests <= 0 { + return nil, errors.New("maximum manifests must be positive") } if cfg.Logger == nil { cfg.Logger = log.New(io.Discard, "", 0) } + if cfg.AssetClient == nil { + cfg.AssetClient = defaultAssetClient() + } + assetRoutes, err := ParseAssetRoutes(cfg.AssetHeaderRoutes) + if err != nil { + return nil, err + } if err := os.MkdirAll(cfg.CacheDir, 0o700); err != nil { return nil, fmt.Errorf("create cache directory: %w", err) } server := &Server{ - cfg: cfg, - objects: make(map[string]object), - published: make(map[string]struct{}), - publishing: make(map[string]*publication), - sem: make(chan struct{}, cfg.MaxConcurrent), - limiter: newIntervalLimiter(cfg.UploadsPerMinute), - } - if cfg.StorageMode == "packs" { - packs, err := newPackStore(server) - if err != nil { - return nil, err - } - server.packs = packs + cfg: cfg, + objects: make(map[string]object), + published: make(map[string]struct{}), + publishing: make(map[string]*publication), + sem: make(chan struct{}, cfg.MaxConcurrent), + fileIO: newIOGate(maxConcurrentFileIO), + limiter: newIntervalLimiter(cfg.UploadsPerMinute), + usage: newUsageRecorder(), + assetRoutes: assetRoutes, + } + server.cfg.Backend = &countingBackend{ + backend: cfg.Backend, + counter: &server.stats.backendRequests, + } + packs, err := newPackStore(server) + if err != nil { + return nil, err } + server.packs = packs return server, nil } +// countingBackend records every call into the GitHub Actions cache. Counting at +// this boundary rather than at each call site keeps the total honest: closure +// validation, packed reads, and retries all reach the API without a matching +// client request. +type countingBackend struct { + backend cache.Backend + counter *atomic.Uint64 +} + +func (b *countingBackend) Exists(ctx context.Context, key string) (bool, error) { + b.counter.Add(1) + return b.backend.Exists(ctx, key) +} + +func (b *countingBackend) Load(ctx context.Context, key string, dst io.Writer) (bool, error) { + b.counter.Add(1) + return b.backend.Load(ctx, key, dst) +} + +func (b *countingBackend) Save(ctx context.Context, key string, src *os.File, size int64) error { + b.counter.Add(1) + return b.backend.Save(ctx, key, src, size) +} + func (s *Server) Handler() http.Handler { return http.HandlerFunc(s.serveHTTP) } func (s *Server) Snapshot() Stats { - return s.stats.snapshot() + stats := s.stats.snapshot() + // Restored against used is the ratio that says whether packs are placing + // frequently and rarely fetched content together. + report := s.usage.report() + stats.PackBytesRestored = uint64(report.PackBytesRestored) + stats.PackBytesDeclared = uint64(report.PackBytesDeclared) + stats.PackBytesUsed = uint64(report.PackBytesUsed) + return stats +} + +// Usage reports which entries this job touched and how. +func (s *Server) Usage() UsageReport { + return s.usage.report() } // Close commits every pending CARv2 batch before the action process exits. func (s *Server) Close(ctx context.Context) error { - if s.packs == nil { - return nil - } return s.packs.close(ctx) } @@ -174,13 +245,7 @@ func (s *Server) serveHTTP(w http.ResponseWriter, r *http.Request) { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } - body := s.Snapshot().JSON() - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Content-Length", strconv.Itoa(len(body))) - w.WriteHeader(http.StatusOK) - if r.Method == http.MethodGet { - _, _ = w.Write(body) - } + s.serveJSON(w, r, s.Snapshot().JSON()) return case "/shutdown": s.handleShutdown(w, r) @@ -197,26 +262,56 @@ func (s *Server) serveHTTP(w http.ResponseWriter, r *http.Request) { s.handleImplicitEmptyCASRead(w, r) return } - key := s.cfg.KeyPrefix + "-" + kind + "-" + digest switch r.Method { - case http.MethodHead, http.MethodGet: - s.handleRead(w, r, key, kind, digest) + case http.MethodHead: + s.handleHead(w, r, kind, digest) + case http.MethodGet: + s.handleRead(w, r, kind, digest) case http.MethodPut: - s.handlePut(w, r, key, kind, digest) + s.handlePut(w, r, kind, digest) default: w.Header().Set("Allow", "GET, HEAD, PUT") s.reject(w, "method not allowed", http.StatusMethodNotAllowed) } } +// handleHead answers a packed CAS presence check from the manifest view. Bazel +// issues these while building without the bytes, so restoring a whole pack to +// answer one would defeat the point. +func (s *Server) handleHead(w http.ResponseWriter, r *http.Request, kind, digest string) { + if kind != "cas" { + s.handleRead(w, r, kind, digest) + return + } + size, err := s.casPresence(r.Context(), digest) + if err != nil { + http.NotFound(w, r) + return + } + s.writeObjectHeader(w, size) +} + func (s *Server) handleImplicitEmptyCASRead(w http.ResponseWriter, r *http.Request) { - s.stats.hits.Add(1) + s.implicitEmptyCASHit() + s.writeObjectHeader(w, 0) +} + +func (s *Server) writeObjectHeader(w http.ResponseWriter, size int64) { w.Header().Set("Content-Type", "application/octet-stream") - w.Header().Set("Content-Length", "0") + w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) w.Header().Set("Cache-Control", "private, max-age=31536000, immutable") w.WriteHeader(http.StatusOK) } +func (s *Server) serveJSON(w http.ResponseWriter, r *http.Request, body []byte) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Length", strconv.Itoa(len(body))) + w.WriteHeader(http.StatusOK) + if r.Method == http.MethodGet { + _, _ = w.Write(body) + } +} + func (s *Server) handleShutdown(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { w.Header().Set("Allow", "POST") @@ -250,71 +345,15 @@ func parseObjectPath(path string) (kind, digest string, ok bool) { return parts[0], parts[1], true } -func (s *Server) handleRead(w http.ResponseWriter, r *http.Request, key, kind, digest string) { - obj, found, err := s.resolve(r.Context(), key, kind, digest) - if err != nil { - s.stats.backendLoadErrors.Add(1) - s.cfg.Logger.Printf("backend load failed for %s/%s: %s", kind, digest, safeError(err)) - if s.cfg.FailOpen { - s.stats.misses.Add(1) - http.NotFound(w, r) - } else { - http.Error(w, "cache backend unavailable", http.StatusBadGateway) - } - return - } - if !found { - s.stats.misses.Add(1) - http.NotFound(w, r) - return - } - if kind == "ac" { - if err := s.validateActionResult(r.Context(), obj); err != nil { - switch { - case errors.Is(err, errIncompleteActionResult): - s.stats.incompleteActionResults.Add(1) - s.stats.misses.Add(1) - s.cfg.Logger.Printf("action result ac/%s is incomplete: %s", digest, safeError(err)) - http.NotFound(w, r) - case errors.Is(err, errInvalidActionResult): - s.stats.invalidActionResults.Add(1) - s.stats.misses.Add(1) - s.cfg.Logger.Printf("action result ac/%s is invalid: %s", digest, safeError(err)) - http.NotFound(w, r) - default: - s.stats.backendLoadErrors.Add(1) - s.cfg.Logger.Printf("action result ac/%s validation failed: %s", digest, safeError(err)) - if s.cfg.FailOpen { - s.stats.misses.Add(1) - http.NotFound(w, r) - } else { - http.Error(w, "cache backend unavailable", http.StatusBadGateway) - } - } - return - } - s.stats.validatedActionResults.Add(1) - } - - file, err := os.Open(obj.path) +func (s *Server) handleRead(w http.ResponseWriter, r *http.Request, kind, digest string) { + file, size, err := s.openObject(r.Context(), kind, digest) if err != nil { - s.stats.backendLoadErrors.Add(1) - s.cfg.Logger.Printf("open local cache object %s/%s: %v", kind, digest, err) - if s.cfg.FailOpen { - s.stats.misses.Add(1) - http.NotFound(w, r) - } else { - http.Error(w, "local cache unavailable", http.StatusInternalServerError) - } + s.failRequest(w, r, err) return } defer file.Close() - s.stats.hits.Add(1) - w.Header().Set("Content-Type", "application/octet-stream") - w.Header().Set("Content-Length", strconv.FormatInt(obj.size, 10)) - w.Header().Set("Cache-Control", "private, max-age=31536000, immutable") - w.WriteHeader(http.StatusOK) + s.writeObjectHeader(w, size) if r.Method == http.MethodHead { return } @@ -325,97 +364,60 @@ func (s *Server) handleRead(w http.ResponseWriter, r *http.Request, key, kind, d } } -func (s *Server) resolve(ctx context.Context, key, kind, digest string) (object, bool, error) { - s.objectsMu.RLock() - obj, ok := s.objects[key] - s.objectsMu.RUnlock() - if ok { - return obj, true, nil - } - if s.packs != nil { - return s.packs.resolve(ctx, key, kind, digest) +func (s *Server) failRequest(w http.ResponseWriter, r *http.Request, err error) { + switch { + case errors.Is(err, errCacheMiss): + http.NotFound(w, r) + case errors.Is(err, errLocalFailure): + http.Error(w, "local cache unavailable", http.StatusInternalServerError) + default: + http.Error(w, "cache backend unavailable", http.StatusBadGateway) } +} - if err := s.acquire(ctx); err != nil { - return object{}, false, err +func (s *Server) resolve(ctx context.Context, key, kind, digest string) (object, bool, error) { + value, found, err := s.resolveObject(ctx, key, kind, digest) + if found && err == nil { + s.usage.record(kind, digest, s.packFor(kind, digest), accessDownload, value.size) } - defer s.release() + return value, found, err +} - // Re-check after waiting for another backend operation. +func (s *Server) resolveObject(ctx context.Context, key, kind, digest string) (object, bool, error) { s.objectsMu.RLock() - obj, ok = s.objects[key] + obj, ok := s.objects[key] s.objectsMu.RUnlock() if ok { return obj, true, nil } - - file, err := os.CreateTemp(s.cfg.CacheDir, "download-*") - if err != nil { - return object{}, false, fmt.Errorf("create download spool: %w", err) - } - path := file.Name() - keep := false - defer func() { - _ = file.Close() - if !keep { - _ = os.Remove(path) - } - }() - - limited := &maxWriter{writer: file, remaining: s.cfg.MaxBlobSize} - backendCtx, cancel := context.WithTimeout(ctx, s.cfg.BackendTimeout) - defer cancel() - found, err := s.cfg.Backend.Load(backendCtx, key, limited) - if err != nil { - return object{}, false, err - } - if !found { - return object{}, false, nil - } - s.stats.backendDownloads.Add(1) - if err := file.Sync(); err != nil { - return object{}, false, fmt.Errorf("sync download spool: %w", err) - } - info, err := file.Stat() - if err != nil { - return object{}, false, fmt.Errorf("stat download spool: %w", err) - } - if kind == "cas" { - actual, err := hashFile(file) - if err != nil { - return object{}, false, err - } - if actual != digest { - return object{}, false, fmt.Errorf("CAS integrity check failed: expected %s, got %s", digest, actual) - } - } - obj = object{path: path, size: info.Size()} - s.objectsMu.Lock() - if existing, exists := s.objects[key]; exists { - obj = existing - } else { - s.objects[key] = obj - keep = true - } - s.objectsMu.Unlock() - return obj, true, nil + return s.packs.resolve(ctx, key, kind, digest) } -func (s *Server) exists(ctx context.Context, key string) (bool, error) { +// presence reports whether a CAS object can be served and its recorded size +// from the manifest view, without restoring its pack. +func (s *Server) presence(ctx context.Context, kind, digest string) (int64, bool, error) { + key := s.objectKey(kind, digest) s.objectsMu.RLock() - _, ok := s.objects[key] + object, ok := s.objects[key] s.objectsMu.RUnlock() if ok { - return true, nil + s.usage.record(kind, digest, s.packFor(kind, digest), accessPresence, object.size) + return object.size, true, nil } - if s.packs != nil { - prefix := s.cfg.KeyPrefix + "-cas-" - if !strings.HasPrefix(key, prefix) || len(key) != len(prefix)+64 { - return false, errors.New("packed storage can only resolve CAS keys") - } - return s.packs.exists(ctx, key[len(prefix):]) + if kind != "cas" { + return 0, false, errors.New("packed storage can only resolve CAS keys") + } + size, found := s.packs.presence(digest) + if found { + s.usage.record(kind, digest, s.packFor(kind, digest), accessPresence, size) } - return s.backendExists(ctx, key) + return size, found, nil +} + +// packFor names the pack serving an entry, which is what lets a later +// optimisation pass map usage onto cache layout. +func (s *Server) packFor(kind, digest string) string { + return s.packs.packFor(kind, digest) } func (s *Server) backendExists(ctx context.Context, key string) (bool, error) { @@ -430,7 +432,7 @@ func (s *Server) backendExists(ctx context.Context, key string) (bool, error) { return s.cfg.Backend.Exists(backendCtx, key) } -func (s *Server) handlePut(w http.ResponseWriter, r *http.Request, key, kind, digest string) { +func (s *Server) handlePut(w http.ResponseWriter, r *http.Request, kind, digest string) { if encoding := r.Header.Get("Content-Encoding"); encoding != "" && !strings.EqualFold(encoding, "identity") { s.reject(w, "content encoding is unsupported", http.StatusUnsupportedMediaType) return @@ -444,141 +446,17 @@ func (s *Server) handlePut(w http.ResponseWriter, r *http.Request, key, kind, di return } - file, err := os.CreateTemp(s.cfg.CacheDir, "upload-*") - if err != nil { - http.Error(w, "cannot create upload spool", http.StatusInternalServerError) - return - } - path := file.Name() - keep := false - defer func() { - _ = file.Close() - if !keep { - _ = os.Remove(path) - } - }() - - hasher := sha256.New() - writer := io.Writer(file) - if kind == "cas" { - writer = io.MultiWriter(file, hasher) - } - n, err := io.Copy(writer, io.LimitReader(r.Body, r.ContentLength+1)) - s.stats.bytesReceived.Add(uint64(n)) - if err != nil { - s.reject(w, "failed to read request body", http.StatusBadRequest) - return - } - if n != r.ContentLength { - s.reject(w, "body size does not match Content-Length", http.StatusBadRequest) - return - } - if kind == "cas" { - actual := hex.EncodeToString(hasher.Sum(nil)) - if actual != digest { - s.reject(w, "CAS digest does not match request body", http.StatusUnprocessableEntity) - return - } - } - if err := file.Sync(); err != nil { - http.Error(w, "cannot sync upload spool", http.StatusInternalServerError) - return - } - - s.objectsMu.Lock() - stored, exists := s.objects[key] - if !exists { - stored = object{path: path, size: n} - s.objects[key] = stored - keep = true - } - s.objectsMu.Unlock() - - if !s.cfg.WriteEnabled { - s.stats.discardedUploads.Add(1) - w.WriteHeader(http.StatusNoContent) - return - } - if s.packs != nil { - if kind == "cas" { - s.packs.stageCAS(digest, stored) - } else { - closure, err := s.collectActionResultClosure(r.Context(), stored) - if err != nil { - s.handlePackedActionValidationError(w, digest, err) - return - } - if err := s.packs.stageAction(digest, stored, closure); err != nil { - s.handleSaveError(w, kind, digest, err) - return - } - s.stats.validatedActionResults.Add(1) - } - w.WriteHeader(http.StatusNoContent) - return - } - if kind == "ac" { - if err := s.validateActionResultForPublication(r.Context(), object{path: path, size: n}); err != nil { - switch { - case errors.Is(err, errIncompleteActionResult): - s.stats.incompleteActionResults.Add(1) - s.stats.skippedActionResultUploads.Add(1) - s.cfg.Logger.Printf("not publishing incomplete action result ac/%s: %s", digest, safeError(err)) - w.WriteHeader(http.StatusNoContent) - case errors.Is(err, errInvalidActionResult): - s.stats.invalidActionResults.Add(1) - s.stats.skippedActionResultUploads.Add(1) - s.cfg.Logger.Printf("not publishing invalid action result ac/%s: %s", digest, safeError(err)) - w.WriteHeader(http.StatusNoContent) - default: - s.stats.backendLoadErrors.Add(1) - s.cfg.Logger.Printf("action result ac/%s publication validation failed: %s", digest, safeError(err)) - if s.cfg.FailOpen { - s.stats.skippedActionResultUploads.Add(1) - w.WriteHeader(http.StatusNoContent) - } else { - http.Error(w, "cache backend unavailable", http.StatusBadGateway) - } - } - return - } - s.stats.validatedActionResults.Add(1) - } - - deduplicated, err := s.publishOnce(r.Context(), key, file, n) - if err != nil { - s.handleSaveError(w, kind, digest, err) - return - } - if deduplicated { - s.stats.deduplicatedUploads.Add(1) - } else { - s.stats.uploads.Add(1) - } - w.WriteHeader(http.StatusNoContent) -} - -func (s *Server) handlePackedActionValidationError(w http.ResponseWriter, digest string, err error) { - switch { - case errors.Is(err, errIncompleteActionResult): - s.stats.incompleteActionResults.Add(1) - s.stats.skippedActionResultUploads.Add(1) - s.cfg.Logger.Printf("not staging incomplete action result ac/%s: %s", digest, safeError(err)) - w.WriteHeader(http.StatusNoContent) - case errors.Is(err, errInvalidActionResult): - s.stats.invalidActionResults.Add(1) - s.stats.skippedActionResultUploads.Add(1) - s.cfg.Logger.Printf("not staging invalid action result ac/%s: %s", digest, safeError(err)) + switch err := s.writeObject(r.Context(), kind, digest, r.Body, r.ContentLength); { + case err == nil: w.WriteHeader(http.StatusNoContent) + case errors.Is(err, errPayloadTruncated): + s.reject(w, "body size does not match Content-Length", http.StatusBadRequest) + case errors.Is(err, errPayloadMismatch): + s.reject(w, "CAS digest does not match request body", http.StatusUnprocessableEntity) + case errors.Is(err, errLocalFailure): + http.Error(w, "cannot spool upload", http.StatusInternalServerError) default: - s.stats.backendLoadErrors.Add(1) - s.cfg.Logger.Printf("packed action result ac/%s validation failed: %s", digest, safeError(err)) - if s.cfg.FailOpen { - s.stats.skippedActionResultUploads.Add(1) - w.WriteHeader(http.StatusNoContent) - } else { - http.Error(w, "cache backend unavailable", http.StatusBadGateway) - } + http.Error(w, "cache backend unavailable", http.StatusBadGateway) } } @@ -628,15 +506,33 @@ func (s *Server) publishOnce(ctx context.Context, key string, file *os.File, siz } func (s *Server) publish(ctx context.Context, key string, file *os.File, size int64) error { - if err := s.acquire(ctx); err != nil { - return err + waited := false + for { + if err := s.acquire(ctx); err != nil { + return err + } + if err := ctx.Err(); err != nil { + s.release() + return err + } + delay := s.limiter.claimStart() + if delay <= 0 { + break + } + s.release() + waited = true + timer := time.NewTimer(delay) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } } - defer s.release() - if waited, err := s.limiter.wait(ctx); err != nil { - return err - } else if waited { + if waited { s.stats.throttleWaits.Add(1) } + defer s.release() if _, err := file.Seek(0, io.SeekStart); err != nil { return err @@ -646,16 +542,6 @@ func (s *Server) publish(ctx context.Context, key string, file *os.File, size in return s.cfg.Backend.Save(backendCtx, key, file, size) } -func (s *Server) handleSaveError(w http.ResponseWriter, kind, digest string, err error) { - s.stats.backendSaveErrors.Add(1) - s.cfg.Logger.Printf("backend save failed for %s/%s: %s", kind, digest, safeError(err)) - if s.cfg.FailOpen { - w.WriteHeader(http.StatusNoContent) - return - } - http.Error(w, "cache backend unavailable", http.StatusBadGateway) -} - func (s *Server) reject(w http.ResponseWriter, message string, status int) { s.stats.rejectedRequests.Add(1) http.Error(w, message, status) diff --git a/internal/server/server_test.go b/internal/server/server_test.go index 6ef1a16..bb1b5eb 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -20,12 +20,14 @@ import ( ) type memoryBackend struct { - mu sync.Mutex - objects map[string][]byte - loadErr error - existsErr error - saveErr error - saves int + mu sync.Mutex + objects map[string][]byte + loadErr error + existsErr error + saveErr error + saves int + loads int + existsCalls int } type blockingSaveBackend struct { @@ -52,6 +54,7 @@ func newMemoryBackend() *memoryBackend { func (b *memoryBackend) Load(_ context.Context, key string, dst io.Writer) (bool, error) { b.mu.Lock() defer b.mu.Unlock() + b.loads++ if b.loadErr != nil { return false, b.loadErr } @@ -63,9 +66,16 @@ func (b *memoryBackend) Load(_ context.Context, key string, dst io.Writer) (bool return true, err } +func (b *memoryBackend) loadCount() int { + b.mu.Lock() + defer b.mu.Unlock() + return b.loads +} + func (b *memoryBackend) Exists(_ context.Context, key string) (bool, error) { b.mu.Lock() defer b.mu.Unlock() + b.existsCalls++ if b.existsErr != nil { return false, b.existsErr } @@ -73,6 +83,18 @@ func (b *memoryBackend) Exists(_ context.Context, key string) (bool, error) { return ok, nil } +func (b *memoryBackend) existsCount() int { + b.mu.Lock() + defer b.mu.Unlock() + return b.existsCalls +} + +func (b *memoryBackend) remove(key string) { + b.mu.Lock() + defer b.mu.Unlock() + delete(b.objects, key) +} + func (b *memoryBackend) Save(_ context.Context, key string, src *os.File, size int64) error { b.mu.Lock() defer b.mu.Unlock() @@ -90,17 +112,30 @@ func (b *memoryBackend) Save(_ context.Context, key string, src *os.File, size i func testServer(t *testing.T, backend cache.Backend, mutate func(*Config)) *Server { t.Helper() + var catalogBackend *memoryBackend + switch backend := backend.(type) { + case *memoryBackend: + catalogBackend = backend + case *blockingSaveBackend: + catalogBackend = backend.memoryBackend + default: + t.Fatalf("test backend %T does not support cache catalog listing", backend) + } cfg := Config{ - Backend: backend, - CacheDir: t.TempDir(), - KeyPrefix: "test-v1", - WriteEnabled: true, - FailOpen: true, - MaxBlobSize: 1024, - MaxConcurrent: 2, - UploadsPerMinute: 199, - BackendTimeout: time.Second, - Logger: log.New(io.Discard, "", 0), + Backend: backend, + Catalog: memoryCatalog{backend: catalogBackend}, + CacheDir: t.TempDir(), + KeyPrefix: "test-v1", + PackSize: 1024, + PackFlushInterval: time.Hour, + MaxManifests: 100, + WriteEnabled: true, + FailOpen: true, + MaxBlobSize: 1024, + MaxConcurrent: 2, + UploadsPerMinute: 199, + BackendTimeout: time.Second, + Logger: log.New(io.Discard, "", 0), } if mutate != nil { mutate(&cfg) @@ -109,6 +144,14 @@ func testServer(t *testing.T, backend cache.Backend, mutate func(*Config)) *Serv if err != nil { t.Fatal(err) } + catalogBackend.mu.Lock() + for key, data := range catalogBackend.objects { + if strings.HasPrefix(key, cfg.KeyPrefix+"-cas-") || strings.HasPrefix(key, cfg.KeyPrefix+"-ac-") { + server.objects[key] = object{data: bytes.Clone(data), inMemory: true, size: int64(len(data))} + } + } + catalogBackend.mu.Unlock() + t.Cleanup(func() { closePackedServer(t, server) }) return server } @@ -147,12 +190,44 @@ func TestCASPutHeadGet(t *testing.T) { t.Fatalf("GET status/body = %d/%q", response.Code, response.Body.String()) } stats := server.Snapshot() - if stats.Uploads != 1 || stats.Hits != 2 || stats.BytesServed != uint64(len(data)) { + if stats.Uploads != 0 || stats.Hits != 2 || stats.BytesServed != uint64(len(data)) { t.Fatalf("unexpected stats: %+v", stats) } + if err := server.packs.flush(t.Context(), true); err != nil { + t.Fatal(err) + } + stats = server.Snapshot() + if stats.PackUploads != 1 || stats.ManifestUploads != 1 || stats.Uploads != 2 { + t.Fatalf("cache object was not published as one pack and manifest: %+v", stats) + } } -func TestDuplicateCASPutsArePublishedOnlyOnce(t *testing.T) { +func TestMissBreakdownAccountsForEveryMiss(t *testing.T) { + server := testServer(t, newMemoryBackend(), nil) + for _, path := range []string{ + "/cas/" + digest([]byte("absent blob")), + "/ac/" + digest([]byte("absent action")), + } { + response := httptest.NewRecorder() + server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil)) + if response.Code != http.StatusNotFound { + t.Fatalf("GET %s status = %d", path, response.Code) + } + } + + stats := server.Snapshot() + if stats.MissesCAS != 1 || stats.MissesAC != 1 { + t.Fatalf("misses were not attributed by kind: %+v", stats) + } + // The breakdown is only useful if it explains the headline number. + total := stats.MissesAC + stats.MissesCAS + stats.MissesPresence + + stats.MissesRejected + stats.MissesDegraded + if total != stats.Misses { + t.Fatalf("breakdown sums to %d, but misses = %d", total, stats.Misses) + } +} + +func TestDuplicateCASPutsArePackedOnce(t *testing.T) { backend := newMemoryBackend() server := testServer(t, backend, nil) data := []byte("duplicate output") @@ -164,18 +239,22 @@ func TestDuplicateCASPutsArePublishedOnlyOnce(t *testing.T) { t.Fatalf("status = %d, body = %s", response.Code, response.Body) } } - stats := server.Snapshot() - if backend.saves != 1 || stats.Uploads != 1 || stats.DeduplicatedUploads != 1 { - t.Fatalf("duplicate PUT reached backend: saves=%d stats=%+v", backend.saves, stats) + server.packs.mu.Lock() + pending := len(server.packs.pendingCAS) + server.packs.mu.Unlock() + if pending != 1 { + t.Fatalf("pending CAS objects = %d, want one", pending) + } + if err := server.packs.flush(t.Context(), true); err != nil { + t.Fatal(err) + } + if stats := server.Snapshot(); stats.PackUploads != 1 || stats.ManifestUploads != 1 { + t.Fatalf("duplicate PUT created more than one packed entry: %+v", stats) } } -func TestConcurrentDuplicateCASPutsShareOnePublication(t *testing.T) { - backend := &blockingSaveBackend{ - memoryBackend: newMemoryBackend(), - started: make(chan struct{}), - release: make(chan struct{}), - } +func TestConcurrentDuplicateCASPutsArePackedOnce(t *testing.T) { + backend := newMemoryBackend() server := testServer(t, backend, nil) data := []byte("concurrent duplicate output") path := "/cas/" + digest(data) @@ -185,9 +264,7 @@ func TestConcurrentDuplicateCASPutsShareOnePublication(t *testing.T) { responses <- putCacheObject(server, path, data) } go put() - <-backend.started go put() - close(backend.release) for range 2 { response := <-responses @@ -195,9 +272,11 @@ func TestConcurrentDuplicateCASPutsShareOnePublication(t *testing.T) { t.Fatalf("status = %d, body = %s", response.Code, response.Body) } } - stats := server.Snapshot() - if backend.saves != 1 || stats.Uploads != 1 || stats.DeduplicatedUploads != 1 { - t.Fatalf("concurrent PUTs were not coalesced: saves=%d stats=%+v", backend.saves, stats) + server.packs.mu.Lock() + pending := len(server.packs.pendingCAS) + server.packs.mu.Unlock() + if pending != 1 { + t.Fatalf("pending CAS objects = %d, want one", pending) } } @@ -274,7 +353,6 @@ func TestReadOnlyValidatesAndDiscardsBackendUpload(t *testing.T) { func TestFailOpenBackendErrors(t *testing.T) { backend := newMemoryBackend() - backend.loadErr = errors.New("unavailable") server := testServer(t, backend, nil) request := httptest.NewRequest(http.MethodGet, "/ac/"+strings.Repeat("a", 64), nil) response := httptest.NewRecorder() @@ -283,7 +361,6 @@ func TestFailOpenBackendErrors(t *testing.T) { t.Fatalf("status = %d, want 404", response.Code) } - backend.loadErr = nil backend.saveErr = errors.New("unavailable") data := []byte("result") request = httptest.NewRequest(http.MethodPut, "/cas/"+digest(data), bytes.NewReader(data)) @@ -292,29 +369,35 @@ func TestFailOpenBackendErrors(t *testing.T) { if response.Code != http.StatusNoContent { t.Fatalf("status = %d, want soft-success", response.Code) } + if err := server.packs.flush(t.Context(), true); err == nil { + t.Fatal("packed backend failure was not surfaced by flush") + } if server.Snapshot().BackendSaveErrors != 1 { t.Fatalf("backend save failure was not counted: %+v", server.Snapshot()) } + backend.saveErr = nil } func TestStrictBackendErrors(t *testing.T) { backend := newMemoryBackend() - backend.loadErr = errors.New("unavailable") + writer := testServer(t, backend, nil) + data := []byte("strict backend failure") + if response := putCacheObject(writer, "/cas/"+digest(data), data); response.Code != http.StatusNoContent { + t.Fatalf("seed PUT = %d", response.Code) + } + closePackedServer(t, writer) server := testServer(t, backend, func(cfg *Config) { cfg.FailOpen = false }) - request := httptest.NewRequest(http.MethodGet, "/ac/"+strings.Repeat("a", 64), nil) - response := httptest.NewRecorder() - server.Handler().ServeHTTP(response, request) + backend.loadErr = errors.New("unavailable") + response := readCacheObject(server, "/cas/"+digest(data)) if response.Code != http.StatusBadGateway { t.Fatalf("status = %d, want 502", response.Code) } } -func TestCorruptCASBackendIsMiss(t *testing.T) { +func TestUnknownCASDigestIsMiss(t *testing.T) { backend := newMemoryBackend() - key := "test-v1-cas-" + strings.Repeat("a", 64) - backend.objects[key] = []byte("corrupt") server := testServer(t, backend, nil) request := httptest.NewRequest(http.MethodGet, "/cas/"+strings.Repeat("a", 64), nil) response := httptest.NewRecorder() @@ -322,25 +405,27 @@ func TestCorruptCASBackendIsMiss(t *testing.T) { if response.Code != http.StatusNotFound { t.Fatalf("status = %d, want 404", response.Code) } - if server.Snapshot().BackendLoadErrors != 1 { - t.Fatalf("integrity failure was not counted") + if server.Snapshot().MissesCAS != 1 { + t.Fatalf("unknown digest was not counted as a cache miss: %+v", server.Snapshot()) } } -func TestBackendDownloadIsMeasured(t *testing.T) { +func TestPackedDownloadIsMeasured(t *testing.T) { backend := newMemoryBackend() data := []byte("persisted") hash := digest(data) - backend.objects["test-v1-cas-"+hash] = data + seed := testServer(t, backend, nil) + if response := putCacheObject(seed, "/cas/"+hash, data); response.Code != http.StatusNoContent { + t.Fatalf("seed PUT = %d", response.Code) + } + closePackedServer(t, seed) server := testServer(t, backend, nil) - request := httptest.NewRequest(http.MethodGet, "/cas/"+hash, nil) - response := httptest.NewRecorder() - server.Handler().ServeHTTP(response, request) + response := readCacheObject(server, "/cas/"+hash) if response.Code != http.StatusOK || response.Body.String() != string(data) { t.Fatalf("status/body = %d/%q", response.Code, response.Body.String()) } - if server.Snapshot().BackendDownloads != 1 { - t.Fatalf("backend download was not counted: %+v", server.Snapshot()) + if server.Snapshot().PackDownloads != 1 { + t.Fatalf("packed download was not counted: %+v", server.Snapshot()) } } @@ -387,16 +472,97 @@ func TestNewRejectsUnsafeConfiguration(t *testing.T) { } } +func TestNewRequiresManifestCatalog(t *testing.T) { + _, err := New(Config{ + Backend: newMemoryBackend(), + CacheDir: t.TempDir(), + KeyPrefix: "test-v1", + PackSize: 1024, + PackFlushInterval: time.Second, + MaxManifests: 1, + MaxBlobSize: 1024, + MaxConcurrent: 1, + UploadsPerMinute: 1, + BackendTimeout: time.Second, + }) + if err == nil || !strings.Contains(err.Error(), "manifest catalog is required") { + t.Fatalf("New error = %v, want manifest catalog required", err) + } +} + func TestIntervalLimiterHonorsCancellation(t *testing.T) { limiter := newIntervalLimiter(1) if waited, err := limiter.wait(context.Background()); err != nil || waited { t.Fatalf("first wait = %t, %v", waited, err) } + limiter.mu.Lock() + firstStart := limiter.last + limiter.mu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) defer cancel() if waited, err := limiter.wait(ctx); !waited || !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("second wait = %t, %v", waited, err) } + limiter.mu.Lock() + last := limiter.last + limiter.mu.Unlock() + if !last.Equal(firstStart) { + t.Fatalf("cancelled wait changed the last start time: %s, want %s", last, firstStart) + } +} + +func TestIntervalLimiterSpacesActualStarts(t *testing.T) { + limiter := &intervalLimiter{interval: 20 * time.Millisecond} + if delay := limiter.claimStart(); delay != 0 { + t.Fatalf("first start delay = %s, want none", delay) + } + delay := limiter.claimStart() + if delay <= 0 { + t.Fatalf("second start delay = %s, want a positive delay", delay) + } + time.Sleep(delay) + if delay := limiter.claimStart(); delay != 0 { + t.Fatalf("start delay after waiting = %s, want none", delay) + } +} + +func TestThrottledPublishDoesNotHoldBackendSlot(t *testing.T) { + server := testServer(t, newMemoryBackend(), func(cfg *Config) { + cfg.MaxConcurrent = 1 + }) + server.limiter.mu.Lock() + server.limiter.last = time.Now() + server.limiter.mu.Unlock() + + file, err := os.CreateTemp(server.cfg.CacheDir, "test-publish-*") + if err != nil { + t.Fatal(err) + } + defer func() { + _ = file.Close() + _ = os.Remove(file.Name()) + }() + + ctx, cancel := context.WithCancel(context.Background()) + published := make(chan error, 1) + go func() { + published <- server.publish(ctx, "test-key", file, 0) + }() + defer cancel() + + time.Sleep(10 * time.Millisecond) + + readCtx, stopWaiting := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer stopWaiting() + if err := server.acquire(readCtx); err != nil { + t.Fatalf("rate-limited publish occupied the backend slot: %v", err) + } + server.release() + + cancel() + if err := <-published; !errors.Is(err, context.Canceled) { + t.Fatalf("publish error = %v, want context.Canceled", err) + } } func TestSafeErrorRedactsURLsAndTokens(t *testing.T) { diff --git a/internal/server/stats.go b/internal/server/stats.go index b0637fc..df656f4 100644 --- a/internal/server/stats.go +++ b/internal/server/stats.go @@ -7,12 +7,20 @@ import ( // Stats is a point-in-time JSON representation of cache activity. type Stats struct { - Requests uint64 `json:"requests"` - Hits uint64 `json:"hits"` - Misses uint64 `json:"misses"` + Requests uint64 `json:"requests"` + Operations uint64 `json:"operations"` + Hits uint64 `json:"hits"` + Misses uint64 `json:"misses"` + // The four buckets below partition Misses, so they always sum to it. + MissesAC uint64 `json:"misses_ac"` + MissesCAS uint64 `json:"misses_cas"` + MissesPresence uint64 `json:"misses_presence"` + MissesRejected uint64 `json:"misses_rejected"` + MissesDegraded uint64 `json:"misses_degraded"` Uploads uint64 `json:"uploads"` DeduplicatedUploads uint64 `json:"deduplicated_uploads"` DiscardedUploads uint64 `json:"discarded_uploads"` + BackendRequests uint64 `json:"backend_requests"` BackendDownloads uint64 `json:"backend_downloads"` BackendExistenceChecks uint64 `json:"backend_existence_checks"` BackendLoadErrors uint64 `json:"backend_load_errors"` @@ -24,11 +32,26 @@ type Stats struct { SkippedActionResultUploads uint64 `json:"skipped_action_result_uploads"` BytesServed uint64 `json:"bytes_served"` BytesReceived uint64 `json:"bytes_received"` + AssetRequests uint64 `json:"asset_requests"` + AssetHits uint64 `json:"asset_hits"` + AssetDownloads uint64 `json:"asset_downloads"` + AssetRejected uint64 `json:"asset_rejected"` + AssetFetchErrors uint64 `json:"asset_fetch_errors"` ThrottleWaits uint64 `json:"throttle_waits"` PackUploads uint64 `json:"pack_uploads"` ManifestUploads uint64 `json:"manifest_uploads"` PackDownloads uint64 `json:"pack_downloads"` + PackBytesRestored uint64 `json:"pack_bytes_restored"` + PackBytesDeclared uint64 `json:"pack_bytes_declared"` + PackBytesUsed uint64 `json:"pack_bytes_used"` + PackLoadsSkipped uint64 `json:"pack_loads_skipped"` + PackRenewals uint64 `json:"pack_renewals"` + CompressedBlocks uint64 `json:"compressed_blocks"` + CompressionSavedBytes uint64 `json:"compression_saved_bytes"` + PacksDiscovered uint64 `json:"packs_discovered"` ManifestsDiscovered uint64 `json:"manifests_discovered"` + ManifestsSkipped uint64 `json:"manifests_skipped"` + ManifestsOrphaned uint64 `json:"manifests_orphaned"` ManifestDiscoveryErrors uint64 `json:"manifest_discovery_errors"` ManifestLoadErrors uint64 `json:"manifest_load_errors"` ActionDigestConflicts uint64 `json:"action_digest_conflicts"` @@ -36,11 +59,18 @@ type Stats struct { type counters struct { requests atomic.Uint64 + operations atomic.Uint64 hits atomic.Uint64 misses atomic.Uint64 + missesAC atomic.Uint64 + missesCAS atomic.Uint64 + missesPresence atomic.Uint64 + missesRejected atomic.Uint64 + missesDegraded atomic.Uint64 uploads atomic.Uint64 deduplicatedUploads atomic.Uint64 discardedUploads atomic.Uint64 + backendRequests atomic.Uint64 backendDownloads atomic.Uint64 backendExistenceChecks atomic.Uint64 backendLoadErrors atomic.Uint64 @@ -52,11 +82,23 @@ type counters struct { skippedActionResultUploads atomic.Uint64 bytesServed atomic.Uint64 bytesReceived atomic.Uint64 + assetRequests atomic.Uint64 + assetHits atomic.Uint64 + assetDownloads atomic.Uint64 + assetRejected atomic.Uint64 + assetFetchErrors atomic.Uint64 throttleWaits atomic.Uint64 packUploads atomic.Uint64 manifestUploads atomic.Uint64 packDownloads atomic.Uint64 + packLoadsSkipped atomic.Uint64 + packRenewals atomic.Uint64 + compressedBlocks atomic.Uint64 + compressionSavedBytes atomic.Uint64 + packsDiscovered atomic.Uint64 manifestsDiscovered atomic.Uint64 + manifestsSkipped atomic.Uint64 + manifestsOrphaned atomic.Uint64 manifestDiscoveryErrors atomic.Uint64 manifestLoadErrors atomic.Uint64 actionDigestConflicts atomic.Uint64 @@ -65,11 +107,18 @@ type counters struct { func (c *counters) snapshot() Stats { return Stats{ Requests: c.requests.Load(), + Operations: c.operations.Load(), Hits: c.hits.Load(), Misses: c.misses.Load(), + MissesAC: c.missesAC.Load(), + MissesCAS: c.missesCAS.Load(), + MissesPresence: c.missesPresence.Load(), + MissesRejected: c.missesRejected.Load(), + MissesDegraded: c.missesDegraded.Load(), Uploads: c.uploads.Load(), DeduplicatedUploads: c.deduplicatedUploads.Load(), DiscardedUploads: c.discardedUploads.Load(), + BackendRequests: c.backendRequests.Load(), BackendDownloads: c.backendDownloads.Load(), BackendExistenceChecks: c.backendExistenceChecks.Load(), BackendLoadErrors: c.backendLoadErrors.Load(), @@ -81,11 +130,23 @@ func (c *counters) snapshot() Stats { SkippedActionResultUploads: c.skippedActionResultUploads.Load(), BytesServed: c.bytesServed.Load(), BytesReceived: c.bytesReceived.Load(), + AssetRequests: c.assetRequests.Load(), + AssetHits: c.assetHits.Load(), + AssetDownloads: c.assetDownloads.Load(), + AssetRejected: c.assetRejected.Load(), + AssetFetchErrors: c.assetFetchErrors.Load(), ThrottleWaits: c.throttleWaits.Load(), PackUploads: c.packUploads.Load(), ManifestUploads: c.manifestUploads.Load(), PackDownloads: c.packDownloads.Load(), + PackLoadsSkipped: c.packLoadsSkipped.Load(), + PackRenewals: c.packRenewals.Load(), + CompressedBlocks: c.compressedBlocks.Load(), + CompressionSavedBytes: c.compressionSavedBytes.Load(), + PacksDiscovered: c.packsDiscovered.Load(), ManifestsDiscovered: c.manifestsDiscovered.Load(), + ManifestsSkipped: c.manifestsSkipped.Load(), + ManifestsOrphaned: c.manifestsOrphaned.Load(), ManifestDiscoveryErrors: c.manifestDiscoveryErrors.Load(), ManifestLoadErrors: c.manifestLoadErrors.Load(), ActionDigestConflicts: c.actionDigestConflicts.Load(), diff --git a/internal/server/usage.go b/internal/server/usage.go new file mode 100644 index 0000000..e919829 --- /dev/null +++ b/internal/server/usage.go @@ -0,0 +1,164 @@ +package server + +import ( + "encoding/json" + "sort" + "sync" +) + +// Access classes recorded for a cache entry. +const ( + accessPresence = "presence" + accessDownload = "download" +) + +// UsageEntry is one cache entry a job touched. +type UsageEntry struct { + Kind string `json:"kind"` + Digest string `json:"digest"` + Pack string `json:"pack,omitempty"` + // Absent when nothing reported a size. Zero is a real size, not a missing + // one: the empty blob has a well-known digest. + Size *int64 `json:"size,omitempty"` + PresenceChecks uint64 `json:"presence_checks"` + Downloads uint64 `json:"downloads"` +} + +// Access reports how the entry was used. A presence-only entry still has to +// exist, or the action result referencing it becomes a miss, but nothing ever +// needed its bytes. +func (e UsageEntry) Access() string { + if e.Downloads > 0 { + return accessDownload + } + return accessPresence +} + +// UsagePack describes how much of a restored pack a job turned out to need. +// Size is what the transfer cost; DeclaredBytes is the uncompressed content it +// holds, and is the only one of the two comparable with BytesUsed. +type UsagePack struct { + ID string `json:"id"` + Size int64 `json:"size"` + DeclaredBytes int64 `json:"declared_bytes"` + BytesUsed int64 `json:"bytes_used"` + Restored bool `json:"restored"` +} + +// UsageReport is the record an optimisation pass consumes. It is deliberately +// about what was used rather than what exists: pack composition can be read back +// from the manifests, but only a job knows which entries it needed. +type UsageReport struct { + Entries []UsageEntry `json:"entries"` + Packs []UsagePack `json:"packs"` + // PackBytesRestored is what the transfers cost, so it is compressed and is + // not comparable with PackBytesUsed. + PackBytesRestored int64 `json:"pack_bytes_restored"` + // PackBytesDeclared is the uncompressed content those packs hold. Yield is + // PackBytesUsed over this. + PackBytesDeclared int64 `json:"pack_bytes_declared"` + PackBytesUsed int64 `json:"pack_bytes_used"` +} + +func (r UsageReport) JSON() []byte { + data, _ := json.Marshal(r) + return data +} + +type usageRecorder struct { + mu sync.Mutex + entries map[string]*UsageEntry + restored map[string]restoredPack +} + +type restoredPack struct { + stored int64 + declared int64 +} + +func newUsageRecorder() *usageRecorder { + return &usageRecorder{ + entries: make(map[string]*UsageEntry), + restored: make(map[string]restoredPack), + } +} + +func (r *usageRecorder) record(kind, digest, pack, access string, size int64) { + if digest == "" { + return + } + r.mu.Lock() + defer r.mu.Unlock() + entry, found := r.entries[kind+"/"+digest] + if !found { + entry = &UsageEntry{Kind: kind, Digest: digest} + r.entries[kind+"/"+digest] = entry + } + if pack != "" { + entry.Pack = pack + } + // Never let a presence check without a size erase a size a download established. + if size >= 0 { + recorded := size + entry.Size = &recorded + } + if access == accessDownload { + entry.Downloads++ + return + } + entry.PresenceChecks++ +} + +// packRestored notes that a pack was paid for. The bytes it cost are compared +// against the bytes that turned out to be wanted, which is the ratio that says +// whether packing is placing hot and cold content together. +func (r *usageRecorder) packRestored(pack string, stored, declared int64) { + r.mu.Lock() + defer r.mu.Unlock() + r.restored[pack] = restoredPack{stored: stored, declared: declared} +} + +func (r *usageRecorder) report() UsageReport { + r.mu.Lock() + defer r.mu.Unlock() + + report := UsageReport{ + Entries: make([]UsageEntry, 0, len(r.entries)), + Packs: make([]UsagePack, 0, len(r.restored)), + } + used := make(map[string]int64, len(r.restored)) + for _, entry := range r.entries { + copied := *entry + if entry.Size != nil { + size := *entry.Size + copied.Size = &size + } + report.Entries = append(report.Entries, copied) + // Only a download consumes the bandwidth a restore paid for; a presence + // check is answered from the manifest without touching the pack. + if copied.Pack != "" && copied.Downloads > 0 && copied.Size != nil { + used[copied.Pack] += *copied.Size + } + } + for pack, sizes := range r.restored { + report.Packs = append(report.Packs, UsagePack{ + ID: pack, + Size: sizes.stored, + DeclaredBytes: sizes.declared, + BytesUsed: used[pack], + Restored: true, + }) + report.PackBytesRestored += sizes.stored + report.PackBytesDeclared += sizes.declared + report.PackBytesUsed += used[pack] + } + + sort.Slice(report.Entries, func(i, j int) bool { + if report.Entries[i].Kind != report.Entries[j].Kind { + return report.Entries[i].Kind < report.Entries[j].Kind + } + return report.Entries[i].Digest < report.Entries[j].Digest + }) + sort.Slice(report.Packs, func(i, j int) bool { return report.Packs[i].ID < report.Packs[j].ID }) + return report +} diff --git a/internal/server/usage_test.go b/internal/server/usage_test.go new file mode 100644 index 0000000..d478b87 --- /dev/null +++ b/internal/server/usage_test.go @@ -0,0 +1,143 @@ +package server + +import ( + "encoding/json" + "net/http" + "strings" + "testing" + "time" +) + +func usageFor(t *testing.T, report UsageReport, kind, digest string) UsageEntry { + t.Helper() + for _, entry := range report.Entries { + if entry.Kind == kind && entry.Digest == digest { + return entry + } + } + t.Fatalf("no usage recorded for %s/%s in %+v", kind, digest, report.Entries) + return UsageEntry{} +} + +func TestUsageSeparatesPresenceChecksFromDownloads(t *testing.T) { + downloaded := []byte("an output something actually reads") + downloadedReference := referenceFor(downloaded) + backend := newMemoryBackend() + backend.objects["test-v1-cas-"+downloadedReference.hash] = downloaded + server := testServer(t, backend, nil) + + headCacheObject(server, "/cas/"+downloadedReference.hash) + readCacheObject(server, "/cas/"+downloadedReference.hash) + + entry := usageFor(t, server.Usage(), "cas", downloadedReference.hash) + if entry.Downloads == 0 || entry.Access() != accessDownload { + t.Fatalf("entry = %+v, want a download", entry) + } + if entry.Size == nil || *entry.Size != downloadedReference.size { + t.Fatalf("size = %v, want %d", entry.Size, downloadedReference.size) + } +} + +// An output that is only ever presence-checked still has to exist, or the action +// result referencing it becomes a miss. Recording those checks is what stops a +// later optimisation pass from treating such an output as dead. +func TestUsageRecordsClosureValidationPresenceChecks(t *testing.T) { + output := []byte("an output nothing downloads") + outputReference := referenceFor(output) + actionDigest := strings.Repeat("a", 64) + backend := newMemoryBackend() + backend.objects["test-v1-cas-"+outputReference.hash] = output + backend.objects["test-v1-ac-"+actionDigest] = actionResultProto(t, outputReference) + server := testServer(t, backend, nil) + + if response := readCacheObject(server, "/ac/"+actionDigest); response.Code != http.StatusOK { + t.Fatalf("AC GET = %d", response.Code) + } + + report := server.Usage() + action := usageFor(t, report, "ac", actionDigest) + if action.Downloads == 0 { + t.Fatalf("action result = %+v, want a download", action) + } + blob := usageFor(t, report, "cas", outputReference.hash) + if blob.PresenceChecks == 0 || blob.Access() != accessPresence { + t.Fatalf("output = %+v, want a presence check and no download", blob) + } + if blob.Size == nil || *blob.Size != outputReference.size { + t.Fatalf("size = %v, want %d from manifest", blob.Size, outputReference.size) + } + encoded, err := json.Marshal(blob) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(encoded), `"size"`) { + t.Fatalf("entry is missing manifest size: %s", encoded) + } +} + +// The ratio of bytes restored to bytes wanted is what says whether packing is +// putting frequently and rarely fetched content together. +func TestUsageReportsPackYield(t *testing.T) { + hot := []byte(strings.Repeat("h", 300)) + cold := []byte(strings.Repeat("c", 300)) + hotReference := referenceFor(hot) + coldReference := referenceFor(cold) + backend := newMemoryBackend() + + packed := func(t *testing.T) *Server { + t.Helper() + return testServer(t, backend, func(cfg *Config) { + cfg.Catalog = memoryCatalog{backend: backend} + cfg.PackSize = 1024 + cfg.PackFlushInterval = time.Hour + cfg.MaxManifests = 16 + }) + } + + seed := packed(t) + for _, blob := range [][]byte{hot, cold} { + if response := putCacheObject(seed, "/cas/"+digest(blob), blob); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + } + closePackedServer(t, seed) + + // A fresh server pays for the whole pack to read one of the two blobs. + restored := packed(t) + defer closePackedServer(t, restored) + if response := readCacheObject(restored, "/cas/"+hotReference.hash); response.Code != http.StatusOK { + t.Fatalf("CAS GET = %d", response.Code) + } + report := restored.Usage() + if len(report.Packs) != 1 { + t.Fatalf("packs = %+v, want exactly one restored pack", report.Packs) + } + if report.PackBytesUsed != hotReference.size { + t.Fatalf("bytes used = %d, want %d", report.PackBytesUsed, hotReference.size) + } + // Yield is used over declared. A restored total is compressed, so comparing + // against it can exceed 1 and say nothing. + if report.PackBytesDeclared != hotReference.size+coldReference.size { + t.Fatalf("declared = %d, want the two blobs' %d", + report.PackBytesDeclared, hotReference.size+coldReference.size) + } + if report.PackBytesUsed >= report.PackBytesDeclared { + t.Fatalf("used %d of %d declared; the yield should be below 1", + report.PackBytesUsed, report.PackBytesDeclared) + } + if pack := usageFor(t, report, "cas", hotReference.hash).Pack; pack != report.Packs[0].ID { + t.Fatalf("entry pack = %q, want %q", pack, report.Packs[0].ID) + } + // The cold blob was never asked for, so it must not appear as used. + for _, entry := range report.Entries { + if entry.Digest == coldReference.hash { + t.Fatalf("unused blob was recorded: %+v", entry) + } + } + + stats := restored.Snapshot() + if stats.PackBytesRestored != uint64(report.PackBytesRestored) || + stats.PackBytesUsed != uint64(report.PackBytesUsed) { + t.Fatalf("stats disagree with the usage report: %+v", stats) + } +} diff --git a/optimise/action.yml b/optimise/action.yml new file mode 100644 index 0000000..8f4da5b --- /dev/null +++ b/optimise/action.yml @@ -0,0 +1,90 @@ +name: Optimise Bazel cache layout +description: Regroup CARv2 packs around how recent jobs actually read them, and delete what it replaces +author: cre4ture +branding: + icon: package + color: green +inputs: + github-token: + description: "Token with actions: write; required to delete the cache entries this pass replaces" + required: true + key-prefix: + description: "Immutable GitHub cache-key namespace to optimise; must match the cache action's key-prefix" + required: false + default: bazel-http-v1 + usage-artifact: + description: "Job artifact the cache action publishes its usage records to" + required: false + default: bazel-cache-usage + max-records: + description: "How many recent usage records to plan from; each job that uses the cache publishes one" + required: false + default: "25" + min-runs: + description: "Refuse to plan from fewer usage records than this; too small a window describes particular jobs rather than the repository" + required: false + default: "3" + pack-size-mb: + description: "Target size of a rebuilt pack in MiB (1-32)" + required: false + default: "8" + min-waste-fraction: + description: "How much of a pack must be bytes an average restore pays for and does not want before rebuilding it (0-1)" + required: false + default: "0.25" + evict-after-hours: + description: "Evict entries no job has used for this long, rewriting each affected pack on its own and keeping its age. Defaults to GitHub's 7-day expiry of unused caches. Packs are only reshaped once twice this old" + required: false + default: "168" + download-overhead-mb: + description: "Fixed cost of restoring one pack, in MiB it is worth; what makes reshaping merge small packs to cut downloads" + required: false + default: "8" + min-improvement: + description: "How much of a wasteful pack's overfetch its rebuild must remove, judged on recent runs the regrouping was not fitted to (0-1). Stops a pass rebuilding packs no grouping can improve" + required: false + default: "0.25" + max-blob-size-mb: + description: "Maximum object size in MiB" + required: false + default: "512" + max-new-mb: + description: "Stop a pass once it has published this many MiB, so a cache near its quota is not asked to hold the old and new layouts at once; 0 means no limit" + required: false + default: "2048" + uploads-per-minute: + description: "Evenly spaced uploads; must be below 200" + required: false + default: "180" + reap-unmanifested-packs: + description: "Delete packs that no manifest names at all, and manifests whose pack is gone. Both are unreachable, but this is the one thing here that removes data without publishing a replacement" + required: false + default: "false" + reap-older-than-hours: + description: "Only reap packs and manifests older than this, so a pack a running job has published but not yet committed a manifest for is out of reach. Fractions are allowed; anything under an hour is for testing only" + required: false + default: "24" + backend-timeout-seconds: + description: "Timeout for one GitHub cache operation" + required: false + default: "300" + dry-run: + description: "Plan and report without publishing or deleting anything" + required: false + default: "false" + job-summary: + description: "Write the result to the job summary" + required: false + default: "true" +outputs: + summary: + description: "JSON result of the pass" + rebuilt: + description: "Number of packs rebuilt" + deleted: + description: "Number of packs deleted" + reaped: + description: "Number of unreachable packs reaped" +runs: + using: node24 + main: main.js diff --git a/optimise/main.js b/optimise/main.js new file mode 100644 index 0000000..b13277f --- /dev/null +++ b/optimise/main.js @@ -0,0 +1,280 @@ +"use strict"; + +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { spawn } = require("node:child_process"); +const { + eventPayload, + formatBytes, + formatCount, + input, + mask, + parseBoolean, + safeTemporaryDirectory, + setOutput, +} = require("../action/lib"); +const { resolveBinary } = require("../action/release"); + +function positiveInteger(name, fallback, maximum = Number.MAX_SAFE_INTEGER) { + const value = Number.parseInt(input(name, String(fallback)), 10); + if (!Number.isSafeInteger(value) || value <= 0 || value > maximum) { + throw new Error(`${name} must be an integer between 1 and ${maximum}`); + } + return value; +} + +function fraction(name, fallback) { + const value = Number.parseFloat(input(name, String(fallback))); + if (!Number.isFinite(value) || value < 0 || value > 1) { + throw new Error(`${name} must be between 0 and 1`); + } + return value; +} + +// Fractions are allowed so that a test can ask for a threshold shorter than an +// hour. Anything that short cannot tell a lost pack from one a running job is +// still publishing, so it warns. +function reapAge(name, fallback, maximumHours) { + const hours = Number.parseFloat(input(name, String(fallback))); + if (!Number.isFinite(hours) || hours <= 0 || hours > maximumHours) { + throw new Error( + `${name} must be greater than 0 and at most ${maximumHours}; fractions of an hour are allowed`, + ); + } + if (hours < 1) { + process.stdout.write( + `::warning::${name} is under an hour, so a pack a running job has published but not yet ` + + `committed a manifest for can be reaped; use this for testing only${os.EOL}`, + ); + } + return Math.max(1, Math.round(hours * 3600)); +} + +function run(binary, args, env) { + return new Promise((resolve, reject) => { + const child = spawn(binary, args, { stdio: ["ignore", "inherit", "inherit"], env }); + child.on("error", reject); + child.on("exit", (code, signal) => { + if (signal) { + reject(new Error(`the optimiser was killed by ${signal}`)); + return; + } + if (code !== 0) { + reject(new Error(`the optimiser exited with status ${code}`)); + return; + } + resolve(); + }); + }); +} + +function writeJobSummary(result) { + const file = process.env.GITHUB_STEP_SUMMARY; + if (!file) { + return; + } + const count = (value) => formatCount(value ?? 0); + const bytes = (value) => formatBytes(value ?? 0); + const yesNo = (value) => (value ? "yes" : "no"); + const rows = [ + ["Usage records read", count(result.Records)], + ["Packs before", count(result.Packs)], + ["Live entries", count(result.Entries)], + ["Manifests not restorable here", count(result.Unreadable)], + ["Packs no manifest names", count(result.Unmanifested)], + ["Packs old enough to reap", count(result.Reapable)], + ["Packs rebuilt", count(result.Rebuilt)], + ["Packs deleted", count(result.Deleted)], + ["Packs reaped", count(result.Reaped)], + ["Manifests whose pack is gone", count(result.OrphanManifests)], + ["Of those, reaped", count(result.ReapedManifests)], + ["Published", bytes(result.PublishedBytes)], + ["Stopped at the byte budget", yesNo(result.Incomplete)], + ["Wasted per restore", bytes(result.WastedBytes)], + ["Usage records in the eviction window", count(result.RecordsInWindow)], + ["Packs cleaned of stale entries", count(result.Evicted)], + ["Stale entries evicted", `${count(result.EvictedEntries)} (${bytes(result.EvictedBytes)})`], + ["Wholly stale packs left to expire", count(result.Abandoned)], + ["Packs old enough to reshape", count(result.ReshapeEligible)], + ["Overfetch per job before", bytes(result.OverfetchBefore)], + ["Overfetch per job after", bytes(result.OverfetchAfter)], + ["Downloads per job before", (result.DownloadsBefore ?? 0).toFixed(1)], + ["Downloads per job after", (result.DownloadsAfter ?? 0).toFixed(1)], + ["Wasteful packs no regrouping improves", count(result.Unimproved)], + ["Reclaimed", bytes(result.ReclaimedBytes)], + ["Dry run", yesNo(result.DryRun)], + ]; + const table = [ + "### Bazel cache layout", + "", + ...(result.Skipped ? [`Nothing to do: ${result.Skipped}.`, ""] : []), + ...(result.EvictionSkipped ? [`Evicting nothing: ${result.EvictionSkipped}.`, ""] : []), + ...(result.ReshapeSkipped ? [`Not reshaping: ${result.ReshapeSkipped}.`, ""] : []), + "| Measure | Value |", + "| --- | ---: |", + ...rows.map(([label, value]) => `| ${label} | ${value} |`), + "", + ].join(os.EOL); + fs.appendFileSync(file, table + os.EOL); +} + +// A pass reads, rebuilds and deletes entirely within the reference it runs on. +// Running it from a branch would therefore rebuild that branch's own caches, +// which is almost always a mistake: the entries jobs actually read belong to the +// default branch. +function requireDefaultBranch() { + const defaultBranch = eventPayload().repository?.default_branch; + const ref = process.env.GITHUB_REF_NAME; + if (!defaultBranch || !ref || ref === defaultBranch) { + return; + } + throw new Error( + `refusing to apply from ${ref}: a pass only ever touches its own reference's caches, ` + + `so this would rebuild ${ref} rather than what jobs read; run from ${defaultBranch} or set dry-run`, + ); +} + +async function main() { + if (process.platform !== "linux") { + throw new Error("this release supports Linux GitHub Actions runners only"); + } + if (process.env.ACTIONS_CACHE_SERVICE_V2?.toLowerCase() !== "true") { + throw new Error("GitHub Actions cache v2 is unavailable (ACTIONS_CACHE_SERVICE_V2 != true)"); + } + if (!process.env.ACTIONS_RESULTS_URL || !process.env.ACTIONS_RUNTIME_TOKEN) { + throw new Error("GitHub Actions cache v2 credentials are unavailable in this step"); + } + + const architecture = { x64: "amd64", arm64: "arm64" }[process.arch]; + if (!architecture) { + throw new Error(`unsupported Linux architecture: ${process.arch}`); + } + + const githubToken = input("github-token", ""); + if (!githubToken) { + throw new Error("github-token is required; the pass deletes the cache entries it replaces"); + } + mask(githubToken); + + const keyPrefix = input("key-prefix", "bazel-http-v1").trim(); + if (!/^[A-Za-z0-9._-]{1,128}$/.test(keyPrefix)) { + throw new Error("key-prefix must match [A-Za-z0-9._-]{1,128}"); + } + const usageArtifact = input("usage-artifact", "bazel-cache-usage").trim(); + if (!/^[A-Za-z0-9._-]{1,180}$/.test(usageArtifact)) { + throw new Error("usage-artifact must match [A-Za-z0-9._-]{1,180}"); + } + const maxRecords = positiveInteger("max-records", 25, 1000); + const minRuns = positiveInteger("min-runs", 3, 1000); + const packSizeMB = positiveInteger("pack-size-mb", 8, 32); + const maxBlobSizeMB = positiveInteger("max-blob-size-mb", 512, 10_240); + const uploadsPerMinute = positiveInteger("uploads-per-minute", 180, 199); + const maxNewMB = Number.parseInt(input("max-new-mb", "2048"), 10); + if (!Number.isSafeInteger(maxNewMB) || maxNewMB < 0) { + throw new Error("max-new-mb must be a non-negative integer"); + } + const reap = parseBoolean(input("reap-unmanifested-packs", "false"), "reap-unmanifested-packs"); + const reapOlderThanSeconds = reapAge("reap-older-than-hours", 24, 8760); + const backendTimeoutSeconds = positiveInteger("backend-timeout-seconds", 300, 3600); + const minWasteFraction = fraction("min-waste-fraction", 0.25); + const minImprovement = fraction("min-improvement", 0.25); + const evictAfterHours = positiveInteger("evict-after-hours", 168, 8760); + const downloadOverheadMB = Number.parseInt(input("download-overhead-mb", "8"), 10); + if (!Number.isSafeInteger(downloadOverheadMB) || downloadOverheadMB < 0 || downloadOverheadMB > 1024) { + throw new Error("download-overhead-mb must be an integer between 0 and 1024"); + } + const dryRun = parseBoolean(input("dry-run", "false"), "dry-run"); + const jobSummary = parseBoolean(input("job-summary", "true"), "job-summary"); + if (!dryRun) { + requireDefaultBranch(); + } + + const tempDir = safeTemporaryDirectory( + fs.mkdtempSync(path.join(path.resolve(process.env.RUNNER_TEMP), "bazel-gha-optimise-")), + ); + const summaryFile = path.join(tempDir, "summary.json"); + const spoolDir = path.join(tempDir, "spool"); + + const binary = await resolveBinary({ + program: "cache-optimiser", + actionRoot: path.resolve(__dirname, ".."), + architecture, + // Installing under a fixed name keeps every part of the spawned path a + // constant, so no release name can influence which program runs. + installPath: path.join(tempDir, "cache-optimiser"), + repository: process.env.GITHUB_ACTION_REPOSITORY, + ref: process.env.GITHUB_ACTION_REF, + token: githubToken, + toolCacheRoot: path.resolve( + process.env.RUNNER_TOOL_CACHE || process.env.RUNNER_TEMP || os.tmpdir(), + ), + log: (message) => process.stdout.write(`${message}${os.EOL}`), + }); + + const args = [ + "--cache-dir", + spoolDir, + "--key-prefix", + keyPrefix, + "--usage-artifact", + usageArtifact, + "--max-records", + String(maxRecords), + "--min-runs", + String(minRuns), + "--pack-size", + String(packSizeMB * 1024 * 1024), + "--min-waste-fraction", + String(minWasteFraction), + "--min-improvement", + String(minImprovement), + "--evict-after", + `${evictAfterHours}h`, + "--download-overhead", + String(downloadOverheadMB * 1024 * 1024), + "--max-blob-size", + String(maxBlobSizeMB * 1024 * 1024), + "--uploads-per-minute", + String(uploadsPerMinute), + "--max-new-bytes", + String(maxNewMB * 1024 * 1024), + "--reap-older-than", + `${reapOlderThanSeconds}s`, + "--backend-timeout", + `${backendTimeoutSeconds}s`, + "--summary-file", + summaryFile, + ]; + if (dryRun) { + args.push("--dry-run"); + } + if (reap) { + args.push("--reap"); + } + + try { + // The binary reads its credentials from the environment, so the token has to + // arrive that way rather than on a command line other processes can see. + await run(binary, args, { ...process.env, GITHUB_TOKEN: githubToken }); + } finally { + // The summary is written even on failure, and is the only record of how far + // the pass got. + if (fs.existsSync(summaryFile)) { + const result = JSON.parse(fs.readFileSync(summaryFile, "utf8")); + setOutput("summary", JSON.stringify(result)); + setOutput("rebuilt", String(result.Rebuilt ?? 0)); + setOutput("deleted", String(result.Deleted ?? 0)); + setOutput("reaped", String(result.Reaped ?? 0)); + if (jobSummary) { + writeJobSummary(result); + } + } + fs.rmSync(tempDir, { recursive: true, force: true }); + } +} + +main().catch((error) => { + process.stdout.write(`::error::${error.message}${os.EOL}`); + process.exitCode = 1; +}); diff --git a/optimise/main.test.js b/optimise/main.test.js new file mode 100644 index 0000000..4d55f13 --- /dev/null +++ b/optimise/main.test.js @@ -0,0 +1,254 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const test = require("node:test"); +const { spawnSync } = require("node:child_process"); + +const repoRoot = path.resolve(__dirname, ".."); +const architecture = { x64: "amd64", arm64: "arm64" }[process.arch]; +const asset = `cache-optimiser-linux-${architecture}`; + +// A stub that records how it was invoked and produces the summary the wrapper +// reads back. +const STUB = `#!/usr/bin/env node +const fs = require("node:fs"); +const args = process.argv.slice(2); +fs.writeFileSync(process.env.STUB_ARGS_FILE, JSON.stringify(args)); +const at = args.indexOf("--summary-file"); +fs.writeFileSync(args[at + 1], JSON.stringify({ Records: 4, Rebuilt: 0, Deleted: 0, DryRun: true, Entries: 169396, WastedBytes: 1610612736, OverfetchBefore: 1073741824, OverfetchAfter: 268435456, Unimproved: 12, DownloadsBefore: 7.25, DownloadsAfter: 3, Evicted: 3, EvictedEntries: 1500, EvictedBytes: 52428800, ReshapeSkipped: "1 packs are old enough to reshape, and reshaping needs at least 2" })); +`; + +function runWrapper(t, inputs) { + const distBinary = path.join(repoRoot, "dist", asset); + if (fs.existsSync(distBinary)) { + // Reusing our own stub matters: a test that calls this twice would + // otherwise see the stub it just wrote and skip itself. + if (fs.readFileSync(distBinary, "utf8") !== STUB) { + // A real build is present, so the wrapper would run the actual optimiser + // against a live cache rather than the stub. + t.skip(`dist/${asset} exists; run this before scripts/build-dist.sh`); + return null; + } + } else { + fs.mkdirSync(path.dirname(distBinary), { recursive: true }); + fs.writeFileSync(distBinary, STUB, { mode: 0o755 }); + t.after(() => fs.rmSync(distBinary, { force: true })); + } + + const runnerTemp = fs.mkdtempSync(path.join(os.tmpdir(), "optimise-wrapper-")); + t.after(() => fs.rmSync(runnerTemp, { recursive: true, force: true })); + const argsFile = path.join(runnerTemp, "args.json"); + + const result = spawnSync(process.execPath, [path.join(__dirname, "main.js")], { + encoding: "utf8", + // Deliberately not inheriting the environment: on a runner the ambient + // GITHUB_* variables describe the job running the test, and the wrapper + // would read them as its own context. + env: { + PATH: process.env.PATH, + HOME: process.env.HOME, + STUB_ARGS_FILE: argsFile, + RUNNER_TEMP: runnerTemp, + RUNNER_TOOL_CACHE: path.join(runnerTemp, "tools"), + GITHUB_OUTPUT: path.join(runnerTemp, "output"), + GITHUB_STEP_SUMMARY: path.join(runnerTemp, "summary.md"), + ACTIONS_CACHE_SERVICE_V2: "true", + ACTIONS_RESULTS_URL: "https://results.example.invalid/", + ACTIONS_RUNTIME_TOKEN: "header.payload.signature", + "INPUT_GITHUB-TOKEN": "test-token", + ...inputs, + }, + }); + return { result, argsFile, runnerTemp }; +} + +// The wrapper had no coverage at all, and shipped without passing the +// architecture through: the asset name became cache-optimiser-linux-undefined, +// which surfaced as a path error several frames away. +test("the wrapper runs the binary for this architecture with the parsed inputs", (t) => { + const run = runWrapper(t, { + "INPUT_KEY-PREFIX": "custom-prefix", + "INPUT_USAGE-ARTIFACT": "custom-usage", + "INPUT_MIN-RUNS": "2", + "INPUT_PACK-SIZE-MB": "4", + "INPUT_MIN-IMPROVEMENT": "0.4", + "INPUT_EVICT-AFTER-HOURS": "72", + "INPUT_DOWNLOAD-OVERHEAD-MB": "2", + "INPUT_DRY-RUN": "true", + }); + if (!run) return; + + assert.equal(run.result.status, 0, run.result.stdout + run.result.stderr); + const args = JSON.parse(fs.readFileSync(run.argsFile, "utf8")); + const valueOf = (flag) => args[args.indexOf(flag) + 1]; + assert.equal(valueOf("--key-prefix"), "custom-prefix"); + assert.equal(valueOf("--usage-artifact"), "custom-usage"); + assert.equal(valueOf("--min-runs"), "2"); + assert.equal(valueOf("--pack-size"), String(4 * 1024 * 1024)); + assert.equal(valueOf("--min-improvement"), "0.4"); + assert.equal(valueOf("--evict-after"), "72h"); + assert.equal(valueOf("--download-overhead"), String(2 * 1024 * 1024)); + assert.ok(args.includes("--dry-run")); +}); + +test("a pass that applies does not ask for a dry run", (t) => { + const run = runWrapper(t, { "INPUT_DRY-RUN": "false" }); + if (!run) return; + + assert.equal(run.result.status, 0, run.result.stdout + run.result.stderr); + const args = JSON.parse(fs.readFileSync(run.argsFile, "utf8")); + assert.ok(!args.includes("--dry-run")); +}); + +// Reaping removes data without publishing a replacement, so it has to stay off +// unless it is asked for. +test("reaping is off unless it is asked for", (t) => { + const off = runWrapper(t, { "INPUT_DRY-RUN": "true" }); + if (!off) return; + assert.equal(off.result.status, 0, off.result.stdout + off.result.stderr); + assert.ok(!JSON.parse(fs.readFileSync(off.argsFile, "utf8")).includes("--reap")); +}); + +test("reaping passes its age threshold through", (t) => { + const run = runWrapper(t, { + "INPUT_DRY-RUN": "true", + "INPUT_REAP-UNMANIFESTED-PACKS": "true", + "INPUT_REAP-OLDER-THAN-HOURS": "48", + }); + if (!run) return; + + assert.equal(run.result.status, 0, run.result.stdout + run.result.stderr); + const args = JSON.parse(fs.readFileSync(run.argsFile, "utf8")); + assert.ok(args.includes("--reap")); + assert.equal(args[args.indexOf("--reap-older-than") + 1], `${48 * 3600}s`); +}); + +// Testing the reaper needs a threshold shorter than an hour, which is too short +// to tell a lost pack from one a running job is still publishing. +test("a sub-hour age threshold is allowed but warned about", (t) => { + const run = runWrapper(t, { + "INPUT_DRY-RUN": "true", + "INPUT_REAP-UNMANIFESTED-PACKS": "true", + "INPUT_REAP-OLDER-THAN-HOURS": "0.25", + }); + if (!run) return; + + assert.equal(run.result.status, 0, run.result.stdout + run.result.stderr); + const args = JSON.parse(fs.readFileSync(run.argsFile, "utf8")); + assert.equal(args[args.indexOf("--reap-older-than") + 1], "900s"); + assert.match(run.result.stdout, /::warning::reap-older-than-hours is under an hour/); +}); + +test("an age threshold of zero or less is refused", (t) => { + for (const hours of ["0", "-1"]) { + const run = runWrapper(t, { "INPUT_REAP-OLDER-THAN-HOURS": hours }); + if (!run) return; + assert.equal(run.result.status, 1); + assert.match(run.result.stdout, /reap-older-than-hours must be greater than 0/); + } +}); + +test("the publish budget and upload rate reach the binary", (t) => { + const run = runWrapper(t, { + "INPUT_DRY-RUN": "true", + "INPUT_MAX-NEW-MB": "512", + "INPUT_UPLOADS-PER-MINUTE": "120", + }); + if (!run) return; + + assert.equal(run.result.status, 0, run.result.stdout + run.result.stderr); + const args = JSON.parse(fs.readFileSync(run.argsFile, "utf8")); + const valueOf = (flag) => args[args.indexOf(flag) + 1]; + assert.equal(valueOf("--max-new-bytes"), String(512 * 1024 * 1024)); + assert.equal(valueOf("--uploads-per-minute"), "120"); +}); + +test("an upload rate at or above GitHub's limit is refused", (t) => { + const run = runWrapper(t, { "INPUT_UPLOADS-PER-MINUTE": "200" }); + if (!run) return; + + assert.equal(run.result.status, 1); + assert.match(run.result.stdout, /uploads-per-minute must be an integer between 1 and 199/); +}); + +test("the result reaches the job summary and the step outputs", (t) => { + const run = runWrapper(t, { "INPUT_DRY-RUN": "true" }); + if (!run) return; + + assert.equal(run.result.status, 0, run.result.stdout + run.result.stderr); + const summary = fs.readFileSync(path.join(run.runnerTemp, "summary.md"), "utf8"); + assert.match(summary, /Usage records read \| 4/); + // Sizes are for people to read, so they use the largest unit that fits + // rather than a raw byte count. + assert.match(summary, /Wasted per restore \| 1\.5GiB/); + assert.match(summary, /Overfetch per job before \| 1GiB/); + assert.match(summary, /Overfetch per job after \| 256MiB/); + assert.match(summary, /Wasteful packs no regrouping improves \| 12/); + assert.match(summary, /Downloads per job before \| 7\.3/); + assert.match(summary, /Stale entries evicted \| 1,500 \(50MiB\)/); + assert.match(summary, /Not reshaping: 1 packs are old enough/); + assert.match(summary, /Live entries \| 169,396/); + assert.match(summary, /Dry run \| yes/); + const outputs = fs.readFileSync(path.join(run.runnerTemp, "output"), "utf8"); + assert.match(outputs, /^rebuilt=0$/m); + assert.match(outputs, /^deleted=0$/m); + assert.match(outputs, /^summary=\{.*"Records":4.*\}$/m); +}); + +test("a token is required, since the pass deletes what it replaces", (t) => { + const run = runWrapper(t, { "INPUT_GITHUB-TOKEN": "" }); + if (!run) return; + + assert.equal(run.result.status, 1); + assert.match(run.result.stdout, /github-token is required/); +}); + +test("an input outside its range stops the pass", (t) => { + const run = runWrapper(t, { "INPUT_MIN-WASTE-FRACTION": "2" }); + if (!run) return; + + assert.equal(run.result.status, 1); + assert.match(run.result.stdout, /min-waste-fraction must be between 0 and 1/); + + const improvement = runWrapper(t, { "INPUT_MIN-IMPROVEMENT": "-0.1" }); + assert.equal(improvement.result.status, 1); + assert.match(improvement.result.stdout, /min-improvement must be between 0 and 1/); + + const eviction = runWrapper(t, { "INPUT_EVICT-AFTER-HOURS": "0" }); + assert.equal(eviction.result.status, 1); + assert.match(eviction.result.stdout, /evict-after-hours must be an integer between 1 and 8760/); +}); + +// Deleting spans every ref, but a replacement published from a branch is only +// visible to that branch. +test("applying from a branch other than the default is refused", (t) => { + const eventFile = path.join(os.tmpdir(), `optimise-event-${process.pid}.json`); + fs.writeFileSync(eventFile, JSON.stringify({ repository: { default_branch: "main" } })); + t.after(() => fs.rmSync(eventFile, { force: true })); + + const applying = runWrapper(t, { + "INPUT_DRY-RUN": "false", + GITHUB_EVENT_PATH: eventFile, + GITHUB_REF_NAME: "some-feature", + }); + if (!applying) return; + assert.equal(applying.result.status, 1); + assert.match(applying.result.stdout, /refusing to apply from some-feature/); +}); + +test("planning from a branch is allowed, since it deletes nothing", (t) => { + const eventFile = path.join(os.tmpdir(), `optimise-event-dry-${process.pid}.json`); + fs.writeFileSync(eventFile, JSON.stringify({ repository: { default_branch: "main" } })); + t.after(() => fs.rmSync(eventFile, { force: true })); + + const run = runWrapper(t, { + "INPUT_DRY-RUN": "true", + GITHUB_EVENT_PATH: eventFile, + GITHUB_REF_NAME: "some-feature", + }); + if (!run) return; + assert.equal(run.result.status, 0, run.result.stdout + run.result.stderr); +}); diff --git a/proto/README.md b/proto/README.md new file mode 100644 index 0000000..85b932b --- /dev/null +++ b/proto/README.md @@ -0,0 +1,10 @@ +# Vendored protocol buffer definitions + +The files under `build/` are copied verbatim from +[bazelbuild/remote-apis](https://github.com/bazelbuild/remote-apis) at revision +`9e084d0e43e717128ee72b5be584a7ba33e8006b` (tag `v2.12.0`). Do not edit them by +hand; re-run `scripts/generate-proto.sh --update` to refresh both the vendored +sources and the generated Go code. + +Generated Go code lives in `internal/proto/gen` and is committed so that the +normal `go build` / `go test` flow needs neither `buf` nor `protoc`. diff --git a/proto/buf.lock b/proto/buf.lock new file mode 100644 index 0000000..8447589 --- /dev/null +++ b/proto/buf.lock @@ -0,0 +1,6 @@ +# Generated by buf. DO NOT EDIT. +version: v2 +deps: + - name: buf.build/googleapis/googleapis + commit: c17df5b2beca46928cc87d5656bd5343 + digest: b5:648a01e0170d4512dea7d564016165decd1ed6e34bef79fe54753e51ad7e27545709ad9157d7551270147d551155c595a2fb0bf5bb33b1c83040ddbce915c604 diff --git a/proto/buf.yaml b/proto/buf.yaml new file mode 100644 index 0000000..747115a --- /dev/null +++ b/proto/buf.yaml @@ -0,0 +1,5 @@ +version: v2 +modules: + - path: . +deps: + - buf.build/googleapis/googleapis diff --git a/proto/build/bazel/remote/asset/v1/remote_asset.proto b/proto/build/bazel/remote/asset/v1/remote_asset.proto new file mode 100644 index 0000000..6581f05 --- /dev/null +++ b/proto/build/bazel/remote/asset/v1/remote_asset.proto @@ -0,0 +1,495 @@ +// Copyright 2020 The Bazel Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package build.bazel.remote.asset.v1; + +import "build/bazel/remote/execution/v2/remote_execution.proto"; +import "google/api/annotations.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; +import "google/rpc/status.proto"; + +option csharp_namespace = "Build.Bazel.Remote.Asset.v1"; +option go_package = "github.com/bazelbuild/remote-apis/build/bazel/remote/asset/v1;remoteasset"; +option java_multiple_files = true; +option java_outer_classname = "RemoteAssetProto"; +option java_package = "build.bazel.remote.asset.v1"; +option objc_class_prefix = "RA"; + +// The Remote Asset API provides a mapping from a URI and Qualifiers to +// Digests. +// +// Multiple URIs may be used to refer to the same content. For example, the +// same tarball may exist at multiple mirrors and thus be retrievable from +// multiple URLs. When URLs are used, these should refer to actual content as +// Fetch service implementations may choose to fetch the content directly +// from the origin. For example, the HEAD of a git repository's active branch +// can be referred to as: +// +// uri: https://github.com/bazelbuild/remote-apis.git +// +// URNs may be used to strongly identify content, for instance by using the +// uuid namespace identifier: urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6. +// This is most applicable to named content that is Push'd, where the URN +// serves as an agreed-upon key, but carries no other inherent meaning. +// +// Service implementations may choose to support only URLs, only URNs for +// Push'd content, only other URIs for which the server and client agree upon +// semantics of, or any mixture of the above. + +// Qualifiers are used to disambiguate or sub-select content that shares a URI. +// This may include specifying a particular commit or branch, in the case of +// URIs referencing a repository; they could also be used to specify a +// particular subdirectory of a repository or tarball. Qualifiers may also be +// used to ensure content matches what the client expects, even when there is +// no ambiguity to be had - for example, a qualifier specifying a checksum +// value. +// +// In cases where the semantics of the request are not immediately clear from +// the URL and/or qualifiers - e.g. dictated by URL scheme - it is recommended +// to use an additional qualifier to remove the ambiguity. The `resource_type` +// qualifier is recommended for this purpose. +// +// Qualifiers may be supplied in any order. +message Qualifier { + // The "name" of the qualifier, for example "resource_type". + // No separation is made between 'standard' and 'nonstandard' + // qualifiers, in accordance with https://tools.ietf.org/html/rfc6648, + // however implementers *SHOULD* take care to avoid ambiguity. + string name = 1; + + // The "value" of the qualifier. Semantics will be dictated by the name. + string value = 2; +} + +// The Fetch service resolves or fetches assets referenced by URI and +// Qualifiers, returning a Digest for the content in +// [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +service Fetch { + // Resolve or fetch referenced assets, making them available to the caller and + // other consumers in the [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + // + // Servers *MAY* fetch content that they do not already have cached, for any + // URLs they support. + // + // Servers *SHOULD* ensure that referenced files are present in the CAS at the + // time of the response, and (if supported) that they will remain available + // for a reasonable period of time. The lifetimes of the referenced blobs *SHOULD* + // be increased if necessary and applicable. + // In the event that a client receives a reference to content that is no + // longer present, it *MAY* re-issue the request with + // `oldest_content_accepted` set to a more recent timestamp than the original + // attempt, to induce a re-fetch from origin. + // + // Servers *MAY* cache fetched content and reuse it for subsequent requests, + // subject to `oldest_content_accepted`. + // + // Servers *MAY* support the complementary [Push][build.bazel.remote.asset.v1.Push] + // API and allow content to be directly inserted for use in future fetch + // responses. + // + // Servers *MUST* ensure Fetch'd content matches all the specified + // qualifiers except in the case of previously Push'd resources, for which + // the server *MAY* trust the pushing client to have set the qualifiers + // correctly, without validation. + // + // Servers not implementing the complementary [Push][build.bazel.remote.asset.v1.Push] + // API *MUST* reject requests containing qualifiers it does not support. + // + // Servers *MAY* transform assets as part of the fetch. For example a + // tarball fetched by [FetchDirectory][build.bazel.remote.asset.v1.Fetch.FetchDirectory] + // might be unpacked, or a Git repository + // fetched by [FetchBlob][build.bazel.remote.asset.v1.Fetch.FetchBlob] + // might be passed through `git-archive`. + // + // Errors handling the requested assets will be returned as gRPC Status errors + // here; errors outside the server's control will be returned inline in the + // `status` field of the response (see comment there for details). + // The possible RPC errors include: + // * `INVALID_ARGUMENT`: One or more arguments were invalid, such as a + // qualifier that is not supported by the server. + // * `RESOURCE_EXHAUSTED`: There is insufficient quota of some resource to + // perform the requested operation. The client may retry after a delay. + // * `UNAVAILABLE`: Due to a transient condition the operation could not be + // completed. The client should retry. + // * `INTERNAL`: An internal error occurred while performing the operation. + // The client should retry. + // * `DEADLINE_EXCEEDED`: The fetch could not be completed within the given + // RPC deadline. The client should retry for at least as long as the value + // provided in `timeout` field of the request. + // + // In the case of unsupported qualifiers, the server *SHOULD* additionally + // send a [BadRequest][google.rpc.BadRequest] error detail where, for each + // unsupported qualifier, there is a `FieldViolation` with a `field` of + // `qualifiers.name` and a `description` of `"{qualifier}" not supported` + // indicating the name of the unsupported qualifier. + rpc FetchBlob(FetchBlobRequest) returns (FetchBlobResponse) { + option (google.api.http) = { post: "/v1/{instance_name=**}/assets:fetchBlob" body: "*" }; + } + rpc FetchDirectory(FetchDirectoryRequest) returns (FetchDirectoryResponse) { + option (google.api.http) = { post: "/v1/{instance_name=**}/assets:fetchDirectory" body: "*" }; + } +} + +// A request message for +// [Fetch.FetchBlob][build.bazel.remote.asset.v1.Fetch.FetchBlob]. +message FetchBlobRequest { + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + string instance_name = 1; + + // The timeout for the underlying fetch, if content needs to be retrieved from + // origin. + // + // If unset, the server *MAY* apply an implementation-defined timeout. + // + // If set, and the user-provided timeout exceeds the RPC deadline, the server + // *SHOULD* keep the fetch going after the RPC completes, to be made + // available for future Fetch calls. The server may also enforce (via clamping + // and/or an INVALID_ARGUMENT error) implementation-defined minimum and + // maximum timeout values. + // + // If this timeout is exceeded on an attempt to retrieve content from origin + // the client will receive DEADLINE_EXCEEDED in [FetchBlobResponse.status]. + google.protobuf.Duration timeout = 2; + + // The oldest content the client is willing to accept, as measured from the + // time it was Push'd or when the underlying retrieval from origin was + // started. + // Upon retries of Fetch requests that cannot be completed within a single + // RPC, clients *SHOULD* provide the same value for subsequent requests as the + // original, to simplify combining the request with the previous attempt. + // + // If unset, the client *SHOULD* accept content of any age. + google.protobuf.Timestamp oldest_content_accepted = 3; + + // The URI(s) of the content to fetch. These may be resources that the server + // can directly fetch from origin, in which case multiple URIs *SHOULD* + // represent the same content available at different locations (such as an + // origin and secondary mirrors). These may also be URIs for content known to + // the server through other mechanisms, e.g. pushed via the [Push][build.bazel.remote.asset.v1.Push] + // service. + // + // Clients *MUST* supply at least one URI. Servers *MAY* match any one of the + // supplied URIs. + repeated string uris = 4; + + // Qualifiers sub-specifying the content to fetch - see comments on + // [Qualifier][build.bazel.remote.asset.v1.Qualifier]. + // The same qualifiers apply to all URIs. + // + // Specified qualifier names *MUST* be unique. + repeated Qualifier qualifiers = 5; + + // The digest function the server must use to compute the digest. + // + // If unset, the server SHOULD default to SHA256. + build.bazel.remote.execution.v2.DigestFunction.Value digest_function = 6; +} + +// A response message for +// [Fetch.FetchBlob][build.bazel.remote.asset.v1.Fetch.FetchBlob]. +message FetchBlobResponse { + // If the status has a code other than `OK`, it indicates that the operation + // was unable to be completed for reasons outside the servers' control. + // The possible fetch errors include: + // * `DEADLINE_EXCEEDED`: The operation could not be completed within the + // specified timeout. + // * `NOT_FOUND`: The requested asset was not found at the specified location. + // * `PERMISSION_DENIED`: The request was rejected by a remote server, or + // requested an asset from a disallowed origin. + // * `ABORTED`: The operation could not be completed, typically due to a + // failed consistency check. + // * `RESOURCE_EXHAUSTED`: There is insufficient quota of some resource to + // perform the requested operation. The client may retry after a delay. + google.rpc.Status status = 1; + + // The uri from the request that resulted in a successful retrieval, or from + // which the error indicated in `status` was obtained. + string uri = 2; + + // Any qualifiers known to the server and of interest to clients. + repeated Qualifier qualifiers = 3; + + // A minimum timestamp the content is expected to be available through. + // Servers *MAY* omit this field, if not known with confidence. + google.protobuf.Timestamp expires_at = 4; + + // The result of the fetch, if the status had code `OK`. + // The digest of the file's contents, available for download through the CAS. + build.bazel.remote.execution.v2.Digest blob_digest = 5; + + // This field SHOULD be set to the digest function that was used by the server + // to compute [FetchBlobResponse.blob_digest]. + // Clients could use this to determine whether the server honors + // [FetchBlobRequest.digest_function] that was set in the request. + // + // If unset, clients SHOULD default to use SHA256 regardless of the requested + // [FetchBlobRequest.digest_function]. + build.bazel.remote.execution.v2.DigestFunction.Value digest_function = 6; +} + +// A request message for +// [Fetch.FetchDirectory][build.bazel.remote.asset.v1.Fetch.FetchDirectory]. +message FetchDirectoryRequest { + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + string instance_name = 1; + + // The timeout for the underlying fetch, if content needs to be retrieved from + // origin. This value is allowed to exceed the RPC deadline, in which case the + // server *SHOULD* keep the fetch going after the RPC completes, to be made + // available for future Fetch calls. + // + // If this timeout is exceeded on an attempt to retrieve content from origin + // the client will receive DEADLINE_EXCEEDED in [FetchDirectoryResponse.status]. + google.protobuf.Duration timeout = 2; + + // The oldest content the client is willing to accept, as measured from the + // time it was Push'd or when the underlying retrieval from origin was + // started. + // Upon retries of Fetch requests that cannot be completed within a single + // RPC, clients *SHOULD* provide the same value for subsequent requests as the + // original, to simplify combining the request with the previous attempt. + // + // If unset, the client *SHOULD* accept content of any age. + google.protobuf.Timestamp oldest_content_accepted = 3; + + // The URI(s) of the content to fetch. These may be resources that the server + // can directly fetch from origin, in which case multiple URIs *SHOULD* + // represent the same content available at different locations (such as an + // origin and secondary mirrors). These may also be URIs for content known to + // the server through other mechanisms, e.g. pushed via the [Push][build.bazel.remote.asset.v1.Push] + // service. + // + // Clients *MUST* supply at least one URI. Servers *MAY* match any one of the + // supplied URIs. + repeated string uris = 4; + + // Qualifiers sub-specifying the content to fetch - see comments on + // [Qualifier][build.bazel.remote.asset.v1.Qualifier]. + // The same qualifiers apply to all URIs. + // + // Specified qualifier names *MUST* be unique. + repeated Qualifier qualifiers = 5; + + // The digest function the server must use to compute the digest. + // + // If unset, the server SHOULD default to SHA256. + build.bazel.remote.execution.v2.DigestFunction.Value digest_function = 6; +} + +// A response message for +// [Fetch.FetchDirectory][build.bazel.remote.asset.v1.Fetch.FetchDirectory]. +message FetchDirectoryResponse { + // If the status has a code other than `OK`, it indicates that the operation + // was unable to be completed for reasons outside the servers' control. + // The possible fetch errors include: + // * `DEADLINE_EXCEEDED`: The operation could not be completed within the + // specified timeout. + // * `NOT_FOUND`: The requested asset was not found at the specified location. + // * `PERMISSION_DENIED`: The request was rejected by a remote server, or + // requested an asset from a disallowed origin. + // * `ABORTED`: The operation could not be completed, typically due to a + // failed consistency check. + // * `RESOURCE_EXHAUSTED`: There is insufficient quota of some resource to + // perform the requested operation. The client may retry after a delay. + google.rpc.Status status = 1; + + // The uri from the request that resulted in a successful retrieval, or from + // which the error indicated in `status` was obtained. + string uri = 2; + + // Any qualifiers known to the server and of interest to clients. + repeated Qualifier qualifiers = 3; + + // A minimum timestamp the content is expected to be available through. + // Servers *MAY* omit this field, if not known with confidence. + google.protobuf.Timestamp expires_at = 4; + + // The result of the fetch, if the status had code `OK`. + // the root digest of a directory tree, suitable for fetching via + // [ContentAddressableStorage.GetTree]. + build.bazel.remote.execution.v2.Digest root_directory_digest = 5; + + // This field SHOULD be set to the digest function that was used by the server + // to compute [FetchBlobResponse.root_directory_digest]. + // Clients could use this to determine whether the server honors + // [FetchDirectoryRequest.digest_function] that was set in the request. + // + // If unset, clients SHOULD default to use SHA256 regardless of the requested + // [FetchDirectoryRequest.digest_function]. + build.bazel.remote.execution.v2.DigestFunction.Value digest_function = 6; +} + +// The Push service is complementary to the Fetch, and allows for +// associating contents of URLs to be returned in future Fetch API calls. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +service Push { + // These APIs associate the identifying information of a resource, as + // indicated by URI and optionally Qualifiers, with content available in the + // CAS. For example, associating a repository url and a commit id with a + // Directory Digest. + // + // Servers *SHOULD* only allow trusted clients to associate content, and *MAY* + // only allow certain URIs to be pushed. + // + // Clients *MUST* ensure associated content is available in CAS prior to + // pushing. + // + // Clients *MUST* ensure the Qualifiers listed correctly match the contents, + // and Servers *MAY* trust these values without validation. + // Fetch servers *MAY* require exact match of all qualifiers when returning + // content previously pushed, or allow fetching content with only a subset of + // the qualifiers specified on Push. + // + // Clients can specify expiration information that the server *SHOULD* + // respect. Subsequent requests can be used to alter the expiration time. + // + // A minimal compliant Fetch implementation may support only Push'd content + // and return `NOT_FOUND` for any resource that was not pushed first. + // Alternatively, a compliant implementation may choose to not support Push + // and only return resources that can be Fetch'd from origin. + // + // Errors will be returned as gRPC Status errors. + // The possible RPC errors include: + // * `INVALID_ARGUMENT`: One or more arguments to the RPC were invalid. + // * `RESOURCE_EXHAUSTED`: There is insufficient quota of some resource to + // perform the requested operation. The client may retry after a delay. + // * `UNAVAILABLE`: Due to a transient condition the operation could not be + // completed. The client should retry. + // * `INTERNAL`: An internal error occurred while performing the operation. + // The client should retry. + rpc PushBlob(PushBlobRequest) returns (PushBlobResponse) { + option (google.api.http) = { post: "/v1/{instance_name=**}/assets:pushBlob" body: "*" }; + } + + rpc PushDirectory(PushDirectoryRequest) returns (PushDirectoryResponse) { + option (google.api.http) = { post: "/v1/{instance_name=**}/assets:pushDirectory" body: "*" }; + } +} + +// A request message for +// [Push.PushBlob][build.bazel.remote.asset.v1.Push.PushBlob]. +message PushBlobRequest { + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + string instance_name = 1; + + // The URI(s) of the content to associate. If multiple URIs are specified, the + // pushed content will be available to fetch by specifying any of them. + repeated string uris = 2; + + // Qualifiers sub-specifying the content that is being pushed - see comments + // on [Qualifier][build.bazel.remote.asset.v1.Qualifier]. + // The same qualifiers apply to all URIs. + repeated Qualifier qualifiers = 3; + + // A time after which this content should stop being returned via [FetchBlob][build.bazel.remote.asset.v1.Fetch.FetchBlob]. + // Servers *MAY* expire content early, e.g. due to storage pressure. + google.protobuf.Timestamp expire_at = 4; + + // The blob to associate. + build.bazel.remote.execution.v2.Digest blob_digest = 5; + + // Referenced blobs or directories that need to not expire before expiration + // of this association, in addition to `blob_digest` itself. + // These fields are hints - clients *MAY* omit them, and servers *SHOULD* + // respect them, at the risk of increased incidents of Fetch responses + // indirectly referencing unavailable blobs. + repeated build.bazel.remote.execution.v2.Digest references_blobs = 6; + repeated build.bazel.remote.execution.v2.Digest references_directories = 7; + + // The digest function that was used to compute the blob digest. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the action digest hash and the digest functions announced + // in the server's capabilities. + build.bazel.remote.execution.v2.DigestFunction.Value digest_function = 8; +} + +// A response message for +// [Push.PushBlob][build.bazel.remote.asset.v1.Push.PushBlob]. +message PushBlobResponse { /* empty */ } + +// A request message for +// [Push.PushDirectory][build.bazel.remote.asset.v1.Push.PushDirectory]. +message PushDirectoryRequest { + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + string instance_name = 1; + + // The URI(s) of the content to associate. If multiple URIs are specified, the + // pushed content will be available to fetch by specifying any of them. + repeated string uris = 2; + + // Qualifiers sub-specifying the content that is being pushed - see comments + // on [Qualifier][build.bazel.remote.asset.v1.Qualifier]. + // The same qualifiers apply to all URIs. + repeated Qualifier qualifiers = 3; + + // A time after which this content should stop being returned via + // [FetchDirectory][build.bazel.remote.asset.v1.Fetch.FetchDirectory]. + // Servers *MAY* expire content early, e.g. due to storage pressure. + google.protobuf.Timestamp expire_at = 4; + + // Directory to associate + build.bazel.remote.execution.v2.Digest root_directory_digest = 5; + + // Referenced blobs or directories that need to not expire before expiration + // of this association, in addition to `root_directory_digest` itself. + // These fields are hints - clients *MAY* omit them, and servers *SHOULD* + // respect them, at the risk of increased incidents of Fetch responses + // indirectly referencing unavailable blobs. + repeated build.bazel.remote.execution.v2.Digest references_blobs = 6; + repeated build.bazel.remote.execution.v2.Digest references_directories = 7; + + // The digest function that was used to compute blob digests. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the action digest hash and the digest functions announced + // in the server's capabilities. + build.bazel.remote.execution.v2.DigestFunction.Value digest_function = 8; +} + +// A response message for +// [Push.PushDirectory][build.bazel.remote.asset.v1.Push.PushDirectory]. +message PushDirectoryResponse { /* empty */ } diff --git a/proto/build/bazel/remote/execution/v2/remote_execution.proto b/proto/build/bazel/remote/execution/v2/remote_execution.proto new file mode 100644 index 0000000..e9cab05 --- /dev/null +++ b/proto/build/bazel/remote/execution/v2/remote_execution.proto @@ -0,0 +1,2511 @@ +// Copyright 2018 The Bazel Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package build.bazel.remote.execution.v2; + +import "build/bazel/semver/semver.proto"; +import "google/api/annotations.proto"; +import "google/longrunning/operations.proto"; +import "google/protobuf/any.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; +import "google/protobuf/wrappers.proto"; +import "google/rpc/status.proto"; + +option csharp_namespace = "Build.Bazel.Remote.Execution.V2"; +option go_package = "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2;remoteexecution"; +option java_multiple_files = true; +option java_outer_classname = "RemoteExecutionProto"; +option java_package = "build.bazel.remote.execution.v2"; +option objc_class_prefix = "REX"; + + +// The Remote Execution API is used to execute an +// [Action][build.bazel.remote.execution.v2.Action] on the remote +// workers. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +service Execution { + // Execute an action remotely. + // + // In order to execute an action, the client must first upload all of the + // inputs, the + // [Command][build.bazel.remote.execution.v2.Command] to run, and the + // [Action][build.bazel.remote.execution.v2.Action] into the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + // It then calls `Execute` with an `action_digest` referring to them. The + // server will run the action and eventually return the result. + // + // The input `Action`'s fields MUST meet the various canonicalization + // requirements specified in the documentation for their types so that it has + // the same digest as other logically equivalent `Action`s. The server MAY + // enforce the requirements and return errors if a non-canonical input is + // received. It MAY also proceed without verifying some or all of the + // requirements, such as for performance reasons. If the server does not + // verify the requirement, then it will treat the `Action` as distinct from + // another logically equivalent action if they hash differently. + // + // Returns a stream of + // [google.longrunning.Operation][google.longrunning.Operation] messages + // describing the resulting execution, with eventual `response` + // [ExecuteResponse][build.bazel.remote.execution.v2.ExecuteResponse]. The + // `metadata` on the operation is of type + // [ExecuteOperationMetadata][build.bazel.remote.execution.v2.ExecuteOperationMetadata]. + // + // If the client remains connected after the first response is returned after + // the server, then updates are streamed as if the client had called + // [WaitExecution][build.bazel.remote.execution.v2.Execution.WaitExecution] + // until the execution completes or the request reaches an error. The + // operation can also be queried using [Operations + // API][google.longrunning.Operations.GetOperation]. + // + // The server NEED NOT implement other methods or functionality of the + // Operations API. + // + // Errors discovered during creation of the `Operation` will be reported + // as gRPC Status errors, while errors that occurred while running the + // action will be reported in the `status` field of the `ExecuteResponse`. The + // server MUST NOT set the `error` field of the `Operation` proto. + // The possible errors include: + // + // * `INVALID_ARGUMENT`: One or more arguments are invalid. + // * `FAILED_PRECONDITION`: One or more errors occurred in setting up the + // action requested, such as a missing input or command or no worker being + // available. The client may be able to fix the errors and retry. + // * `RESOURCE_EXHAUSTED`: There is insufficient quota of some resource to run + // the action. + // * `UNAVAILABLE`: Due to a transient condition, such as all workers being + // occupied (and the server does not support a queue), the action could not + // be started. The client should retry. + // * `INTERNAL`: An internal error occurred in the execution engine or the + // worker. + // * `DEADLINE_EXCEEDED`: The execution timed out. + // * `CANCELLED`: The operation was cancelled by the client. This status is + // only possible if the server implements the Operations API CancelOperation + // method, and it was called for the current execution. + // + // In the case of a missing input or command, the server SHOULD additionally + // send a [PreconditionFailure][google.rpc.PreconditionFailure] error detail + // where, for each requested blob not present in the CAS, there is a + // `Violation` with a `type` of `MISSING` and a `subject` of + // `"blobs/{digest_function/}{hash}/{size}"` indicating the digest of the + // missing blob. The `subject` is formatted the same way as the + // `resource_name` provided to + // [ByteStream.Read][google.bytestream.ByteStream.Read], with the leading + // instance name omitted. `digest_function` MUST thus be omitted if its value + // is one of MD5, MURMUR3, SHA1, SHA256, SHA384, SHA512, or VSO. + // + // The server does not need to guarantee that a call to this method leads to + // at most one execution of the action. The server MAY execute the action + // multiple times, potentially in parallel. These redundant executions MAY + // continue to run, even if the operation is completed. + rpc Execute(ExecuteRequest) returns (stream google.longrunning.Operation) { + option (google.api.http) = { post: "/v2/{instance_name=**}/actions:execute" body: "*" }; + } + + // Wait for an execution operation to complete. When the client initially + // makes the request, the server immediately responds with the current status + // of the execution. The server will leave the request stream open until the + // operation completes, and then respond with the completed operation. The + // server MAY choose to stream additional updates as execution progresses, + // such as to provide an update as to the state of the execution. + // + // In addition to the cases described for Execute, the WaitExecution method + // may fail as follows: + // + // * `NOT_FOUND`: The operation no longer exists due to any of a transient + // condition, an unknown operation name, or if the server implements the + // Operations API DeleteOperation method and it was called for the current + // execution. The client should call `Execute` to retry. + rpc WaitExecution(WaitExecutionRequest) returns (stream google.longrunning.Operation) { + option (google.api.http) = { post: "/v2/{name=operations/**}:waitExecution" body: "*" }; + } +} + +// The action cache API is used to query whether a given action has already been +// performed and, if so, retrieve its result. Unlike the +// [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage], +// which addresses blobs by their own content, the action cache addresses the +// [ActionResult][build.bazel.remote.execution.v2.ActionResult] by a +// digest of the encoded [Action][build.bazel.remote.execution.v2.Action] +// which produced them. +// +// The lifetime of entries in the action cache is implementation-specific, but +// the server SHOULD assume that more recently used entries are more likely to +// be used again. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +service ActionCache { + // Retrieve a cached execution result. + // + // Implementations SHOULD ensure that any blobs referenced from the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage] + // are available at the time of returning the + // [ActionResult][build.bazel.remote.execution.v2.ActionResult] and will be + // for some period of time afterwards. The lifetimes of the referenced blobs SHOULD be increased + // if necessary and applicable. + // + // Errors: + // + // * `NOT_FOUND`: The requested `ActionResult` is not in the cache. + rpc GetActionResult(GetActionResultRequest) returns (ActionResult) { + option (google.api.http) = { get: "/v2/{instance_name=**}/actionResults/{action_digest.hash}/{action_digest.size_bytes}" }; + } + + // Upload a new execution result. + // + // In order to allow the server to perform access control based on the type of + // action, and to assist with client debugging, the client MUST first upload + // the [Action][build.bazel.remote.execution.v2.Action] that produced the + // result, along with its + // [Command][build.bazel.remote.execution.v2.Command], into the + // `ContentAddressableStorage`. + // + // Server implementations MAY modify the + // `UpdateActionResultRequest.action_result` and return an equivalent value. + // + // Errors: + // + // * `INVALID_ARGUMENT`: One or more arguments are invalid. + // * `FAILED_PRECONDITION`: One or more errors occurred in updating the + // action result, such as a missing command or action. + // * `RESOURCE_EXHAUSTED`: There is insufficient storage space to add the + // entry to the cache. + rpc UpdateActionResult(UpdateActionResultRequest) returns (ActionResult) { + option (google.api.http) = { put: "/v2/{instance_name=**}/actionResults/{action_digest.hash}/{action_digest.size_bytes}" body: "action_result" }; + } +} + +// The CAS (content-addressable storage) is used to store the inputs to and +// outputs from the execution service. Each piece of content is addressed by the +// digest of its binary data. +// +// Most of the binary data stored in the CAS is opaque to the execution engine, +// and is only used as a communication medium. In order to build an +// [Action][build.bazel.remote.execution.v2.Action], +// however, the client will need to also upload the +// [Command][build.bazel.remote.execution.v2.Command] and input root +// [Directory][build.bazel.remote.execution.v2.Directory] for the Action. +// The Command and Directory messages must be marshalled to wire format and then +// uploaded under the hash as with any other piece of content. In practice, the +// input root directory is likely to refer to other Directories in its +// hierarchy, which must also each be uploaded on their own. +// +// For small file uploads the client should group them together and call +// [BatchUpdateBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchUpdateBlobs]. +// +// For large uploads, the client must use the +// [Write method][google.bytestream.ByteStream.Write] of the ByteStream API. +// +// For uncompressed data, the `WriteRequest.resource_name` is of the following form: +// `{instance_name}/uploads/{uuid}/blobs/{digest_function/}{hash}/{size}{/optional_metadata}` +// +// Where: +// * `instance_name` is an identifier used to distinguish between the various +// instances on the server. Syntax and semantics of this field are defined +// by the server; Clients must not make any assumptions about it (e.g., +// whether it spans multiple path segments or not). If it is the empty path, +// the leading slash is omitted, so that the `resource_name` becomes +// `uploads/{uuid}/blobs/{digest_function/}{hash}/{size}{/optional_metadata}`. +// To simplify parsing, a path segment cannot equal any of the following +// keywords: `blobs`, `uploads`, `actions`, `actionResults`, `operations`, +// `capabilities` or `compressed-blobs`. +// * `uuid` is a version 4 UUID generated by the client, used to avoid +// collisions between concurrent uploads of the same data. Clients MAY +// reuse the same `uuid` for uploading different blobs. +// * `digest_function` is a lowercase string form of a `DigestFunction.Value` +// enum, indicating which digest function was used to compute `hash`. If the +// digest function used is one of MD5, MURMUR3, SHA1, SHA256, SHA384, SHA512, +// or VSO, this component MUST be omitted. In that case the server SHOULD +// infer the digest function using the length of the `hash` and the digest +// functions announced in the server's capabilities. +// * `hash` and `size` refer to the [Digest][build.bazel.remote.execution.v2.Digest] +// of the data being uploaded. +// * `optional_metadata` is implementation specific data, which clients MAY omit. +// Servers MAY ignore this metadata. +// +// Data can alternatively be uploaded in compressed form, with the following +// `WriteRequest.resource_name` form: +// `{instance_name}/uploads/{uuid}/compressed-blobs/{compressor}/{digest_function/}{uncompressed_hash}/{uncompressed_size}{/optional_metadata}` +// +// Where: +// * `instance_name`, `uuid`, `digest_function` and `optional_metadata` are +// defined as above. +// * `compressor` is a lowercase string form of a `Compressor.Value` enum +// other than `identity`, which is supported by the server and advertised in +// [CacheCapabilities.supported_compressors][build.bazel.remote.execution.v2.CacheCapabilities.supported_compressors]. +// * `uncompressed_hash` and `uncompressed_size` refer to the +// [Digest][build.bazel.remote.execution.v2.Digest] of the data being +// uploaded, once uncompressed. Servers MUST verify that these match +// the uploaded data once uncompressed, and MUST return an +// `INVALID_ARGUMENT` error in the case of mismatch. +// +// Note that when writing compressed blobs, the `WriteRequest.write_offset` in +// the initial request in a stream refers to the offset in the uncompressed form +// of the blob. In subsequent requests, `WriteRequest.write_offset` MUST be the +// sum of the first request's 'WriteRequest.write_offset' and the total size of +// all the compressed data bundles in the previous requests. +// Note that this mixes an uncompressed offset with a compressed byte length, +// which is nonsensical, but it is done to fit the semantics of the existing +// ByteStream protocol. +// +// Uploads of the same data MAY occur concurrently in any form, compressed or +// uncompressed. +// +// Clients SHOULD NOT use gRPC-level compression for ByteStream API `Write` +// calls of compressed blobs, since this would compress already-compressed data. +// +// When attempting an upload, if another client has already completed the upload +// (which may occur in the middle of a single upload if another client uploads +// the same blob concurrently), the request will terminate immediately without +// error, and with a response whose `committed_size` is the value `-1` if this +// is a compressed upload, or with the full size of the uploaded file if this is +// an uncompressed upload (regardless of how much data was transmitted by the +// client). If the client completes the upload but the +// [Digest][build.bazel.remote.execution.v2.Digest] does not match, an +// `INVALID_ARGUMENT` error will be returned. In either case, the client should +// not attempt to retry the upload. +// +// Small downloads can be grouped and requested in a batch via +// [BatchReadBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchReadBlobs]. +// +// For large downloads, the client must use the +// [Read method][google.bytestream.ByteStream.Read] of the ByteStream API. +// +// For uncompressed data, the `ReadRequest.resource_name` is of the following form: +// `{instance_name}/blobs/{digest_function/}{hash}/{size}` +// Where `instance_name`, `digest_function`, `hash` and `size` are defined as +// for uploads. +// +// Data can alternatively be downloaded in compressed form, with the following +// `ReadRequest.resource_name` form: +// `{instance_name}/compressed-blobs/{compressor}/{digest_function/}{uncompressed_hash}/{uncompressed_size}` +// +// Where: +// * `instance_name`, `compressor` and `digest_function` are defined as for +// uploads. +// * `uncompressed_hash` and `uncompressed_size` refer to the +// [Digest][build.bazel.remote.execution.v2.Digest] of the data being +// downloaded, once uncompressed. Clients MUST verify that these match +// the downloaded data once uncompressed, and take appropriate steps in +// the case of failure such as retrying a limited number of times or +// surfacing an error to the user. +// +// When downloading compressed blobs: +// * `ReadRequest.read_offset` refers to the offset in the uncompressed form +// of the blob. +// * Servers MUST return `INVALID_ARGUMENT` if `ReadRequest.read_limit` is +// non-zero. +// * Servers MAY use any compression level they choose, including different +// levels for different blobs (e.g. choosing a level designed for maximum +// speed for data known to be incompressible). +// * Clients SHOULD NOT use gRPC-level compression, since this would compress +// already-compressed data. +// +// Servers MUST be able to provide data for all recently advertised blobs in +// each of the compression formats that the server supports, as well as in +// uncompressed form. +// +// Additionally, ByteStream requests MAY come with an additional plain text header +// that indicates the `resource_name` of the blob being sent. The header, if +// present, MUST follow the following convention: +// * name: `build.bazel.remote.execution.v2.resource-name`. +// * contents: the plain text resource_name of the request message. +// If set, the contents of the header MUST match the `resource_name` of the request +// message. Servers MAY use this header to assist in routing requests to the +// appropriate backend. +// +// The lifetime of entries in the CAS is implementation specific, but it SHOULD +// be long enough to allow for newly-added and recently looked-up entries to be +// used in subsequent calls (e.g. to +// [Execute][build.bazel.remote.execution.v2.Execution.Execute]). +// +// Servers MUST behave as though empty blobs are always available, even if they +// have not been uploaded. Clients MAY optimize away the uploading or +// downloading of empty blobs. +// +// As with other services in the Remote Execution API, any call may return an +// error with a [RetryInfo][google.rpc.RetryInfo] error detail providing +// information about when the client should retry the request; clients SHOULD +// respect the information provided. +service ContentAddressableStorage { + // Determine if blobs are present in the CAS. + // + // Clients can use this API before uploading blobs to determine which ones are + // already present in the CAS and do not need to be uploaded again. + // + // Servers SHOULD increase the lifetimes of the referenced blobs if necessary and + // applicable. + // + // There are no method-specific errors. + rpc FindMissingBlobs(FindMissingBlobsRequest) returns (FindMissingBlobsResponse) { + option (google.api.http) = { post: "/v2/{instance_name=**}/blobs:findMissing" body: "*" }; + } + + // Upload many blobs at once. + // + // The server may enforce a limit of the combined total size of blobs + // to be uploaded using this API. This limit may be obtained using the + // [Capabilities][build.bazel.remote.execution.v2.Capabilities] API. + // Requests exceeding the limit should either be split into smaller + // chunks or uploaded using the + // [ByteStream API][google.bytestream.ByteStream], as appropriate. + // + // This request is equivalent to calling a Bytestream `Write` request + // on each individual blob, in parallel. The requests may succeed or fail + // independently. + // + // Errors: + // + // * `INVALID_ARGUMENT`: The client attempted to upload more than the + // server supported limit. + // + // Individual requests may return the following errors, additionally: + // + // * `RESOURCE_EXHAUSTED`: There is insufficient disk quota to store the blob. + // * `INVALID_ARGUMENT`: The + // [Digest][build.bazel.remote.execution.v2.Digest] does not match the + // provided data. + rpc BatchUpdateBlobs(BatchUpdateBlobsRequest) returns (BatchUpdateBlobsResponse) { + option (google.api.http) = { post: "/v2/{instance_name=**}/blobs:batchUpdate" body: "*" }; + } + + // Download many blobs at once. + // + // The server may enforce a limit of the combined total size of blobs + // to be downloaded using this API. This limit may be obtained using the + // [Capabilities][build.bazel.remote.execution.v2.Capabilities] API. + // Requests exceeding the limit should either be split into smaller + // chunks or downloaded using the + // [ByteStream API][google.bytestream.ByteStream], as appropriate. + // + // This request is equivalent to calling a Bytestream `Read` request + // on each individual blob, in parallel. The requests may succeed or fail + // independently. + // + // Errors: + // + // * `INVALID_ARGUMENT`: The client attempted to read more than the + // server supported limit. + // + // Every error on individual read will be returned in the corresponding digest + // status. + rpc BatchReadBlobs(BatchReadBlobsRequest) returns (BatchReadBlobsResponse) { + option (google.api.http) = { post: "/v2/{instance_name=**}/blobs:batchRead" body: "*" }; + } + + // Fetch the entire directory tree rooted at a node. + // + // This request must be targeted at a + // [Directory][build.bazel.remote.execution.v2.Directory] stored in the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage] + // (CAS). The server will enumerate the `Directory` tree recursively and + // return every node descended from the root. + // + // The GetTreeRequest.page_token parameter can be used to skip ahead in + // the stream (e.g. when retrying a partially completed and aborted request), + // by setting it to a value taken from GetTreeResponse.next_page_token of the + // last successfully processed GetTreeResponse). + // + // The exact traversal order is unspecified and, unless retrieving subsequent + // pages from an earlier request, is not guaranteed to be stable across + // multiple invocations of `GetTree`. + // + // If part of the tree is missing from the CAS, the server will return the + // portion present and omit the rest. + // + // Errors: + // + // * `NOT_FOUND`: The requested tree root is not present in the CAS. + rpc GetTree(GetTreeRequest) returns (stream GetTreeResponse) { + option (google.api.http) = { get: "/v2/{instance_name=**}/blobs/{root_digest.hash}/{root_digest.size_bytes}:getTree" }; + } + + // SplitBlob retrieves information about how a blob is split into chunks. + // + // This call returns information about how a blob is split into chunks, and + // returns a list of the chunk digests. Using the returned list of chunk digests, + // a client can check which chunks are locally available and only fetch the + // missing ones. The desired blob can be assembled by concatenating the fetched + // chunks in the order of the digests in the list. The chunks SHOULD all be + // available in the CAS. + // + // This API can be used to reduce the required data to download a large blob + // from CAS if some chunks from similar blobs are locally available. For this + // procedure to work properly, blobs SHOULD be split in a content-defined way, + // rather than with fixed-sized chunking. + // + // If a split request is answered successfully, a client can expect the + // following guarantees from the server: + // 1. The blob chunks are stored in CAS. + // 2. Concatenating the blob chunks in the order of the digest list returned + // by the server results in the original blob. + // + // Servers which implement this functionality MUST declare that they support + // it by setting the + // [CacheCapabilities.split_blob_support][build.bazel.remote.execution.v2.CacheCapabilities.split_blob_support] + // field accordingly. + // + // Clients MUST check that the server supports this capability, before using + // it. + // + // Clients SHOULD verify that the digest of the blob assembled by the fetched + // chunks is equal to the requested blob digest. + // + // The lifetimes of the generated chunk blobs MAY be independent of the + // lifetime of the original blob. In particular: + // * A blob and any chunk derived from it MAY be evicted from the CAS at + // different times. + // * A call to [SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob] + // extends the lifetime of the original blob, and sets the lifetimes of + // the resulting chunks (or extends the lifetimes of already-existing + // chunks). + // * Touching a chunk extends its lifetime, but the server MAY choose not + // to extend the lifetime of the original blob. + // * Touching the original blob extends its lifetime, but the server MAY + // choose not to extend the lifetimes of chunks derived from it. + // + // When blob splitting and splicing is used at the same time, the clients and + // the server SHOULD agree out-of-band upon a chunking algorithm used by both + // parties to benefit from each other's chunk data and avoid unnecessary data + // duplication. + // + // Errors: + // + // * `NOT_FOUND`: The requested blob is not present in the CAS, OR there is no + // split information available for the blob, OR at least one chunk needed to + // reconstruct the blob is missing from the CAS. + // * `RESOURCE_EXHAUSTED`: There is insufficient disk quota to store the blob + // chunks. + rpc SplitBlob(SplitBlobRequest) returns (SplitBlobResponse) { + option (google.api.http) = { get: "/v2/{instance_name=**}/blobs/{blob_digest.hash}/{blob_digest.size_bytes}:splitBlob" }; + } + + // SpliceBlob tells the CAS how chunks can compose a blob. + // + // This is the complementary operation to the + // [ContentAddressableStorage.SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob] + // function to handle the chunked upload of large blobs to save upload + // traffic. + // + // When uploading a large blob using chunked upload, clients MUST first upload + // all chunks to the CAS, then call this RPC to tell the server how those chunks + // compose the original blob. The chunks referenced in the SpliceBlob call SHOULD be + // available in the CAS before calling this RPC. + // + // If a client needs to upload a large blob and is able to split a blob into + // chunks in such a way that reusable chunks are obtained, e.g., by means of + // content-defined chunking, it can first determine which parts of the blob + // are already available in the remote CAS and upload the missing chunks, and + // then use this API to store information on how the chunks compose the + // original blob. + // + // Servers which implement this functionality MUST declare that they support + // it by setting the + // [CacheCapabilities.splice_blob_support][build.bazel.remote.execution.v2.CacheCapabilities.splice_blob_support] + // field accordingly. + // + // Clients MUST check that the server supports this capability, before using + // it. + // + // In order to ensure data consistency of the CAS, the server MUST only add + // blobs to the CAS after verifying their digests. In particular, servers MUST NOT + // trust digests provided by the client. The server MAY accept a request as no-op + // if the client-specified blob is already in CAS or if information on how to + // construct the blob from chunks is available. If the client-specified blob is + // not already in the CAS, the server MUST verify that the digest of the newly + // created blob assembled from chunks matches the digest specified by the + // client, and reject the request if they differ. Servers MAY choose to allow + // overwriting existing chunk mappings or to store multiple chunk mappings for + // the same blob. + // + // When blob splitting and splicing is used at the same time, the clients and + // the server SHOULD agree out-of-band upon a chunking algorithm used by both + // parties to benefit from each other's chunk data and avoid unnecessary data + // duplication. + // + // Errors: + // + // * `NOT_FOUND`: At least one of the blob chunks is not present in the CAS. + // * `RESOURCE_EXHAUSTED`: There is insufficient disk quota to store the + // spliced blob. + // * `INVALID_ARGUMENT`: The digest of the spliced blob is different from the + // provided expected digest. + // * `ALREADY_EXISTS`: The blob already exists in CAS and the server did not + // extend the lifetime of the chunks specified in the request, e.g. because + // it prefers a different chunking and extended those instead. Clients can + // call [SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob] + // to check what chunk mapping the server is using. + rpc SpliceBlob(SpliceBlobRequest) returns (SpliceBlobResponse) { + option (google.api.http) = { post: "/v2/{instance_name=**}/blobs:spliceBlob" body: "*" }; + } +} + +// The Capabilities service may be used by remote execution clients to query +// various server properties, in order to self-configure or return meaningful +// error messages. +// +// The query may include a particular `instance_name`, in which case the values +// returned will pertain to that instance. +service Capabilities { + // GetCapabilities returns the server capabilities configuration of the + // remote endpoint. + // Only the capabilities of the services supported by the endpoint will + // be returned: + // * Execution + CAS + Action Cache endpoints should return both + // CacheCapabilities and ExecutionCapabilities. + // * Execution only endpoints should return ExecutionCapabilities. + // * CAS + Action Cache only endpoints should return CacheCapabilities. + // + // There are no method-specific errors. + rpc GetCapabilities(GetCapabilitiesRequest) returns (ServerCapabilities) { + option (google.api.http) = { + get: "/v2/{instance_name=**}/capabilities" + }; + } +} + +// An `Action` captures all the information about an execution which is required +// to reproduce it. +// +// `Action`s are the core component of the [Execution] service. A single +// `Action` represents a repeatable action that can be performed by the +// execution service. `Action`s can be succinctly identified by the digest of +// their wire format encoding and, once an `Action` has been executed, will be +// cached in the action cache. Future requests can then use the cached result +// rather than needing to run afresh. +// +// When a server completes execution of an +// [Action][build.bazel.remote.execution.v2.Action], it MAY choose to +// cache the [result][build.bazel.remote.execution.v2.ActionResult] in +// the [ActionCache][build.bazel.remote.execution.v2.ActionCache] unless +// `do_not_cache` is `true`. Clients SHOULD expect the server to do so. By +// default, future calls to +// [Execute][build.bazel.remote.execution.v2.Execution.Execute] the same +// `Action` will also serve their results from the cache. Clients must take care +// to understand the caching behaviour. Ideally, all `Action`s will be +// reproducible so that serving a result from cache is always desirable and +// correct. +message Action { + // The digest of the [Command][build.bazel.remote.execution.v2.Command] + // to run, which MUST be present in the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + Digest command_digest = 1; + + // The digest of the root + // [Directory][build.bazel.remote.execution.v2.Directory] for the input + // files. The files in the directory tree are available in the correct + // location on the build machine before the command is executed. The root + // directory, as well as every subdirectory and content blob referred to, MUST + // be in the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + Digest input_root_digest = 2; + + reserved 3 to 5; // Used for fields moved to [Command][build.bazel.remote.execution.v2.Command]. + + // A timeout after which the execution should be killed. If the timeout is + // absent, then the client is specifying that the execution should continue + // as long as the server will let it. The server SHOULD impose a timeout if + // the client does not specify one, however, if the client does specify a + // timeout that is longer than the server's maximum timeout, the server MUST + // reject the request. + // + // The timeout is only intended to cover the "execution" of the specified + // action and not time in queue nor any overheads before or after execution + // such as marshalling inputs/outputs. The server SHOULD avoid including time + // spent the client doesn't have control over, and MAY extend or reduce the + // timeout to account for delays or speedups that occur during execution + // itself (e.g., lazily loading data from the Content Addressable Storage, + // live migration of virtual machines, emulation overhead). + // + // The timeout is a part of the + // [Action][build.bazel.remote.execution.v2.Action] message, and + // therefore two `Actions` with different timeouts are different, even if they + // are otherwise identical. This is because, if they were not, running an + // `Action` with a lower timeout than is required might result in a cache hit + // from an execution run with a longer timeout, hiding the fact that the + // timeout is too short. By encoding it directly in the `Action`, a lower + // timeout will result in a cache miss and the execution timeout will fail + // immediately, rather than whenever the cache entry gets evicted. + google.protobuf.Duration timeout = 6; + + // If true, then the `Action`'s result cannot be cached, and in-flight + // requests for the same `Action` may not be merged. + bool do_not_cache = 7; + + reserved 8; // Used for field moved to [Command][build.bazel.remote.execution.v2.Command]. + + // An optional additional salt value used to place this `Action` into a + // separate cache namespace from other instances having the same field + // contents. This salt typically comes from operational configuration + // specific to sources such as repo and service configuration, + // and allows disowning an entire set of ActionResults that might have been + // poisoned by buggy software or tool failures. + bytes salt = 9; + + // The optional platform requirements for the execution environment. The + // server MAY choose to execute the action on any worker satisfying the + // requirements, so the client SHOULD ensure that running the action on any + // such worker will have the same result. A detailed lexicon for this can be + // found in the accompanying platform.md. + // New in version 2.2: clients SHOULD set these platform properties as well + // as those in the [Command][build.bazel.remote.execution.v2.Command]. Servers + // SHOULD prefer those set here. + Platform platform = 10; +} + +// A `Command` is the actual command executed by a worker running an +// [Action][build.bazel.remote.execution.v2.Action] and specifications of its +// environment. +// +// Except as otherwise required, the environment (such as which system +// libraries or binaries are available, and what filesystems are mounted where) +// is defined by and specific to the implementation of the remote execution API. +message Command { + // An `EnvironmentVariable` is one variable to set in the running program's + // environment. + message EnvironmentVariable { + // The variable name. + string name = 1; + + // The variable value. + string value = 2; + } + + // The arguments to the command. + // + // The first argument specifies the command to run, which may be either an + // absolute path, a path relative to the working directory, or an unqualified + // path (without path separators) which will be resolved using the operating + // system's equivalent of the PATH environment variable. Path separators + // native to the operating system running on the worker SHOULD be used. If the + // `environment_variables` list contains an entry for the PATH environment + // variable, it SHOULD be respected. If not, the resolution process is + // implementation-defined. + // + // Changed in v2.3. v2.2 and older require that no PATH lookups are performed, + // and that relative paths are resolved relative to the input root. This + // behavior can, however, not be relied upon, as most implementations already + // followed the rules described above. + repeated string arguments = 1; + + // The environment variables to set when running the program. The worker may + // provide its own default environment variables; these defaults can be + // overridden using this field. Additional variables can also be specified. + // + // In order to ensure that equivalent + // [Command][build.bazel.remote.execution.v2.Command]s always hash to the same + // value, the environment variables MUST be lexicographically sorted by name. + // Sorting of strings is done by code point, equivalently, by the UTF-8 bytes. + repeated EnvironmentVariable environment_variables = 2; + + // A list of the output files that the client expects to retrieve from the + // action. Only the listed files, as well as directories listed in + // `output_directories`, will be returned to the client as output. + // Other files or directories that may be created during command execution + // are discarded. + // + // The paths are relative to the working directory of the action execution. + // The paths are specified using a single forward slash (`/`) as a path + // separator, even if the execution platform natively uses a different + // separator. The path MUST NOT include a trailing slash, nor a leading slash, + // being a relative path. + // + // In order to ensure consistent hashing of the same Action, the output paths + // MUST be sorted lexicographically by code point (or, equivalently, by UTF-8 + // bytes). + // + // An output file cannot be duplicated, be a parent of another output file, or + // have the same path as any of the listed output directories. + // + // Directories leading up to the output files are created by the worker prior + // to execution, even if they are not explicitly part of the input root. + // + // DEPRECATED since v2.1: Use `output_paths` instead. + repeated string output_files = 3 [ deprecated = true ]; + + // A list of the output directories that the client expects to retrieve from + // the action. Only the listed directories will be returned (an entire + // directory structure will be returned as a + // [Tree][build.bazel.remote.execution.v2.Tree] message digest, see + // [OutputDirectory][build.bazel.remote.execution.v2.OutputDirectory]), as + // well as files listed in `output_files`. Other files or directories that + // may be created during command execution are discarded. + // + // The paths are relative to the working directory of the action execution. + // The paths are specified using a single forward slash (`/`) as a path + // separator, even if the execution platform natively uses a different + // separator. The path MUST NOT include a trailing slash, nor a leading slash, + // being a relative path. The special value of empty string is allowed, + // although not recommended, and can be used to capture the entire working + // directory tree, including inputs. + // + // In order to ensure consistent hashing of the same Action, the output paths + // MUST be sorted lexicographically by code point (or, equivalently, by UTF-8 + // bytes). + // + // An output directory cannot be duplicated or have the same path as any of + // the listed output files. An output directory is allowed to be a parent of + // another output directory. + // + // Directories leading up to the output directories (but not the output + // directories themselves) are created by the worker prior to execution, even + // if they are not explicitly part of the input root. + // + // DEPRECATED since 2.1: Use `output_paths` instead. + repeated string output_directories = 4 [ deprecated = true ]; + + // A list of the output paths that the client expects to retrieve from the + // action. Only the listed paths will be returned to the client as output. + // The type of the output (file or directory) is not specified, and will be + // determined by the server after action execution. If the resulting path is + // a file, it will be returned in an + // [OutputFile][build.bazel.remote.execution.v2.OutputFile] typed field. + // If the path is a directory, the entire directory structure will be returned + // as a [Tree][build.bazel.remote.execution.v2.Tree] message digest, see + // [OutputDirectory][build.bazel.remote.execution.v2.OutputDirectory] + // Other files or directories that may be created during command execution + // are discarded. + // + // The paths are relative to the working directory of the action execution. + // The paths are specified using a single forward slash (`/`) as a path + // separator, even if the execution platform natively uses a different + // separator. The path MUST NOT include a trailing slash, nor a leading slash, + // being a relative path. + // + // In order to ensure consistent hashing of the same Action, the output paths + // MUST be deduplicated and sorted lexicographically by code point (or, + // equivalently, by UTF-8 bytes). + // + // Directories leading up to the output paths are created by the worker prior + // to execution, even if they are not explicitly part of the input root. + // + // New in v2.1: this field supersedes the DEPRECATED `output_files` and + // `output_directories` fields. If `output_paths` is used, `output_files` and + // `output_directories` will be ignored! + repeated string output_paths = 7; + + // The platform requirements for the execution environment. The server MAY + // choose to execute the action on any worker satisfying the requirements, so + // the client SHOULD ensure that running the action on any such worker will + // have the same result. A detailed lexicon for this can be found in the + // accompanying platform.md. + // DEPRECATED as of v2.2: platform properties are now specified directly in + // the action. See documentation note in the + // [Action][build.bazel.remote.execution.v2.Action] for migration. + Platform platform = 5 [ deprecated = true ]; + + // The working directory, relative to the input root, for the command to run + // in. It must be a directory which exists in the input tree. If it is left + // empty, then the action is run in the input root. + string working_directory = 6; + + // A list of keys for node properties the client expects to retrieve for + // output files and directories. Keys are either names of string-based + // [NodeProperty][build.bazel.remote.execution.v2.NodeProperty] or + // names of fields in [NodeProperties][build.bazel.remote.execution.v2.NodeProperties]. + // In order to ensure that equivalent `Action`s always hash to the same + // value, the node properties MUST be lexicographically sorted by name. + // Sorting of strings is done by code point, equivalently, by the UTF-8 bytes. + // + // The interpretation of string-based properties is server-dependent. If a + // property is not recognized by the server, the server will return an + // `INVALID_ARGUMENT`. + repeated string output_node_properties = 8; + + enum OutputDirectoryFormat { + // The client is only interested in receiving output directories in + // the form of a single Tree object, using the `tree_digest` field. + TREE_ONLY = 0; + + // The client is only interested in receiving output directories in + // the form of a hierarchy of separately stored Directory objects, + // using the `root_directory_digest` field. + DIRECTORY_ONLY = 1; + + // The client is interested in receiving output directories both in + // the form of a single Tree object and a hierarchy of separately + // stored Directory objects, using both the `tree_digest` and + // `root_directory_digest` fields. + TREE_AND_DIRECTORY = 2; + } + + // The format that the worker should use to store the contents of + // output directories. + // + // In case this field is set to a value that is not supported by the + // worker, the worker SHOULD interpret this field as TREE_ONLY. The + // worker MAY store output directories in formats that are a superset + // of what was requested (e.g., interpreting DIRECTORY_ONLY as + // TREE_AND_DIRECTORY). + OutputDirectoryFormat output_directory_format = 9; +} + +// A `Platform` is a set of requirements, such as hardware, operating system, or +// compiler toolchain, for an +// [Action][build.bazel.remote.execution.v2.Action]'s execution +// environment. A `Platform` is represented as a series of key-value pairs +// representing the properties that are required of the platform. +message Platform { + // A single property for the environment. The server is responsible for + // specifying the property `name`s that it accepts. If an unknown `name` is + // provided in the requirements for an + // [Action][build.bazel.remote.execution.v2.Action], the server SHOULD + // reject the execution request. If permitted by the server, the same `name` + // may occur multiple times. + // + // The server is also responsible for specifying the interpretation of + // property `value`s. For instance, a property describing how much RAM must be + // available may be interpreted as allowing a worker with 16GB to fulfill a + // request for 8GB, while a property describing the OS environment on which + // the action must be performed may require an exact match with the worker's + // OS. + // + // The server MAY use the `value` of one or more properties to determine how + // it sets up the execution environment, such as by making specific system + // files available to the worker. + // + // Both names and values are typically case-sensitive. Note that the platform + // is implicitly part of the action digest, so even tiny changes in the names + // or values (like changing case) may result in different action cache + // entries. + message Property { + // The property name. + string name = 1; + + // The property value. + string value = 2; + } + + // The properties that make up this platform. In order to ensure that + // equivalent `Platform`s always hash to the same value, the properties MUST + // be lexicographically sorted by name, and then by value. Sorting of strings + // is done by code point, equivalently, by the UTF-8 bytes. + repeated Property properties = 1; +} + +// A `Directory` represents a directory node in a file tree, containing zero or +// more children [FileNodes][build.bazel.remote.execution.v2.FileNode], +// [DirectoryNodes][build.bazel.remote.execution.v2.DirectoryNode] and +// [SymlinkNodes][build.bazel.remote.execution.v2.SymlinkNode]. +// Each `Node` contains its name in the directory, either the digest of its +// content (either a file blob or a `Directory` proto) or a symlink target, as +// well as possibly some metadata about the file or directory. +// +// In order to ensure that two equivalent directory trees hash to the same +// value, the following restrictions MUST be obeyed when constructing +// a `Directory`: +// +// * Every child in the directory must have a path of exactly one segment. +// Multiple levels of directory hierarchy may not be collapsed. +// * Each child in the directory must have a unique path segment (file name). +// Note that while the API itself is case-sensitive, the environment where +// the Action is executed may or may not be case-sensitive. That is, it is +// legal to call the API with a Directory that has both "Foo" and "foo" as +// children, but the Action may be rejected by the remote system upon +// execution. +// * The files, directories and symlinks in the directory must each be sorted +// in lexicographical order by path. The path strings must be sorted by code +// point, equivalently, by UTF-8 bytes. +// * The [NodeProperties][build.bazel.remote.execution.v2.NodeProperty] of files, +// directories, and symlinks must be sorted in lexicographical order by +// property name. +// +// A `Directory` that obeys the restrictions is said to be in canonical form. +// +// As an example, the following could be used for a file named `bar` and a +// directory named `foo` with an executable file named `baz` (hashes shortened +// for readability): +// +// ```json +// // (Directory proto) +// { +// files: [ +// { +// name: "bar", +// digest: { +// hash: "4a73bc9d03...", +// size: 65534 +// }, +// node_properties: [ +// { +// "name": "MTime", +// "value": "2017-01-15T01:30:15.01Z" +// } +// ] +// } +// ], +// directories: [ +// { +// name: "foo", +// digest: { +// hash: "4cf2eda940...", +// size: 43 +// } +// } +// ] +// } +// +// // (Directory proto with hash "4cf2eda940..." and size 43) +// { +// files: [ +// { +// name: "baz", +// digest: { +// hash: "b2c941073e...", +// size: 1294, +// }, +// is_executable: true +// } +// ] +// } +// ``` +message Directory { + // The files in the directory. + repeated FileNode files = 1; + + // The subdirectories in the directory. + repeated DirectoryNode directories = 2; + + // The symlinks in the directory. + repeated SymlinkNode symlinks = 3; + + // The node properties of the Directory. + reserved 4; + NodeProperties node_properties = 5; +} + +// A single property for [FileNodes][build.bazel.remote.execution.v2.FileNode], +// [DirectoryNodes][build.bazel.remote.execution.v2.DirectoryNode], and +// [SymlinkNodes][build.bazel.remote.execution.v2.SymlinkNode]. The server is +// responsible for specifying the property `name`s that it accepts. If +// permitted by the server, the same `name` may occur multiple times. +message NodeProperty { + // The property name. + string name = 1; + + // The property value. + string value = 2; +} + +// Node properties for [FileNodes][build.bazel.remote.execution.v2.FileNode], +// [DirectoryNodes][build.bazel.remote.execution.v2.DirectoryNode], and +// [SymlinkNodes][build.bazel.remote.execution.v2.SymlinkNode]. The server is +// responsible for specifying the properties that it accepts. +// +message NodeProperties { + // A list of string-based + // [NodeProperties][build.bazel.remote.execution.v2.NodeProperty]. + repeated NodeProperty properties = 1; + + // The file's last modification timestamp. + google.protobuf.Timestamp mtime = 2; + + // The UNIX file mode, e.g., 0755. + google.protobuf.UInt32Value unix_mode = 3; +} + +// A `FileNode` represents a single file and associated metadata. +message FileNode { + // The name of the file. + string name = 1; + + // The digest of the file's content. + Digest digest = 2; + + reserved 3; // Reserved to ensure wire-compatibility with `OutputFile`. + + // True if file is executable, false otherwise. + bool is_executable = 4; + + // The node properties of the FileNode. + reserved 5; + NodeProperties node_properties = 6; +} + +// A `DirectoryNode` represents a child of a +// [Directory][build.bazel.remote.execution.v2.Directory] which is itself +// a `Directory` and its associated metadata. +message DirectoryNode { + // The name of the directory. + string name = 1; + + // The digest of the + // [Directory][build.bazel.remote.execution.v2.Directory] object + // represented. See [Digest][build.bazel.remote.execution.v2.Digest] + // for information about how to take the digest of a proto message. + Digest digest = 2; +} + +// A `SymlinkNode` represents a symbolic link. +message SymlinkNode { + // The name of the symlink. + string name = 1; + + // The target path of the symlink. The path separator is a forward slash `/`. + // The target path can be relative to the parent directory of the symlink or + // it can be an absolute path starting with `/`. Support for absolute paths + // can be checked using the [Capabilities][build.bazel.remote.execution.v2.Capabilities] + // API. `..` components are allowed anywhere in the target path as logical + // canonicalization may lead to different behavior in the presence of + // directory symlinks (e.g. `foo/../bar` may not be the same as `bar`). + // To reduce potential cache misses, canonicalization is still recommended + // where this is possible without impacting correctness. + string target = 2; + + // The node properties of the SymlinkNode. + reserved 3; + NodeProperties node_properties = 4; +} + +// A content digest. A digest for a given blob consists of the size of the blob +// and its hash. The hash algorithm to use is defined by the server. +// +// The size is considered to be an integral part of the digest and cannot be +// separated. That is, even if the `hash` field is correctly specified but +// `size_bytes` is not, the server MUST reject the request. +// +// The reason for including the size in the digest is as follows: in a great +// many cases, the server needs to know the size of the blob it is about to work +// with prior to starting an operation with it, such as flattening Merkle tree +// structures or streaming it to a worker. Technically, the server could +// implement a separate metadata store, but this results in a significantly more +// complicated implementation as opposed to having the client specify the size +// up-front (or storing the size along with the digest in every message where +// digests are embedded). This does mean that the API leaks some implementation +// details of (what we consider to be) a reasonable server implementation, but +// we consider this to be a worthwhile tradeoff. +// +// When a `Digest` is used to refer to a proto message, it always refers to the +// message in binary encoded form. To ensure consistent hashing, clients and +// servers MUST ensure that they serialize messages according to the following +// rules, even if there are alternate valid encodings for the same message: +// +// * Fields are serialized in tag order. +// * There are no unknown fields. +// * There are no duplicate fields. +// * Fields are serialized according to the default semantics for their type. +// +// Most protocol buffer implementations will always follow these rules when +// serializing, but care should be taken to avoid shortcuts. For instance, +// concatenating two messages to merge them may produce duplicate fields. +message Digest { + // The hash, represented as a lowercase hexadecimal string, padded with + // leading zeroes up to the hash function length. + string hash = 1; + + // The size of the blob, in bytes. + int64 size_bytes = 2; +} + +// ExecutedActionMetadata contains details about a completed execution. +message ExecutedActionMetadata { + // The name of the worker which ran the execution. + string worker = 1; + + // When was the action added to the queue. + google.protobuf.Timestamp queued_timestamp = 2; + + // When the worker received the action. + google.protobuf.Timestamp worker_start_timestamp = 3; + + // When the worker completed the action, including all stages. + google.protobuf.Timestamp worker_completed_timestamp = 4; + + // When the worker started fetching action inputs. + google.protobuf.Timestamp input_fetch_start_timestamp = 5; + + // When the worker finished fetching action inputs. + google.protobuf.Timestamp input_fetch_completed_timestamp = 6; + + // When the worker started executing the action command. + google.protobuf.Timestamp execution_start_timestamp = 7; + + // When the worker completed executing the action command. + google.protobuf.Timestamp execution_completed_timestamp = 8; + + // New in v2.3: the amount of time the worker spent executing the action + // command, potentially computed using a worker-specific virtual clock. + // + // The virtual execution duration is only intended to cover the "execution" of + // the specified action and not time in queue nor any overheads before or + // after execution such as marshalling inputs/outputs. The server SHOULD avoid + // including time spent the client doesn't have control over, and MAY extend + // or reduce the execution duration to account for delays or speedups that + // occur during execution itself (e.g., lazily loading data from the Content + // Addressable Storage, live migration of virtual machines, emulation + // overhead). + // + // The method of timekeeping used to compute the virtual execution duration + // MUST be consistent with what is used to enforce the + // [Action][build.bazel.remote.execution.v2.Action]'s `timeout`. There is no + // relationship between the virtual execution duration and the values of + // `execution_start_timestamp` and `execution_completed_timestamp`. + google.protobuf.Duration virtual_execution_duration = 12; + + // When the worker started uploading action outputs. + google.protobuf.Timestamp output_upload_start_timestamp = 9; + + // When the worker finished uploading action outputs. + google.protobuf.Timestamp output_upload_completed_timestamp = 10; + + // Details that are specific to the kind of worker used. For example, + // on POSIX-like systems this could contain a message with + // getrusage(2) statistics. + repeated google.protobuf.Any auxiliary_metadata = 11; +} + +// An ActionResult represents the result of an +// [Action][build.bazel.remote.execution.v2.Action] being run. +// +// It is advised that at least one field (for example +// `ActionResult.execution_metadata.Worker`) have a non-default value, to +// ensure that the serialized value is non-empty, which can then be used +// as a basic data sanity check. +message ActionResult { + reserved 1; // Reserved for use as the resource name. + + // The output files of the action. For each output file requested in the + // `output_files` or `output_paths` field of the Action, if the corresponding + // file existed after the action completed, a single entry will be present + // either in this field, or the `output_file_symlinks` field if the file was + // a symbolic link to another file (`output_symlinks` field after v2.1). + // + // If an output listed in `output_files` was found, but was a directory rather + // than a regular file, the server will return a FAILED_PRECONDITION. + // If the action does not produce the requested output, then that output + // will be omitted from the list. The server is free to arrange the output + // list as desired; clients MUST NOT assume that the output list is sorted. + repeated OutputFile output_files = 2; + + // The output files of the action that are symbolic links to other files. Those + // may be links to other output files, or input files, or even absolute paths + // outside of the working directory, if the server supports + // [SymlinkAbsolutePathStrategy.ALLOWED][build.bazel.remote.execution.v2.CacheCapabilities.SymlinkAbsolutePathStrategy]. + // For each output file requested in the `output_files` or `output_paths` + // field of the Action, if the corresponding file existed after + // the action completed, a single entry will be present either in this field, + // or in the `output_files` field, if the file was not a symbolic link. + // + // If an output symbolic link of the same name as listed in `output_files` of + // the Command was found, but its target type was not a regular file, the + // server will return a FAILED_PRECONDITION. + // If the action does not produce the requested output, then that output + // will be omitted from the list. The server is free to arrange the output + // list as desired; clients MUST NOT assume that the output list is sorted. + // + // DEPRECATED as of v2.1. Servers that wish to be compatible with v2.0 API + // should still populate this field in addition to `output_symlinks`. + repeated OutputSymlink output_file_symlinks = 10 [ deprecated = true ]; + + // New in v2.1: this field will only be populated if the command + // `output_paths` field was used, and not the pre v2.1 `output_files` or + // `output_directories` fields. + // The output paths of the action that are symbolic links to other paths. Those + // may be links to other outputs, or inputs, or even absolute paths + // outside of the working directory, if the server supports + // [SymlinkAbsolutePathStrategy.ALLOWED][build.bazel.remote.execution.v2.CacheCapabilities.SymlinkAbsolutePathStrategy]. + // A single entry for each output requested in `output_paths` + // field of the Action, if the corresponding path existed after + // the action completed and was a symbolic link. + // + // If the action does not produce a requested output, then that output + // will be omitted from the list. The server is free to arrange the output + // list as desired; clients MUST NOT assume that the output list is sorted. + repeated OutputSymlink output_symlinks = 12; + + // The output directories of the action. For each output directory requested + // in the `output_directories` or `output_paths` field of the Action, if the + // corresponding directory existed after the action completed, a single entry + // will be present in the output list, which will contain the digest of a + // [Tree][build.bazel.remote.execution.v2.Tree] message containing the + // directory tree, and the path equal exactly to the corresponding Action + // output_directories member. + // + // As an example, suppose the Action had an output directory `a/b/dir` and the + // execution produced the following contents in `a/b/dir`: a file named `bar` + // and a directory named `foo` with an executable file named `baz`. Then, + // output_directory will contain (hashes shortened for readability): + // + // ```json + // // OutputDirectory proto: + // { + // path: "a/b/dir" + // tree_digest: { + // hash: "4a73bc9d03...", + // size: 55 + // } + // } + // // Tree proto with hash "4a73bc9d03..." and size 55: + // { + // root: { + // files: [ + // { + // name: "bar", + // digest: { + // hash: "4a73bc9d03...", + // size: 65534 + // } + // } + // ], + // directories: [ + // { + // name: "foo", + // digest: { + // hash: "4cf2eda940...", + // size: 43 + // } + // } + // ] + // } + // children : { + // // (Directory proto with hash "4cf2eda940..." and size 43) + // files: [ + // { + // name: "baz", + // digest: { + // hash: "b2c941073e...", + // size: 1294, + // }, + // is_executable: true + // } + // ] + // } + // } + // ``` + // If an output of the same name as listed in `output_files` of + // the Command was found in `output_directories`, but was not a directory, the + // server will return a FAILED_PRECONDITION. + repeated OutputDirectory output_directories = 3; + + // The output directories of the action that are symbolic links to other + // directories. Those may be links to other output directories, or input + // directories, or even absolute paths outside of the working directory, + // if the server supports + // [SymlinkAbsolutePathStrategy.ALLOWED][build.bazel.remote.execution.v2.CacheCapabilities.SymlinkAbsolutePathStrategy]. + // For each output directory requested in the `output_directories` field of + // the Action, if the directory existed after the action completed, a + // single entry will be present either in this field, or in the + // `output_directories` field, if the directory was not a symbolic link. + // + // If an output of the same name was found, but was a symbolic link to a file + // instead of a directory, the server will return a FAILED_PRECONDITION. + // If the action does not produce the requested output, then that output + // will be omitted from the list. The server is free to arrange the output + // list as desired; clients MUST NOT assume that the output list is sorted. + // + // DEPRECATED as of v2.1. Servers that wish to be compatible with v2.0 API + // should still populate this field in addition to `output_symlinks`. + repeated OutputSymlink output_directory_symlinks = 11 [ deprecated = true ]; + + // The exit code of the command. + int32 exit_code = 4; + + // The standard output buffer of the action. The server SHOULD NOT inline + // stdout unless requested by the client in the + // [GetActionResultRequest][build.bazel.remote.execution.v2.GetActionResultRequest] + // message. The server MAY omit inlining, even if requested, and MUST do so if inlining + // would cause the response to exceed message size limits. + // Clients SHOULD NOT populate this field when uploading to the cache. + bytes stdout_raw = 5; + + // The digest for a blob containing the standard output of the action, which + // can be retrieved from the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + Digest stdout_digest = 6; + + // The standard error buffer of the action. The server SHOULD NOT inline + // stderr unless requested by the client in the + // [GetActionResultRequest][build.bazel.remote.execution.v2.GetActionResultRequest] + // message. The server MAY omit inlining, even if requested, and MUST do so if inlining + // would cause the response to exceed message size limits. + // Clients SHOULD NOT populate this field when uploading to the cache. + bytes stderr_raw = 7; + + // The digest for a blob containing the standard error of the action, which + // can be retrieved from the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + Digest stderr_digest = 8; + + // The details of the execution that originally produced this result. + ExecutedActionMetadata execution_metadata = 9; +} + +// An `OutputFile` is similar to a +// [FileNode][build.bazel.remote.execution.v2.FileNode], but it is used as an +// output in an `ActionResult`. It allows a full file path rather than +// only a name. +message OutputFile { + // The full path of the file relative to the working directory, including the + // filename. The path separator is a forward slash `/`. Since this is a + // relative path, it MUST NOT begin with a leading forward slash. + string path = 1; + + // The digest of the file's content. + Digest digest = 2; + + reserved 3; // Used for a removed field in an earlier version of the API. + + // True if file is executable, false otherwise. + bool is_executable = 4; + + // The contents of the file if inlining was requested. The server SHOULD NOT inline + // file contents unless requested by the client in the + // [GetActionResultRequest][build.bazel.remote.execution.v2.GetActionResultRequest] + // message. The server MAY omit inlining, even if requested, and MUST do so if inlining + // would cause the response to exceed message size limits. + // Clients SHOULD NOT populate this field when uploading to the cache. + bytes contents = 5; + + // The supported node properties of the OutputFile, if requested by the Action. + reserved 6; + NodeProperties node_properties = 7; +} + +// A `Tree` contains all the +// [Directory][build.bazel.remote.execution.v2.Directory] protos in a +// single directory Merkle tree, compressed into one message. +message Tree { + // The root directory in the tree. + Directory root = 1; + + // All the child directories: the directories referred to by the root and, + // recursively, all its children. In order to reconstruct the directory tree, + // the client must take the digests of each of the child directories and then + // build up a tree starting from the `root`. + // Servers SHOULD ensure that these are ordered consistently such that two + // actions producing equivalent output directories on the same server + // implementation also produce Tree messages with matching digests. + repeated Directory children = 2; +} + +// An `OutputDirectory` is the output in an `ActionResult` corresponding to a +// directory's full contents rather than a single file. +message OutputDirectory { + // The full path of the directory relative to the working directory. The path + // separator is a forward slash `/`. Since this is a relative path, it MUST + // NOT begin with a leading forward slash. The empty string value is allowed, + // and it denotes the entire working directory. + string path = 1; + + reserved 2; // Used for a removed field in an earlier version of the API. + + // The digest of the encoded + // [Tree][build.bazel.remote.execution.v2.Tree] proto containing the + // directory's contents. + Digest tree_digest = 3; + + // If set, consumers MAY make the following assumptions about the + // directories contained in the Tree, so that it may be + // instantiated on a local file system by scanning through it + // sequentially: + // + // - All directories with the same binary representation are stored + // exactly once. + // - All directories, apart from the root directory, are referenced by + // at least one parent directory. + // - Directories are stored in topological order, with parents being + // stored before the child. The root directory is thus the first to + // be stored. + // + // Additionally, the Tree MUST be encoded as a stream of records, + // where each record has the following format: + // + // - A tag byte, having one of the following two values: + // - (1 << 3) | 2 == 0x0a: First record (the root directory). + // - (2 << 3) | 2 == 0x12: Any subsequent records (child directories). + // - The size of the directory, encoded as a base 128 varint. + // - The contents of the directory, encoded as a binary serialized + // Protobuf message. + // + // This encoding is a subset of the Protobuf wire format of the Tree + // message. As it is only permitted to store data associated with + // field numbers 1 and 2, the tag MUST be encoded as a single byte. + // More details on the Protobuf wire format can be found here: + // https://developers.google.com/protocol-buffers/docs/encoding + // + // It is recommended that implementations using this feature construct + // Tree objects manually using the specification given above, as + // opposed to using a Protobuf library to marshal a full Tree message. + // As individual Directory messages already need to be marshaled to + // compute their digests, constructing the Tree object manually avoids + // redundant marshaling. + bool is_topologically_sorted = 4; + + // The digest of the encoded + // [Directory][build.bazel.remote.execution.v2.Directory] proto + // containing the contents of the directory's root. + // + // If both `tree_digest` and `root_directory_digest` are set, this + // field MUST match the digest of the root directory contained in the + // Tree message. + Digest root_directory_digest = 5; +} + +// An `OutputSymlink` is similar to a +// [Symlink][build.bazel.remote.execution.v2.SymlinkNode], but it is used as an +// output in an `ActionResult`. +// +// `OutputSymlink` is binary-compatible with `SymlinkNode`. +message OutputSymlink { + // The full path of the symlink relative to the working directory, including the + // filename. The path separator is a forward slash `/`. Since this is a + // relative path, it MUST NOT begin with a leading forward slash. + string path = 1; + + // The target path of the symlink. The path separator is a forward slash `/`. + // The target path can be relative to the parent directory of the symlink or + // it can be an absolute path starting with `/`. Support for absolute paths + // can be checked using the [Capabilities][build.bazel.remote.execution.v2.Capabilities] + // API. `..` components are allowed anywhere in the target path. + string target = 2; + + // The supported node properties of the OutputSymlink, if requested by the + // Action. + reserved 3; + NodeProperties node_properties = 4; +} + +// An `ExecutionPolicy` can be used to control the scheduling of the action. +message ExecutionPolicy { + // The priority (relative importance) of this action. Generally, a lower value + // means that the action should be run sooner than actions having a greater + // priority value, but the interpretation of a given value is server- + // dependent. A priority of 0 means the *default* priority. Priorities may be + // positive or negative, and such actions should run later or sooner than + // actions having the default priority, respectively. The particular semantics + // of this field is up to the server. In particular, every server will have + // their own supported range of priorities, and will decide how these map into + // scheduling policy. + int32 priority = 1; +} + +// A `ResultsCachePolicy` is used for fine-grained control over how action +// outputs are stored in the CAS and Action Cache. +message ResultsCachePolicy { + // The priority (relative importance) of this content in the overall cache. + // Generally, a lower value means a longer retention time or other advantage, + // but the interpretation of a given value is server-dependent. A priority of + // 0 means a *default* value, decided by the server. + // + // The particular semantics of this field is up to the server. In particular, + // every server will have their own supported range of priorities, and will + // decide how these map into retention/eviction policy. + int32 priority = 1; +} + +// A request message for +// [Execution.Execute][build.bazel.remote.execution.v2.Execution.Execute]. +message ExecuteRequest { + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + string instance_name = 1; + + // If true, the action will be executed even if its result is already + // present in the [ActionCache][build.bazel.remote.execution.v2.ActionCache]. + // The execution is still allowed to be merged with other in-flight executions + // of the same action, however - semantically, the service MUST only guarantee + // that the results of an execution with this field set were not visible + // before the corresponding execution request was sent. + // Note that actions from execution requests setting this field set are still + // eligible to be entered into the action cache upon completion, and services + // SHOULD overwrite any existing entries that may exist. This allows + // skip_cache_lookup requests to be used as a mechanism for replacing action + // cache entries that reference outputs no longer available or that are + // poisoned in any way. + // If false, the result may be served from the action cache. + bool skip_cache_lookup = 3; + + reserved 2, 4, 5; // Used for removed fields in an earlier version of the API. + + // The digest of the [Action][build.bazel.remote.execution.v2.Action] to + // execute. + Digest action_digest = 6; + + // An optional policy for execution of the action. + // The server will have a default policy if this is not provided. + ExecutionPolicy execution_policy = 7; + + // An optional policy for the results of this execution in the remote cache. + // The server will have a default policy if this is not provided. + // This may be applied to both the ActionResult and the associated blobs. + ResultsCachePolicy results_cache_policy = 8; + + // The digest function that was used to compute the action digest. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the action digest hash and the digest functions announced + // in the server's capabilities. + DigestFunction.Value digest_function = 9; + + // A hint to the server to request inlining stdout in the + // [ActionResult][build.bazel.remote.execution.v2.ActionResult] message. + bool inline_stdout = 10; + + // A hint to the server to request inlining stderr in the + // [ActionResult][build.bazel.remote.execution.v2.ActionResult] message. + bool inline_stderr = 11; + + // A hint to the server to inline the contents of the listed output files. + // Each path needs to exactly match one file path in either `output_paths` or + // `output_files` (DEPRECATED since v2.1) in the + // [Command][build.bazel.remote.execution.v2.Command] message. + repeated string inline_output_files = 12; +} + +// A `LogFile` is a log stored in the CAS. +message LogFile { + // The digest of the log contents. + Digest digest = 1; + + // This is a hint as to the purpose of the log, and is set to true if the log + // is human-readable text that can be usefully displayed to a user, and false + // otherwise. For instance, if a command-line client wishes to print the + // server logs to the terminal for a failed action, this allows it to avoid + // displaying a binary file. + bool human_readable = 2; +} + +// The response message for +// [Execution.Execute][build.bazel.remote.execution.v2.Execution.Execute], +// which will be contained in the [response +// field][google.longrunning.Operation.response] of the +// [Operation][google.longrunning.Operation]. +message ExecuteResponse { + // The result of the action. + ActionResult result = 1; + + // True if the result was served from cache, false if it was executed. + bool cached_result = 2; + + // If the status has a code other than `OK`, it indicates that the action did + // not finish execution. For example, if the operation times out during + // execution, the status will have a `DEADLINE_EXCEEDED` code. Servers MUST + // use this field for errors in execution, rather than the error field on the + // `Operation` object. + // + // If the status code is other than `OK`, then the result MUST NOT be cached. + // For an error status, the `result` field is optional; the server may + // populate the output-, stdout-, and stderr-related fields if it has any + // information available, such as the stdout and stderr of a timed-out action. + google.rpc.Status status = 3; + + // An optional list of additional log outputs the server wishes to provide. A + // server can use this to return execution-specific logs however it wishes. + // This is intended primarily to make it easier for users to debug issues that + // may be outside of the actual job execution, such as by identifying the + // worker executing the action or by providing logs from the worker's setup + // phase. The keys SHOULD be human readable so that a client can display them + // to a user. + map server_logs = 4; + + // Freeform informational message with details on the execution of the action + // that may be displayed to the user upon failure or when requested explicitly. + string message = 5; +} + +// The current stage of action execution. +// +// Even though these stages are numbered according to the order in which +// they generally occur, there is no requirement that the remote +// execution system reports events along this order. For example, an +// operation MAY transition from the EXECUTING stage back to QUEUED +// in case the hardware on which the operation executes fails. +// +// If and only if the remote execution system reports that an operation +// has reached the COMPLETED stage, it MUST set the [done +// field][google.longrunning.Operation.done] of the +// [Operation][google.longrunning.Operation] and terminate the stream. +message ExecutionStage { + enum Value { + // Invalid value. + UNKNOWN = 0; + + // Checking the result against the cache. + CACHE_CHECK = 1; + + // Currently idle, awaiting a free machine to execute. + QUEUED = 2; + + // Currently being executed by a worker. + EXECUTING = 3; + + // Finished execution. + COMPLETED = 4; + } +} + +// Metadata about an ongoing +// [execution][build.bazel.remote.execution.v2.Execution.Execute], which +// will be contained in the [metadata +// field][google.longrunning.Operation.metadata] of the +// [Operation][google.longrunning.Operation]. +message ExecuteOperationMetadata { + // The current stage of execution. + ExecutionStage.Value stage = 1; + + // The digest of the [Action][build.bazel.remote.execution.v2.Action] + // being executed. + Digest action_digest = 2; + + // If set, the client can use this resource name with + // [ByteStream.Read][google.bytestream.ByteStream.Read] to stream the + // standard output from the endpoint hosting streamed responses. + string stdout_stream_name = 3; + + // If set, the client can use this resource name with + // [ByteStream.Read][google.bytestream.ByteStream.Read] to stream the + // standard error from the endpoint hosting streamed responses. + string stderr_stream_name = 4; + + // The client can read this field to view details about the ongoing + // execution. + ExecutedActionMetadata partial_execution_metadata = 5; + + // The digest function that was used to compute the action digest. + // + // If the digest function used is one of BLAKE3, MD5, MURMUR3, SHA1, + // SHA256, SHA256TREE, SHA384, SHA512, or VSO, the server MAY leave + // this field unset. In that case the client SHOULD infer the digest + // function using the length of the action digest hash and the digest + // functions announced in the server's capabilities. + DigestFunction.Value digest_function = 6; +} + +// A request message for +// [WaitExecution][build.bazel.remote.execution.v2.Execution.WaitExecution]. +message WaitExecutionRequest { + // The name of the [Operation][google.longrunning.Operation] + // returned by [Execute][build.bazel.remote.execution.v2.Execution.Execute]. + string name = 1; +} + +// A request message for +// [ActionCache.GetActionResult][build.bazel.remote.execution.v2.ActionCache.GetActionResult]. +message GetActionResultRequest { + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + string instance_name = 1; + + // The digest of the [Action][build.bazel.remote.execution.v2.Action] + // whose result is requested. + Digest action_digest = 2; + + // A hint to the server to request inlining stdout in the + // [ActionResult][build.bazel.remote.execution.v2.ActionResult] message. + bool inline_stdout = 3; + + // A hint to the server to request inlining stderr in the + // [ActionResult][build.bazel.remote.execution.v2.ActionResult] message. + bool inline_stderr = 4; + + // A hint to the server to inline the contents of the listed output files. + // Each path needs to exactly match one file path in either `output_paths` or + // `output_files` (DEPRECATED since v2.1) in the + // [Command][build.bazel.remote.execution.v2.Command] message. + repeated string inline_output_files = 5; + + // The digest function that was used to compute the action digest. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the action digest hash and the digest functions announced + // in the server's capabilities. + DigestFunction.Value digest_function = 6; +} + +// A request message for +// [ActionCache.UpdateActionResult][build.bazel.remote.execution.v2.ActionCache.UpdateActionResult]. +message UpdateActionResultRequest { + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + string instance_name = 1; + + // The digest of the [Action][build.bazel.remote.execution.v2.Action] + // whose result is being uploaded. + Digest action_digest = 2; + + // The [ActionResult][build.bazel.remote.execution.v2.ActionResult] + // to store in the cache. + ActionResult action_result = 3; + + // An optional policy for the results of this execution in the remote cache. + // The server will have a default policy if this is not provided. + // This may be applied to both the ActionResult and the associated blobs. + ResultsCachePolicy results_cache_policy = 4; + + // The digest function that was used to compute the action digest. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the action digest hash and the digest functions announced + // in the server's capabilities. + DigestFunction.Value digest_function = 5; +} + +// A request message for +// [ContentAddressableStorage.FindMissingBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.FindMissingBlobs]. +message FindMissingBlobsRequest { + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + string instance_name = 1; + + // A list of the blobs to check. All digests MUST use the same digest + // function. + repeated Digest blob_digests = 2; + + // The digest function of the blobs whose existence is checked. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the blob digest hashes and the digest functions announced + // in the server's capabilities. + DigestFunction.Value digest_function = 3; +} + +// A response message for +// [ContentAddressableStorage.FindMissingBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.FindMissingBlobs]. +message FindMissingBlobsResponse { + // A list of the blobs requested *not* present in the storage. + repeated Digest missing_blob_digests = 2; +} + +// A request message for +// [ContentAddressableStorage.BatchUpdateBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchUpdateBlobs]. +message BatchUpdateBlobsRequest { + // A request corresponding to a single blob that the client wants to upload. + message Request { + // The digest of the blob. This MUST be the digest of `data`. All + // digests MUST use the same digest function. + Digest digest = 1; + + // The raw binary data. + bytes data = 2; + + // The format of `data`. Must be `IDENTITY`/unspecified, or one of the + // compressors advertised by the + // [CacheCapabilities.supported_batch_update_compressors][build.bazel.remote.execution.v2.CacheCapabilities.supported_batch_update_compressors] + // field. + Compressor.Value compressor = 3; + } + + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + string instance_name = 1; + + // The individual upload requests. + repeated Request requests = 2; + + // The digest function that was used to compute the digests of the + // blobs being uploaded. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the blob digest hashes and the digest functions announced + // in the server's capabilities. + DigestFunction.Value digest_function = 5; +} + +// A response message for +// [ContentAddressableStorage.BatchUpdateBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchUpdateBlobs]. +message BatchUpdateBlobsResponse { + // A response corresponding to a single blob that the client tried to upload. + message Response { + // The blob digest to which this response corresponds. + Digest digest = 1; + + // The result of attempting to upload that blob. + google.rpc.Status status = 2; + } + + // The responses to the requests. + repeated Response responses = 1; +} + +// A request message for +// [ContentAddressableStorage.BatchReadBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchReadBlobs]. +message BatchReadBlobsRequest { + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + string instance_name = 1; + + // The individual blob digests. All digests MUST use the same digest + // function. + repeated Digest digests = 2; + + // A list of acceptable encodings for the returned inlined data, in no + // particular order. `IDENTITY` is always allowed even if not specified here. + repeated Compressor.Value acceptable_compressors = 3; + + // The digest function of the blobs being requested. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the blob digest hashes and the digest functions announced + // in the server's capabilities. + DigestFunction.Value digest_function = 4; +} + +// A response message for +// [ContentAddressableStorage.BatchReadBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchReadBlobs]. +message BatchReadBlobsResponse { + // A response corresponding to a single blob that the client tried to download. + message Response { + // The digest to which this response corresponds. + Digest digest = 1; + + // The raw binary data. + bytes data = 2; + + // The format the data is encoded in. MUST be `IDENTITY`/unspecified, + // or one of the acceptable compressors specified in the `BatchReadBlobsRequest`. + Compressor.Value compressor = 4; + + // The result of attempting to download that blob. + google.rpc.Status status = 3; + } + + // The responses to the requests. + repeated Response responses = 1; +} + +// A request message for +// [ContentAddressableStorage.GetTree][build.bazel.remote.execution.v2.ContentAddressableStorage.GetTree]. +message GetTreeRequest { + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + string instance_name = 1; + + // The digest of the root, which must be an encoded + // [Directory][build.bazel.remote.execution.v2.Directory] message + // stored in the + // [ContentAddressableStorage][build.bazel.remote.execution.v2.ContentAddressableStorage]. + Digest root_digest = 2; + + // A maximum page size to request. If present, the server will request no more + // than this many items. Regardless of whether a page size is specified, the + // server may place its own limit on the number of items to be returned and + // require the client to retrieve more items using a subsequent request. + int32 page_size = 3; + + // A page token, which must be a value received in a previous + // [GetTreeResponse][build.bazel.remote.execution.v2.GetTreeResponse]. + // If present, the server will use that token as an offset, returning only + // that page and the ones that succeed it. + string page_token = 4; + + // The digest function that was used to compute the digest of the root + // directory. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the root digest hash and the digest functions announced + // in the server's capabilities. + DigestFunction.Value digest_function = 5; +} + +// A response message for +// [ContentAddressableStorage.GetTree][build.bazel.remote.execution.v2.ContentAddressableStorage.GetTree]. +message GetTreeResponse { + // The directories descended from the requested root. + repeated Directory directories = 1; + + // If present, signifies that there are more results which the client can + // retrieve by passing this as the page_token in a subsequent + // [request][build.bazel.remote.execution.v2.GetTreeRequest]. + // If empty, signifies that this is the last page of results. + string next_page_token = 2; +} + +// A request message for +// [ContentAddressableStorage.SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob]. +message SplitBlobRequest { + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + string instance_name = 1; + + // The digest of the blob to be split. + Digest blob_digest = 2; + + // The digest function of the blob to be split. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, + // SHA384, SHA512, or VSO, the client MAY leave this field unset. In + // that case the server SHOULD infer the digest function using the + // length of the blob digest hashes and the digest functions announced + // in the server's capabilities. + DigestFunction.Value digest_function = 3; + + // The chunking function that the client prefers to use. + // + // The server MAY use a different chunking function. + ChunkingFunction.Value chunking_function = 4; +} + +// A response message for +// [ContentAddressableStorage.SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob]. +message SplitBlobResponse { + // The ordered list of digests of the chunks into which the blob was split. + // The original blob is assembled by concatenating the chunk data according to + // the order of the digests given by this list. + // + // The server MUST use the same digest function as the one explicitly or + // implicitly (through hash length) specified in the split request. + repeated Digest chunk_digests = 1; + + // The chunking function used to split the blob. + ChunkingFunction.Value chunking_function = 2; +} + +// A request message for +// [ContentAddressableStorage.SpliceBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SpliceBlob]. +message SpliceBlobRequest { + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + string instance_name = 1; + + // Expected digest of the spliced blob. The client MUST set this field due + // to the following reasons: + // 1. It allows the server to perform an early existence check of the blob + // or existing chunks that assemble the blob before spending the splicing + // effort, as described in the [ContentAddressableStorage.SpliceBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SpliceBlob] + // documentation. + // 2. It allows servers with different storage backends to dispatch the + // request to the correct storage backend based on the size and/or the + // hash of the blob. + // 3. If chunking information already exists for the blob, it allows + // the server to keep the existing chunking information or replace it with + // new chunking information. + Digest blob_digest = 2; + + // The ordered list of digests of the chunks which need to be concatenated to + // assemble the original blob. + repeated Digest chunk_digests = 3; + + // The digest function of all chunks to be concatenated and of the blob to be + // spliced. The server MUST use the same digest function for both cases. + // + // If the digest function used is one of MD5, MURMUR3, SHA1, SHA256, SHA384, + // SHA512, or VSO, the client MAY leave this field unset. In that case the + // server SHOULD infer the digest function using the length of the blob digest + // hashes and the digest functions announced in the server's capabilities. + DigestFunction.Value digest_function = 4; + + // The chunking function that the client used to split the blob. + ChunkingFunction.Value chunking_function = 5; +} + +// A response message for +// [ContentAddressableStorage.SpliceBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SpliceBlob]. +message SpliceBlobResponse { + // Computed digest of the spliced blob. + // + // The server MUST use the same digest function as the one explicitly or + // implicitly (through hash length) specified in the splice request. + Digest blob_digest = 1; +} + +// A request message for +// [Capabilities.GetCapabilities][build.bazel.remote.execution.v2.Capabilities.GetCapabilities]. +message GetCapabilitiesRequest { + // The instance of the execution system to operate against. A server may + // support multiple instances of the execution system (with their own workers, + // storage, caches, etc.). The server MAY require use of this field to select + // between them in an implementation-defined fashion, otherwise it can be + // omitted. + string instance_name = 1; +} + +// A response message for +// [Capabilities.GetCapabilities][build.bazel.remote.execution.v2.Capabilities.GetCapabilities]. +message ServerCapabilities { + // Capabilities of the remote cache system. + CacheCapabilities cache_capabilities = 1; + + // Capabilities of the remote execution system. + ExecutionCapabilities execution_capabilities = 2; + + // Earliest RE API version supported, including deprecated versions. + build.bazel.semver.SemVer deprecated_api_version = 3; + + // Earliest non-deprecated RE API version supported. + build.bazel.semver.SemVer low_api_version = 4; + + // Latest RE API version supported. + build.bazel.semver.SemVer high_api_version = 5; +} + +// The digest function used for converting values into keys for CAS and Action +// Cache. +message DigestFunction { + enum Value { + // It is an error for the server to return this value. + UNKNOWN = 0; + + // The SHA-256 digest function. + SHA256 = 1; + + // The SHA-1 digest function. + SHA1 = 2; + + // The MD5 digest function. + MD5 = 3; + + // The Microsoft "VSO-Hash" paged SHA256 digest function. + // See https://github.com/microsoft/BuildXL/blob/master/Documentation/Specs/PagedHash.md . + VSO = 4; + + // The SHA-384 digest function. + SHA384 = 5; + + // The SHA-512 digest function. + SHA512 = 6; + + // Murmur3 128-bit digest function, x64 variant. Note that this is not a + // cryptographic hash function and its collision properties are not strongly guaranteed. + // See https://github.com/aappleby/smhasher/wiki/MurmurHash3 . + MURMUR3 = 7; + + // The SHA-256 digest function, modified to use a Merkle tree for + // large objects. This permits implementations to store large blobs + // as a decomposed sequence of 2^j sized chunks, where j >= 10, + // while being able to validate integrity at the chunk level. + // + // Furthermore, on systems that do not offer dedicated instructions + // for computing SHA-256 hashes (e.g., the Intel SHA and ARMv8 + // cryptographic extensions), SHA256TREE hashes can be computed more + // efficiently than plain SHA-256 hashes by using generic SIMD + // extensions, such as Intel AVX2 or ARM NEON. + // + // SHA256TREE hashes are computed as follows: + // + // - For blobs that are 1024 bytes or smaller, the hash is computed + // using the regular SHA-256 digest function. + // + // - For blobs that are more than 1024 bytes in size, the hash is + // computed as follows: + // + // 1. The blob is partitioned into a left (leading) and right + // (trailing) blob. These blobs have lengths m and n + // respectively, where m = 2^k and 0 < n <= m. + // + // 2. Hashes of the left and right blob, Hash(left) and + // Hash(right) respectively, are computed by recursively + // applying the SHA256TREE algorithm. + // + // 3. A single invocation is made to the SHA-256 block cipher with + // the following parameters: + // + // M = Hash(left) || Hash(right) + // H = { + // 0xcbbb9d5d, 0x629a292a, 0x9159015a, 0x152fecd8, + // 0x67332667, 0x8eb44a87, 0xdb0c2e0d, 0x47b5481d, + // } + // + // The values of H are the leading fractional parts of the + // square roots of the 9th to the 16th prime number (23 to 53). + // This differs from plain SHA-256, where the first eight prime + // numbers (2 to 19) are used, thereby preventing trivial hash + // collisions between small and large objects. + // + // 4. The hash of the full blob can then be obtained by + // concatenating the outputs of the block cipher: + // + // Hash(blob) = a || b || c || d || e || f || g || h + // + // Addition of the original values of H, as normally done + // through the use of the Davies-Meyer structure, is not + // performed. This isn't necessary, as the block cipher is only + // invoked once. + // + // Test vectors of this digest function can be found in the + // accompanying sha256tree_test_vectors.txt file. + SHA256TREE = 8; + + // The BLAKE3 hash function. + // See https://github.com/BLAKE3-team/BLAKE3. + BLAKE3 = 9; + + // Identical to SHA1, except that "blob ${sizeBytes}\0" is prepended to + // the blob's contents before hashing, where ${sizeBytes} corresponds to + // the decimal size of the original blob. This allows hashes of files to + // be converted from and to the ones used by the Git version control + // system. + GITSHA1 = 10; + } +} + +// The chunking function is used to split a blob into chunks. +// +// The server advertises support for a chunking function by setting the +// corresponding params field in +// [CacheCapabilities][build.bazel.remote.execution.v2.CacheCapabilities]. +// For example, if fast_cdc_2020_params is set, the server supports FAST_CDC_2020. +// +// For optimal deduplication, clients SHOULD use an advertised chunking function. +// When clients use UNKNOWN, the server chooses an algorithm for SplitBlob and +// simply verifies chunk concatenation for SpliceBlob. +message ChunkingFunction { + enum Value { + // No specific algorithm. Servers MUST always accept this value. + // For SplitBlob, the server chooses the algorithm. For SpliceBlob, the + // server only verifies that chunks concatenate to form the expected blob. + UNKNOWN = 0; + + // The FastCDC chunking algorithm as described in the 2020 paper by + // Wen Xia, et al. See https://ieeexplore.ieee.org/document/9055082 + // for details. + FAST_CDC_2020 = 1; + + // The RepMaxCDC chunking algorithm as implemented by buildbarn/go-cdc. + // See https://github.com/buildbarn/go-cdc for details. + REP_MAX_CDC = 2; + } +} + +// Describes the server/instance capabilities for updating the action cache. +message ActionCacheUpdateCapabilities { + bool update_enabled = 1; +} + +// Allowed values for priority in +// [ResultsCachePolicy][build.bazel.remote.execution.v2.ResultsCachePolicy] and +// [ExecutionPolicy][build.bazel.remote.execution.v2.ExecutionPolicy] +// Used for querying both cache and execution valid priority ranges. +message PriorityCapabilities { + // Supported range of priorities, including boundaries. + message PriorityRange { + // The minimum numeric value for this priority range, which represents the + // most urgent task or longest retained item. + int32 min_priority = 1; + // The maximum numeric value for this priority range, which represents the + // least urgent task or shortest retained item. + int32 max_priority = 2; + } + repeated PriorityRange priorities = 1; +} + +// Describes how the server treats absolute symlink targets. +message SymlinkAbsolutePathStrategy { + enum Value { + // Invalid value. + UNKNOWN = 0; + + // Server will return an `INVALID_ARGUMENT` on input symlinks with absolute + // targets. + // If an action tries to create an output symlink with an absolute target, a + // `FAILED_PRECONDITION` will be returned. + DISALLOWED = 1; + + // Server will allow symlink targets to escape the input root tree, possibly + // resulting in non-hermetic builds. + ALLOWED = 2; + } +} + +// Compression formats which may be supported. +message Compressor { + enum Value { + // No compression. Servers and clients MUST always support this, and do + // not need to advertise it. + IDENTITY = 0; + + // Zstandard compression. + ZSTD = 1; + + // RFC 1951 Deflate. This format is identical to what is used by ZIP + // files. Headers such as the one generated by gzip are not + // included. + // + // It is advised to use algorithms such as Zstandard instead, as + // those are faster and/or provide a better compression ratio. + DEFLATE = 2; + + // Brotli compression. + BROTLI = 3; + } +} + +// Capabilities of the remote cache system. +message CacheCapabilities { + // All the digest functions supported by the remote cache. + // Remote cache may support multiple digest functions simultaneously. + repeated DigestFunction.Value digest_functions = 1; + + // Capabilities for updating the action cache. + ActionCacheUpdateCapabilities action_cache_update_capabilities = 2; + + // Supported cache priority range for both CAS and ActionCache. + PriorityCapabilities cache_priority_capabilities = 3; + + // Maximum total size of blobs to be uploaded/downloaded using + // batch methods. A value of 0 means no limit is set, although + // in practice there will always be a message size limitation + // of the protocol in use, e.g. GRPC. + int64 max_batch_total_size_bytes = 4; + + // Whether absolute symlink targets are supported. + SymlinkAbsolutePathStrategy.Value symlink_absolute_path_strategy = 5; + + // Compressors supported by the "compressed-blobs" bytestream resources. + // Servers MUST support identity/no-compression, even if it is not listed + // here. + // + // Note that this does not imply which if any compressors are supported by + // the server at the gRPC level. + repeated Compressor.Value supported_compressors = 6; + + // Compressors supported for inlined data in + // [BatchUpdateBlobs][build.bazel.remote.execution.v2.ContentAddressableStorage.BatchUpdateBlobs] + // requests. + repeated Compressor.Value supported_batch_update_compressors = 7; + + // The maximum blob size that the server will accept for CAS blob uploads. + // - If it is 0, it means there is no limit set. A client may assume + // arbitrarily large blobs may be uploaded to and downloaded from the cache. + // - If it is larger than 0, implementations SHOULD NOT attempt to upload + // blobs with size larger than the limit. Servers SHOULD reject blob + // uploads over the `max_cas_blob_size_bytes` limit with response code + // `INVALID_ARGUMENT` + // - If the cache implementation returns a given limit, it MAY still serve + // blobs larger than this limit. + int64 max_cas_blob_size_bytes = 8; + + // Whether blob splitting is supported for the particular server/instance. If + // yes, the server/instance implements the specified behavior for blob + // splitting and a meaningful result can be expected from the + // [ContentAddressableStorage.SplitBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SplitBlob] + // operation. + bool split_blob_support = 9; + + // Whether blob splicing is supported for the particular server/instance. If + // yes, the server/instance implements the specified behavior for blob + // splicing and a meaningful result can be expected from the + // [ContentAddressableStorage.SpliceBlob][build.bazel.remote.execution.v2.ContentAddressableStorage.SpliceBlob] + // operation. + bool splice_blob_support = 10; + + // The parameters for the FastCDC 2020 chunking algorithm. + // If set, the server supports the FastCDC chunking algorithm. + FastCdc2020Params fast_cdc_2020_params = 11; + + // The parameters for the RepMaxCDC chunking algorithm. + // If set, the server supports the RepMaxCDC chunking algorithm. + RepMaxCdcParams rep_max_cdc_params = 12; +} + +// Parameters for the FastCDC content-defined chunking algorithm. +// +// Implementations MUST follow the FastCDC 2020 paper by Wen Xia, et al.: +// https://ieeexplore.ieee.org/document/9055082 +// +// Supported implementations: +// - Rust: https://docs.rs/fastcdc/3.2.1/fastcdc/v2020/index.html +// - Go: https://github.com/buildbuddy-io/fastcdc2020 +// +// Test vectors can be found in the accompanying fastcdc2020_test_vectors.txt file. +// +// Implementations MUST use normalization level 2, which has been found +// successful for build artifacts with an average chunk size of 512 KiB. +// +// Key algorithm components from the paper: +// +// GEAR table: 256 64-bit integers for the rolling hash, computed as: +// GEAR[i] = high_64_bits(MD5(byte(i))) for i in 0..255 +// +// MASKS table: Bit patterns for chunk boundary detection, derived from +// the C reference implementation. The mask selection based on average +// chunk size SHOULD match the paper. +// +// The minimum and maximum chunk sizes MUST be derived from the average: +// - min_chunk_size = avg_chunk_size_bytes / 4 +// - max_chunk_size = avg_chunk_size_bytes * 4 +// +// Blobs smaller than max_chunk_size (avg_chunk_size_bytes * 4) SHOULD be +// uploaded without chunking. +// +// If any of the advertised parameters are not within the expected range, +// the client SHOULD ignore FastCDC chunking function support. +message FastCdc2020Params { + // The average (expected) chunk size for the FastCDC chunking algorithm. + // The value MUST be between 1 KiB and 1 MiB. The recommended value is + // 524288 (512 KiB). + uint64 avg_chunk_size_bytes = 1; + + // The seed for the FastCDC mask generation. + // The recommended value is 0. + // + // All clients sharing a cache SHOULD use the same seed to maximize + // chunk reuse. + uint32 seed = 2; +} + +// Parameters for the RepMaxCDC content-defined chunking algorithm. +// +// Supported implementations: +// - Go: https://github.com/buildbarn/go-cdc +// +// Key algorithm components: +// +// GEAR table: 256 64-bit integers for the rolling hash, computed as: +// GEAR[i] = high_64_bits(MD5(byte(i))) for i in 0..255 +// +// The algorithm repeatedly applies chunking until all chunks are in the +// range [min_chunk_size_bytes, 2*min_chunk_size_bytes). Cutting points are +// selected where the Gear rolling hash is maximized within a lookahead +// window of horizon_size_bytes. +// +// If any of the advertised parameters are not within the expected range, +// the client SHOULD ignore RepMaxCDC chunking function support. +message RepMaxCdcParams { + // The minimum chunk size for the RepMaxCDC chunking algorithm. + // The value MUST be at least 64 bytes (the Gear hash window size). + // All chunks will be in the range [min_chunk_size_bytes, 2*min_chunk_size_bytes). + // The recommended value is 262144 (256 KiB). + uint64 min_chunk_size_bytes = 1; + + // The lookahead window for finding optimal cutting points. + // Larger values improve deduplication quality with diminishing returns. + // Setting to 0 produces uniform chunks of min_chunk_size_bytes. + // The recommended value is 8 * min_chunk_size_bytes. + uint64 horizon_size_bytes = 2; +} + +// Capabilities of the remote execution system. +message ExecutionCapabilities { + // Legacy field for indicating which digest function is supported by the + // remote execution system. It MUST be set to a value other than UNKNOWN. + // Implementations should consider the repeated digest_functions field + // first, falling back to this singular field if digest_functions is unset. + DigestFunction.Value digest_function = 1; + + // Whether remote execution is enabled for the particular server/instance. + bool exec_enabled = 2; + + // Supported execution priority range. + PriorityCapabilities execution_priority_capabilities = 3; + + // Supported node properties. + repeated string supported_node_properties = 4; + + // All the digest functions supported by the remote execution system. + // If this field is set, it MUST also contain digest_function. + // + // Even if the remote execution system announces support for multiple + // digest functions, individual execution requests may only reference + // CAS objects using a single digest function. For example, it is not + // permitted to execute actions having both MD5 and SHA-256 hashed + // files in their input root. + // + // The CAS objects referenced by action results generated by the + // remote execution system MUST use the same digest function as the + // one used to construct the action. + repeated DigestFunction.Value digest_functions = 5; +} + +// Details for the tool used to call the API. +message ToolDetails { + // Name of the tool, e.g. bazel. + string tool_name = 1; + + // Version of the tool used for the request, e.g. 5.0.3. + string tool_version = 2; +} + +// An optional Metadata to attach to any RPC request to tell the server about an +// external context of the request. The server may use this for logging or other +// purposes. To use it, the client attaches the header to the call using the +// canonical proto serialization: +// +// * name: `build.bazel.remote.execution.v2.requestmetadata-bin` +// * contents: the base64 encoded binary `RequestMetadata` message. +// Note: the gRPC library serializes binary headers encoded in base64 by +// default (https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests). +// Therefore, if the gRPC library is used to pass/retrieve this +// metadata, the user may ignore the base64 encoding and assume it is simply +// serialized as a binary message. +message RequestMetadata { + // The details for the tool invoking the requests. + ToolDetails tool_details = 1; + + // An identifier that ties multiple requests to the same action. + // For example, multiple requests to the CAS, Action Cache, and Execution + // API are used in order to compile foo.cc. + string action_id = 2; + + // An identifier that ties multiple actions together to a final result. + // For example, multiple actions are required to build and run foo_test. + string tool_invocation_id = 3; + + // An identifier to tie multiple tool invocations together. For example, + // runs of foo_test, bar_test and baz_test on a post-submit of a given patch. + string correlated_invocations_id = 4; + + // A brief description of the kind of action, for example, CppCompile or GoLink. + // There is no standard agreed set of values for this, and they are expected to vary between different client tools. + string action_mnemonic = 5; + + // An identifier for the target which produced this action. + // No guarantees are made around how many actions may relate to a single target. + string target_id = 6; + + // An identifier for the configuration in which the target was built, + // e.g. for differentiating building host tools or different target platforms. + // There is no expectation that this value will have any particular structure, + // or equality across invocations, though some client tools may offer these guarantees. + string configuration_id = 7; +} diff --git a/proto/build/bazel/semver/semver.proto b/proto/build/bazel/semver/semver.proto new file mode 100644 index 0000000..44f83f8 --- /dev/null +++ b/proto/build/bazel/semver/semver.proto @@ -0,0 +1,41 @@ +// Copyright 2018 The Bazel Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package build.bazel.semver; + +option csharp_namespace = "Build.Bazel.Semver"; +option go_package = "github.com/bazelbuild/remote-apis/build/bazel/semver"; +option java_multiple_files = true; +option java_outer_classname = "SemverProto"; +option java_package = "build.bazel.semver"; +option objc_class_prefix = "SMV"; + +// The full version of a given tool. +message SemVer { + // The major version, e.g 10 for 10.2.3. + int32 major = 1; + + // The minor version, e.g. 2 for 10.2.3. + int32 minor = 2; + + // The patch version, e.g 3 for 10.2.3. + int32 patch = 3; + + // The pre-release version. Either this field or major/minor/patch fields + // must be filled. They are mutually exclusive. Pre-release versions are + // assumed to be earlier than any released versions. + string prerelease = 4; +} diff --git a/scripts/build-dist.sh b/scripts/build-dist.sh index 50a85c1..ab78744 100755 --- a/scripts/build-dist.sh +++ b/scripts/build-dist.sh @@ -11,13 +11,28 @@ fi version=${VERSION:-dev} ldflags="-s -w -buildid= -X main.version=$version" -for architecture in amd64 arm64; do - output="$project_dir/dist/cache-server-linux-$architecture" - CGO_ENABLED=0 GOOS=linux GOARCH="$architecture" \ - go build -buildvcs=false -trimpath -ldflags "$ldflags" -o "$output" ./cmd/cache-server - chmod 0755 "$output" +for program in cache-server cache-optimiser; do + for target in linux-amd64 linux-arm64 darwin-arm64 windows-amd64 windows-arm64; do + if [[ "$program" == cache-optimiser && "$target" != linux-* ]]; then + continue + fi + output="$project_dir/dist/$program-$target" + if [[ "$target" == windows-* ]]; then + output+=.exe + fi + CGO_ENABLED=0 GOOS="${target%-*}" GOARCH="${target#*-}" \ + go build -buildvcs=false -trimpath -ldflags "$ldflags" -o "$output" "./cmd/$program" + chmod 0755 "$output" + done done ( cd "$project_dir/dist" - sha256sum cache-server-linux-* > SHA256SUMS + if command -v sha256sum >/dev/null; then + checksum=(sha256sum) + else + checksum=(shasum -a 256) + fi + # Sorted by byte value so the checksum file is reproducible whatever the + # builder's locale. + LC_ALL=C "${checksum[@]}" cache-optimiser-linux-* cache-server-darwin-arm64 cache-server-linux-* cache-server-windows-*.exe > SHA256SUMS ) diff --git a/scripts/generate-proto.sh b/scripts/generate-proto.sh new file mode 100755 index 0000000..f9d982b --- /dev/null +++ b/scripts/generate-proto.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Regenerates internal/proto/gen from the vendored protocol buffer definitions in +# proto/. The generated Go code is committed, so this script only needs to run when +# the definitions or the generator versions change. +# +# Pass --update to also re-download the vendored upstream definitions. + +project_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) + +# Keep protoc_gen_go_version in sync with google.golang.org/protobuf in go.mod and +# grpc_version in sync with google.golang.org/grpc. +buf_version=v1.73.0 +protoc_gen_go_version=v1.36.12 +protoc_gen_go_grpc_version=v1.5.1 + +# bazelbuild/remote-apis tag v2.12.0. +remote_apis_revision=9e084d0e43e717128ee72b5be584a7ba33e8006b +remote_apis_files=( + build/bazel/remote/asset/v1/remote_asset.proto + build/bazel/remote/execution/v2/remote_execution.proto + build/bazel/semver/semver.proto +) + +tool_dir="$project_dir/.tools/bin" +mkdir -p "$tool_dir" + +install_tool() { + local binary=$1 module=$2 + if [[ ! -x "$tool_dir/$binary" ]]; then + echo "installing $module" >&2 + GOBIN="$tool_dir" go install "$module" + fi +} + +install_tool buf "github.com/bufbuild/buf/cmd/buf@$buf_version" +install_tool protoc-gen-go "google.golang.org/protobuf/cmd/protoc-gen-go@$protoc_gen_go_version" +install_tool protoc-gen-go-grpc "google.golang.org/grpc/cmd/protoc-gen-go-grpc@$protoc_gen_go_grpc_version" + +export PATH="$tool_dir:$PATH" + +if [[ "${1:-}" == "--update" ]]; then + for file in "${remote_apis_files[@]}"; do + mkdir -p "$project_dir/proto/$(dirname "$file")" + curl -fsSL -o "$project_dir/proto/$file" \ + "https://raw.githubusercontent.com/bazelbuild/remote-apis/$remote_apis_revision/$file" + done + (cd "$project_dir/proto" && buf dep update) +fi + +cd "$project_dir" +rm -rf internal/proto/gen +buf generate +gofmt -l internal/proto/gen