diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1e4e7ff..2348665 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,7 +32,7 @@ jobs: run: go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 - name: Rebuild packaged binaries env: - VERSION: v0.2.2 + VERSION: v0.3.0 run: scripts/build-dist.sh - name: Verify packaged binaries are reproducible run: git diff --exit-code -- dist diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index eeda1bb..d47a6d3 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -16,6 +16,7 @@ on: permissions: contents: read + actions: read jobs: smoke: @@ -27,7 +28,8 @@ jobs: uses: ./ with: write: ${{ github.event_name == 'push' || inputs.mode == 'seed' }} - key-prefix: bazel-http-smoke-v1 + key-prefix: bazel-http-smoke-car-v1 + storage-mode: packs - name: Prepare stable object id: object shell: bash @@ -57,4 +59,4 @@ jobs: STATS_URL: ${{ steps.cache.outputs.stats-url }} run: | curl --fail-with-body --silent --show-error "$STATS_URL" --output "$RUNNER_TEMP/stats.json" - jq --exit-status '.backend_downloads == 1 and .hits == 1' "$RUNNER_TEMP/stats.json" + jq --exit-status '.backend_downloads == 2 and .pack_downloads == 1 and .hits == 1' "$RUNNER_TEMP/stats.json" diff --git a/.go-version b/.go-version index 8fe00a5..f250c8f 100644 --- a/.go-version +++ b/.go-version @@ -1 +1 @@ -1.26.5 +1.26.6 diff --git a/README.md b/README.md index 210e3c6..ed26468 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,50 @@ For a trusted release or scheduled workflow, set `write: true`. For all untrusted code, keep `write: false` and pass the emitted `writable` value to 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. + +```yaml +permissions: + contents: read + actions: read # manifest discovery for storage-mode: packs + +steps: + - id: bazel-cache + uses: cre4ture/bazel-github-actions-cache-v2@ + 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. + +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. +Manifest discovery is eventually consistent by design: an unseen manifest is +only a temporary miss. + +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. + ### IronMesh example The action can replace the external-cache URL and token in the Bazel job: @@ -84,6 +128,11 @@ Do not enable Bazel remote-cache compression with this release. | `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` | +| `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 | @@ -110,6 +159,8 @@ Supported: - 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 Not currently supported: @@ -121,18 +172,13 @@ Not currently supported: ## Limits and operational model -Every Bazel AC or CAS object is one GitHub Actions cache entry. This is the -simplest correct mapping, but large build graphs can create thousands of small -entries. GitHub documents a limit of 200 cache creations per minute; the action -defaults to 180 evenly spaced uploads and exposes throttle statistics. Duplicate -immutable `PUT`s received by the same server are coalesced before they consume -an upload slot; `deduplicated_uploads` reports those avoided backend saves. If -the remaining unique entries become a bottleneck, object segmentation should be -designed from measurements rather than silently bypassing the limit. - -The proposed next-generation design is documented in -[CARv2 packs and a manifest DAG](docs/carv2-manifest-dag-concept.md). It is not -implemented by this release. +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 +`pack_downloads` make that distinction explicit in the final statistics. 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 @@ -144,11 +190,10 @@ 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. Direct output blobs use cache-entry existence checks -without downloading their contents; `Tree` and recursive `Directory` metadata -must be downloaded so their file references can be checked. One action result -is limited to 100,000 distinct validation operations to bound amplification -from a malformed cache entry. +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 +limited to 100,000 distinct validation operations to bound amplification from a +malformed cache entry. - [GitHub dependency cache reference](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching) - [GitHub cache limits](https://docs.github.com/en/actions/reference/limits#cache-limits) @@ -201,7 +246,7 @@ go vet ./... go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./... go run golang.org/x/vuln/cmd/govulncheck@v1.6.0 ./... node --test action/*.test.js -VERSION=v0.2.2 scripts/build-dist.sh +VERSION=v0.3.0 scripts/build-dist.sh git diff --exit-code -- dist (cd dist && sha256sum --check SHA256SUMS) ``` @@ -210,9 +255,9 @@ 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. -The smoke workflow has two modes. A default-branch push seeds a stable object. -A separate `workflow_dispatch` restore run is required to download that object -on a new runner and asserts `backend_downloads == 1`. +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 +one CARv2 pack on a new runner and asserts the persistent hit statistics. ## License diff --git a/action.yml b/action.yml index f6ad5a9..eaf442d 100644 --- a/action.yml +++ b/action.yml @@ -17,6 +17,26 @@ inputs: description: "Immutable GitHub cache-key namespace; change it to invalidate all 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)" + required: false + default: "8" + pack-flush-seconds: + description: "Maximum seconds that staged CARv2 objects wait before publication" + required: false + default: "30" + max-manifests: + description: "Maximum immutable manifest entries to discover through the GitHub Actions REST API" + required: false + default: "2048" + github-token: + description: "GitHub token with actions: read, used only by storage-mode=packs to discover manifest cache keys" + required: false + default: ${{ github.token }} max-blob-size-mb: description: "Maximum accepted or downloaded AC/CAS object size" required: false diff --git a/action/main.js b/action/main.js index 2957b7e..9c5d5f4 100644 --- a/action/main.js +++ b/action/main.js @@ -54,6 +54,18 @@ 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 packSizeMB = positiveInteger("pack-size-mb", 8, 32); + const packFlushSeconds = positiveInteger("pack-flush-seconds", 30, 3600); + 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) mask(githubToken); const portText = input("port", "0"); const port = Number.parseInt(portText, 10); if (!Number.isSafeInteger(port) || port < 0 || port > 65535) { @@ -77,6 +89,14 @@ async function main() { spoolDir, "--key-prefix", input("key-prefix", "bazel-http-v1"), + "--storage-mode", + storageMode, + "--pack-size", + String(packSizeMB * 1024 * 1024), + "--pack-flush-interval", + `${packFlushSeconds}s`, + "--max-manifests", + String(maxManifests), booleanFlag("write-enabled", writeEnabled), booleanFlag("fail-open", failOpen), "--max-blob-size", @@ -95,7 +115,11 @@ async function main() { const logDescriptor = fs.openSync(logFile, "a", 0o600); const child = spawn(binary, args, { detached: true, - env: { ...process.env, BAZEL_GHA_CACHE_SHUTDOWN_TOKEN: shutdownToken }, + env: { + ...process.env, + BAZEL_GHA_CACHE_SHUTDOWN_TOKEN: shutdownToken, + GITHUB_TOKEN: githubToken || process.env.GITHUB_TOKEN || "", + }, stdio: ["ignore", logDescriptor, logDescriptor], }); fs.closeSync(logDescriptor); @@ -125,6 +149,7 @@ async function main() { 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("stats-url", ready.stats_url); setOutput("writable", String(writeEnabled)); @@ -134,7 +159,7 @@ async function main() { ); setOutput("initial-stats", '{"requests":0,"hits":0,"misses":0,"uploads":0}'); process.stdout.write( - `Bazel cache adapter ready at ${ready.url} (write=${writeEnabled}, fail_open=${failOpen}, pid=${ready.pid})${os.EOL}`, + `Bazel cache adapter ready at ${ready.url} (write=${writeEnabled}, mode=${storageMode}, fail_open=${failOpen}, pid=${ready.pid})${os.EOL}`, ); } diff --git a/action/post.js b/action/post.js index 0ce3c4c..9efabf8 100644 --- a/action/post.js +++ b/action/post.js @@ -21,6 +21,7 @@ async function post() { const statsFile = process.env.STATE_stats_file; const logFile = process.env.STATE_log_file; 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; @@ -39,7 +40,10 @@ async function post() { process.stderr.write(`::warning::cache shutdown request failed: ${error.message}\n`); } - for (let attempt = 0; attempt < 100 && processExists(pid); attempt += 1) { + const shutdownAttempts = Number.isSafeInteger(shutdownWaitSeconds) && shutdownWaitSeconds > 0 + ? shutdownWaitSeconds * 10 + : 3300; + for (let attempt = 0; attempt < shutdownAttempts && processExists(pid); attempt += 1) { await sleep(100); } if (processExists(pid)) { @@ -67,6 +71,11 @@ async function post() { `| 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} |`, diff --git a/cmd/cache-server/main.go b/cmd/cache-server/main.go index 06a2f7e..daedc43 100644 --- a/cmd/cache-server/main.go +++ b/cmd/cache-server/main.go @@ -40,6 +40,10 @@ func run() error { port = flag.Int("port", 0, "loopback TCP port; 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") 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") @@ -85,19 +89,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 + } + } srv, err := cacheserver.New(cacheserver.Config{ - Backend: backend, - CacheDir: dir, - KeyPrefix: *keyPrefix, - 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, + 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, }) if err != nil { return err @@ -156,6 +172,11 @@ func run() error { logger.Printf("graceful shutdown failed: %v", err) _ = httpServer.Close() } + flushContext, flushCancel := context.WithTimeout(context.Background(), *backendTimeout) + if err := srv.Close(flushContext); err != nil { + logger.Printf("flush packed cache: %v", err) + } + flushCancel() stats := srv.Snapshot() if err := cacheserver.WriteStatsFile(*statsFile, stats); err != nil { logger.Printf("write stats: %v", err) diff --git a/dist/SHA256SUMS b/dist/SHA256SUMS index cadcb1a..42aa1b6 100644 --- a/dist/SHA256SUMS +++ b/dist/SHA256SUMS @@ -1,2 +1,2 @@ -2e25107fd39830c2f617cb9401cea50071d2f901d88f8e1fff3bde14fde71b44 cache-server-linux-amd64 -5896195b6347e049aa93c64e5010c7019fb93e2b7377af06f8e36fd14a0d34db cache-server-linux-arm64 +100dfdbf3729558bd6953d0e836f6d22a6d7f4e53e67bae289008de2e971e96b cache-server-linux-amd64 +5de1b5db9ffa1350bdda5ef1affcabad59be3527df3b7a2abd332d3a6c3e2bcd cache-server-linux-arm64 diff --git a/dist/cache-server-linux-amd64 b/dist/cache-server-linux-amd64 index b88bc51..b746b5d 100755 Binary files a/dist/cache-server-linux-amd64 and b/dist/cache-server-linux-amd64 differ diff --git a/dist/cache-server-linux-arm64 b/dist/cache-server-linux-arm64 index 3655169..a3c9f73 100755 Binary files a/dist/cache-server-linux-arm64 and b/dist/cache-server-linux-arm64 differ diff --git a/docs/carv2-manifest-dag-concept.md b/docs/carv2-manifest-dag-concept.md index ff86cf2..7944d15 100644 --- a/docs/carv2-manifest-dag-concept.md +++ b/docs/carv2-manifest-dag-concept.md @@ -1,7 +1,7 @@ # Concept: CARv2 packs and a manifest DAG -Status: proposed for a future v0.3 release. This document does not change the -v0.2 object-per-entry format or its wire compatibility. +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. ## Problem @@ -66,8 +66,7 @@ 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. -The final generated schema is a design-time decision, but its logical contents -are: +The implemented DAG-CBOR schema has this logical content: ```text Manifest { @@ -168,8 +167,10 @@ Required tests include: - An end-to-end cold seed followed by a fresh-runner warm restore, measuring cache-entry creations, transfer volume, and hit rate. -Before implementation, validate the chosen manifest schema and pack-size targets -with a prototype against a representative large Bazel build. +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. [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 9dd8c40..2d3d8e5 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,14 @@ module github.com/cre4ture/bazel-github-actions-cache-v2 go 1.26.0 -require github.com/tonistiigi/go-actions-cache v0.0.0-20260120203934-54bc28c26fd2 +require ( + github.com/ipfs/go-block-format v0.2.3 + github.com/ipfs/go-cid v0.6.1 + github.com/ipld/go-car/v2 v2.17.0 + github.com/ipld/go-ipld-prime v0.24.0 + github.com/multiformats/go-multihash v0.2.3 + github.com/tonistiigi/go-actions-cache v0.0.0-20260120203934-54bc28c26fd2 +) require google.golang.org/protobuf v1.36.11 @@ -12,8 +19,29 @@ require ( 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/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 + github.com/multiformats/go-base36 v0.2.0 // indirect + github.com/multiformats/go-multibase v0.3.0 // indirect + github.com/multiformats/go-multicodec v0.10.0 // indirect + github.com/multiformats/go-varint v0.1.0 // indirect + github.com/petar/GoLLRB v0.0.0-20210522233825-ae3b015fd3e9 // indirect github.com/pkg/errors v0.9.1 // indirect + github.com/polydawn/refmt v0.90.0 // indirect + 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/xerrors v0.0.0-20240903120638-7835f813f4da // indirect + lukechampine.com/blake3 v1.4.1 // indirect ) diff --git a/go.sum b/go.sum index 053b59f..1d8fe7c 100644 --- a/go.sum +++ b/go.sum @@ -14,24 +14,125 @@ 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/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/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8= github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= +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/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= +github.com/gopherjs/gopherjs v1.17.2/go.mod h1:pRRIvn/QzFLrKfvEz3qUuEhtE/zLCWfreZ6J5gM2i+k= +github.com/hashicorp/golang-lru v1.0.2 h1:dV3g9Z/unq5DpblPpw+Oqcv4dU/1omnb4Ok8iPY6p1c= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +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/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-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-cidutil v0.1.1 h1:COuby6H8C2ml0alvHYX3WdbFM4F07YtbY0UlT5j+sgI= +github.com/ipfs/go-cidutil v0.1.1/go.mod h1:SCoUftGEUgoXe5Hjeyw5CiLZF8cwYn/TbtpFQXJCP6k= +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-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-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-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-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/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= +github.com/ipld/go-codec-dagpb v1.7.0/go.mod h1:rD3Zg+zub9ZnxcLwfol/OTQRVjaLzXypgy4UqHQvilM= +github.com/ipld/go-ipld-prime v0.24.0 h1:6th8Z6Peh5bCWuRAVZcDO1sHzZdVF6F2cCCDG3681tg= +github.com/ipld/go-ipld-prime v0.24.0/go.mod h1:DYZxr/5caLNFbcuU6zLOgwSW7CgUEoC4wJiZMEU8Zhs= +github.com/ipld/go-ipld-prime/storage/bsadapter v0.0.0-20250821084354-a425e60cd714 h1:cqNk8PEwHnK0vqWln+U/YZhQc9h2NB3KjUjDPZo5Q2s= +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/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= +github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +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= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6cdF0Y8= +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/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= +github.com/mr-tron/base58 v1.3.0/go.mod h1:2BuubE67DCSWwVfx37JWNG8emOC0sHEU4/HpcYgCLX8= +github.com/multiformats/go-base32 v0.1.0 h1:pVx9xoSPqEIQG8o+UbAe7DNi51oej1NtK+aGkbLYxPE= +github.com/multiformats/go-base32 v0.1.0/go.mod h1:Kj3tFY6zNr+ABYMqeUNeGvkIC/UYgtWibDcT0rExnbI= +github.com/multiformats/go-base36 v0.2.0 h1:lFsAbNOGeKtuKozrtBsAkSVhv1p9D0/qedU9rQyccr0= +github.com/multiformats/go-base36 v0.2.0/go.mod h1:qvnKE++v+2MWCfePClUEjE78Z7P2a1UV0xHgWc0hkp4= +github.com/multiformats/go-multibase v0.3.0 h1:8helZD2+4Db7NNWFiktk2NePbF0boolBe6bDQvM4r68= +github.com/multiformats/go-multibase v0.3.0/go.mod h1:MoBLQPCkRTOL3eveIPO81860j2AQY8JwcnNlRkGRUfI= +github.com/multiformats/go-multicodec v0.10.0 h1:UpP223cig/Cx8J76jWt91njpK3GTAO1w02sdcjZDSuc= +github.com/multiformats/go-multicodec v0.10.0/go.mod h1:wg88pM+s2kZJEQfRCKBNU+g32F5aWBEjyFHXvZLTcLI= +github.com/multiformats/go-multihash v0.2.3 h1:7Lyc8XfX/IY2jWb/gI7JP+o7JEq9hOa7BFvVU9RSh+U= +github.com/multiformats/go-multihash v0.2.3/go.mod h1:dXgKXCXjBzdscBLk9JkjINiEsCKRVch90MdaGiKsvSM= +github.com/multiformats/go-varint v0.1.0 h1:i2wqFp4sdl3IcIxfAonHQV9qU5OsZ4Ts9IOoETFs5dI= +github.com/multiformats/go-varint v0.1.0/go.mod h1:5KVAVXegtfmNQQm/lCY+ATvDzvJJhSkUlGQV9wgObdI= +github.com/petar/GoLLRB v0.0.0-20210522233825-ae3b015fd3e9 h1:1/WtZae0yGtPq+TI6+Tv1WTxkukpXeMlviSxvL7SRgk= +github.com/petar/GoLLRB v0.0.0-20210522233825-ae3b015fd3e9/go.mod h1:x3N5drFsm2uilKKuuYo6LdyD8vZAW55sH/9w+pbo1sw= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/polydawn/refmt v0.90.0 h1:58BfEsP+G4uIRD9ApJTFsag+Mw+QQlZuH9uI/lPmjfY= +github.com/polydawn/refmt v0.90.0/go.mod h1:XAlDMOunevTYDsZtOKQd8itHXFMsX/QtDkPHaj6ZLxk= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/smarty/assertions v1.15.0 h1:cR//PqUBUiQRakZWqBiFFQ9wb8emQGDb0HeGdqGByCY= +github.com/smarty/assertions v1.15.0/go.mod h1:yABtdzeQs6l1brC900WlRNwj6ZR55d7B+E8C6HtKdec= +github.com/smartystreets/goconvey v1.8.1 h1:qGjIddxOk4grTu9JPOU31tVfq3cNdBlNa5sSznIX1xY= +github.com/smartystreets/goconvey v1.8.1/go.mod h1:+/u4qLyY6x1jReYOp7GOM2FSt8aP9CzCZL03bI28W60= +github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= +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/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/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= +github.com/whyrusleeping/cbor v0.0.0-20171005072247-63513f603b11/go.mod h1:Wlo/SzPmxVp6vXpGt/zaXhHH0fn4IxgqZc82aKg6bpQ= +github.com/whyrusleeping/cbor-gen v0.3.1 h1:82ioxmhEYut7LBVGhGq8xoRkXPLElVuh5mV67AFfdv0= +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.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= +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= @@ -40,7 +141,13 @@ 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/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= +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= +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/cache/catalog.go b/internal/cache/catalog.go new file mode 100644 index 0000000..2cb711f --- /dev/null +++ b/internal/cache/catalog.go @@ -0,0 +1,117 @@ +package cache + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "os" + "strconv" + "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. +type Catalog interface { + List(ctx context.Context, keyPrefix string, limit int) ([]string, error) +} + +// ActionsCatalog lists cache metadata through the public GitHub REST API. +// A normal GITHUB_TOKEN with actions: read is sufficient. It deliberately +// does not expose deletion or mutation operations. +type ActionsCatalog struct { + baseURL *url.URL + repository string + token string + client *http.Client +} + +// NewActionsCatalog creates a manifest-discovery client from GitHub Actions +// runner environment variables. +func NewActionsCatalog(timeout time.Duration) (*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") + } + token := os.Getenv("GITHUB_TOKEN") + if token == "" { + return nil, errors.New("GITHUB_TOKEN is required for packed-cache manifest discovery") + } + 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) + } + return &ActionsCatalog{ + baseURL: baseURL, + repository: repository, + token: token, + client: &http.Client{Timeout: timeout}, + }, nil +} + +type actionsCacheListResponse struct { + ActionsCaches []struct { + Key string `json:"key"` + } `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") + } + 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() + + request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil) + if err != nil { + return nil, fmt.Errorf("create cache catalog request: %w", err) + } + request.Header.Set("Accept", "application/vnd.github+json") + request.Header.Set("Authorization", "Bearer "+c.token) + request.Header.Set("X-GitHub-Api-Version", "2022-11-28") + response, err := c.client.Do(request) + if err != nil { + return nil, fmt.Errorf("list GitHub Actions caches: %w", err) + } + var result actionsCacheListResponse + decodeErr := json.NewDecoder(response.Body).Decode(&result) + _ = response.Body.Close() + if response.StatusCode != http.StatusOK { + return nil, fmt.Errorf("list GitHub Actions caches: HTTP %d", response.StatusCode) + } + if decodeErr != nil { + 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 len(result.ActionsCaches) < 100 { + return keys, nil + } + page++ + } +} diff --git a/internal/cache/catalog_test.go b/internal/cache/catalog_test.go new file mode 100644 index 0000000..d6715f9 --- /dev/null +++ b/internal/cache/catalog_test.go @@ -0,0 +1,56 @@ +package cache + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" +) + +func TestActionsCatalogListsAllPagesWithinPrefix(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) + } + if got := r.URL.Query().Get("key"); got != "prefix-manifest-" { + t.Fatalf("key = %q", got) + } + if r.URL.Query().Get("page") == "1" { + _, _ = w.Write([]byte(`{"actions_caches":[{"key":"prefix-manifest-one"}]}`)) + return + } + _, _ = w.Write([]byte(`{"actions_caches":[]}`)) + })) + defer server.Close() + baseURL, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + catalog := &ActionsCatalog{baseURL: baseURL, repository: "owner/repository", token: "token", client: server.Client()} + keys, err := catalog.List(context.Background(), "prefix-manifest-", 10) + if err != nil { + t.Fatal(err) + } + if strings.Join(keys, ",") != "prefix-manifest-one" || requests != 1 { + t.Fatalf("keys/requests = %v/%d", keys, requests) + } +} + +func TestActionsCatalogRejectsLimitOverflow(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"}]}`)) + })) + defer server.Close() + baseURL, err := url.Parse(server.URL) + if err != nil { + 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") + } +} diff --git a/internal/server/action_result_validation.go b/internal/server/action_result_validation.go index 52fed14..e2b8447 100644 --- a/internal/server/action_result_validation.go +++ b/internal/server/action_result_validation.go @@ -20,28 +20,37 @@ type actionResultValidator struct { validatedBlobs map[string]int64 validatedTrees map[string]int64 validatedDirectories map[string]int64 + collectClosure bool + closure map[string]digestReference } func (s *Server) validateActionResult(ctx context.Context, object object) error { - return s.validateActionResultClosure(ctx, object, false) + _, err := s.validateActionResultClosure(ctx, object, false, false) + return err } func (s *Server) validateActionResultForPublication(ctx context.Context, object object) error { - return s.validateActionResultClosure(ctx, object, true) + _, 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) } func (s *Server) validateActionResultClosure( ctx context.Context, object object, requirePersisted bool, -) error { + collect bool, +) ([]digestReference, error) { data, err := os.ReadFile(object.path) if err != nil { - return fmt.Errorf("read action result: %w", err) + return nil, fmt.Errorf("read action result: %w", err) } references, err := parseActionResult(data) if err != nil { - return fmt.Errorf("%w: %v", errInvalidActionResult, err) + return nil, fmt.Errorf("%w: %v", errInvalidActionResult, err) } validator := &actionResultValidator{ server: s, @@ -50,18 +59,27 @@ func (s *Server) validateActionResultClosure( validatedBlobs: make(map[string]int64), validatedTrees: make(map[string]int64), validatedDirectories: make(map[string]int64), + collectClosure: collect, + closure: make(map[string]digestReference), } for _, reference := range references.blobs.values { if err := validator.validateBlob(reference); err != nil { - return err + return nil, err } } for _, reference := range references.trees.values { if err := validator.validateTree(reference); err != nil { - return err + return nil, err } } - return validator.validateDirectoryClosure(references.directories.values) + if err := validator.validateDirectoryClosure(references.directories.values); err != nil { + return nil, err + } + closure := make([]digestReference, 0, len(validator.closure)) + for _, reference := range validator.closure { + closure = append(closure, reference) + } + return sortDigestReferences(closure), nil } func (v *actionResultValidator) validateBlob(reference digestReference) error { @@ -76,6 +94,7 @@ func (v *actionResultValidator) validateBlob(reference digestReference) error { if err := v.reserveObject(); err != nil { return err } + v.collect(reference) key := v.server.cfg.KeyPrefix + "-cas-" + reference.hash found, err := v.casExists(key) if err != nil { @@ -93,6 +112,7 @@ func (v *actionResultValidator) validateTree(reference digestReference) error { } else if alreadyValidated { return nil } + v.collect(reference) object, err := v.loadCAS(reference) if err != nil { return err @@ -123,6 +143,7 @@ func (v *actionResultValidator) validateDirectoryClosure(roots []digestReference } else if alreadyValidated { continue } + v.collect(reference) object, err := v.loadCAS(reference) if err != nil { return err @@ -145,6 +166,12 @@ func (v *actionResultValidator) validateDirectoryClosure(roots []digestReference return nil } +func (v *actionResultValidator) collect(reference digestReference) { + if v.collectClosure && !isImplicitEmptyDigest(reference) { + v.closure[reference.hash] = reference + } +} + func (v *actionResultValidator) loadCAS(reference digestReference) (object, error) { if err := v.reserveObject(); err != nil { return object{}, err diff --git a/internal/server/manifest.go b/internal/server/manifest.go new file mode 100644 index 0000000..c53fb55 --- /dev/null +++ b/internal/server/manifest.go @@ -0,0 +1,527 @@ +package server + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "sort" + + "github.com/ipfs/go-cid" + ipld "github.com/ipld/go-ipld-prime" + "github.com/ipld/go-ipld-prime/codec/dagcbor" + "github.com/ipld/go-ipld-prime/datamodel" + "github.com/ipld/go-ipld-prime/node/basicnode" + "github.com/multiformats/go-multihash" +) + +const manifestFormatVersion = 1 + +type manifest struct { + Version int64 + Parents []string + Packs []packDescriptor + CAS []manifestObject + Actions []manifestAction +} + +type packDescriptor struct { + ID string + Key string + Size int64 +} + +type manifestObject struct { + Digest string + CID string + PackID string + Size int64 +} + +type manifestAction struct { + Digest string + CID string + PackID string + Size int64 + ClosurePacks []string +} + +func encodeManifest(value manifest) ([]byte, string, error) { + node, err := manifestToNode(value) + if err != nil { + return nil, "", err + } + var encoded bytes.Buffer + if err := dagcbor.Encode(node, &encoded); err != nil { + return nil, "", fmt.Errorf("encode DAG-CBOR manifest: %w", err) + } + data := encoded.Bytes() + manifestCID, err := dagCBORCID(data) + if err != nil { + return nil, "", err + } + return data, manifestCID.String(), nil +} + +func decodeManifest(data []byte, expectedCID string) (manifest, error) { + if expectedCID != "" { + actual, err := dagCBORCID(data) + if err != nil { + return manifest{}, err + } + if actual.String() != expectedCID { + return manifest{}, fmt.Errorf("manifest CID mismatch: expected %s, got %s", expectedCID, actual) + } + } + node, err := ipld.Decode(data, dagcbor.Decode) + if err != nil { + return manifest{}, fmt.Errorf("decode DAG-CBOR manifest: %w", err) + } + return nodeToManifest(node) +} + +func manifestToNode(value manifest) (datamodel.Node, error) { + if value.Version != manifestFormatVersion { + return nil, fmt.Errorf("unsupported manifest version %d", value.Version) + } + parents := append([]string(nil), value.Parents...) + sort.Strings(parents) + packs := append([]packDescriptor(nil), value.Packs...) + sort.Slice(packs, func(i, j int) bool { return packs[i].ID < packs[j].ID }) + cas := append([]manifestObject(nil), value.CAS...) + sort.Slice(cas, func(i, j int) bool { return cas[i].Digest < cas[j].Digest }) + actions := append([]manifestAction(nil), value.Actions...) + sort.Slice(actions, func(i, j int) bool { return actions[i].Digest < actions[j].Digest }) + + builder := basicnode.Prototype.Map.NewBuilder() + assembler, err := builder.BeginMap(5) + if err != nil { + return nil, err + } + if err := assembleManifestActions(assembler, actions); err != nil { + return nil, err + } + if err := assembleManifestCAS(assembler, cas); err != nil { + return nil, err + } + if err := assembleManifestPacks(assembler, packs); err != nil { + return nil, err + } + if err := assembleStringList(assembler, "parents", parents); err != nil { + return nil, err + } + if err := assembleInt(assembler, "version", value.Version); err != nil { + return nil, err + } + if err := assembler.Finish(); err != nil { + return nil, err + } + return builder.Build(), nil +} + +func assembleManifestActions(assembler datamodel.MapAssembler, actions []manifestAction) error { + if err := assembler.AssembleKey().AssignString("actions"); err != nil { + return err + } + list, err := assembler.AssembleValue().BeginList(int64(len(actions))) + if err != nil { + return err + } + 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 }{ + {"cid", action.CID}, + {"digest", action.Digest}, + {"pack", action.PackID}, + } { + if err := assembleString(mapAssembler, field.key, field.value); err != nil { + return err + } + } + if err := assembleStringList(mapAssembler, "closure", closure); err != nil { + return err + } + if err := assembleInt(mapAssembler, "size", action.Size); err != nil { + return err + } + if err := mapAssembler.Finish(); err != nil { + return err + } + } + return list.Finish() +} + +func assembleManifestCAS(assembler datamodel.MapAssembler, objects []manifestObject) error { + if err := assembler.AssembleKey().AssignString("cas"); err != nil { + return err + } + list, err := assembler.AssembleValue().BeginList(int64(len(objects))) + if err != nil { + return err + } + for _, object := range objects { + mapAssembler, err := list.AssembleValue().BeginMap(4) + if err != nil { + return err + } + for _, field := range []struct{ key, value string }{ + {"cid", object.CID}, + {"digest", object.Digest}, + {"pack", object.PackID}, + } { + if err := assembleString(mapAssembler, field.key, field.value); err != nil { + return err + } + } + if err := assembleInt(mapAssembler, "size", object.Size); err != nil { + return err + } + if err := mapAssembler.Finish(); err != nil { + return err + } + } + return list.Finish() +} + +func assembleManifestPacks(assembler datamodel.MapAssembler, packs []packDescriptor) error { + if err := assembler.AssembleKey().AssignString("packs"); err != nil { + return err + } + list, err := assembler.AssembleValue().BeginList(int64(len(packs))) + if err != nil { + return err + } + for _, pack := range packs { + mapAssembler, err := list.AssembleValue().BeginMap(3) + if err != nil { + return err + } + if err := assembleString(mapAssembler, "id", pack.ID); err != nil { + return err + } + if err := assembleString(mapAssembler, "key", pack.Key); err != nil { + return err + } + if err := assembleInt(mapAssembler, "size", pack.Size); err != nil { + return err + } + if err := mapAssembler.Finish(); err != nil { + return err + } + } + return list.Finish() +} + +func assembleStringList(assembler datamodel.MapAssembler, key string, values []string) error { + if err := assembler.AssembleKey().AssignString(key); err != nil { + return err + } + list, err := assembler.AssembleValue().BeginList(int64(len(values))) + if err != nil { + return err + } + for _, value := range values { + if err := list.AssembleValue().AssignString(value); err != nil { + return err + } + } + return list.Finish() +} + +func assembleString(assembler datamodel.MapAssembler, key, value string) error { + if err := assembler.AssembleKey().AssignString(key); err != nil { + return err + } + return assembler.AssembleValue().AssignString(value) +} + +func assembleInt(assembler datamodel.MapAssembler, key string, value int64) error { + if err := assembler.AssembleKey().AssignString(key); err != nil { + return err + } + return assembler.AssembleValue().AssignInt(value) +} + +func nodeToManifest(node datamodel.Node) (manifest, error) { + if node.Kind() != datamodel.Kind_Map { + return manifest{}, errors.New("manifest must be a map") + } + version, err := nodeInt(node, "version") + if err != nil { + return manifest{}, err + } + if version != manifestFormatVersion { + return manifest{}, fmt.Errorf("unsupported manifest version %d", version) + } + parents, err := nodeStringList(node, "parents") + if err != nil { + return manifest{}, err + } + packs, err := nodePacks(node) + if err != nil { + return manifest{}, err + } + cas, err := nodeCAS(node) + if err != nil { + return manifest{}, err + } + actions, err := nodeActions(node) + if err != nil { + return manifest{}, err + } + value := manifest{Version: version, Parents: parents, Packs: packs, CAS: cas, Actions: actions} + if err := value.validate(); err != nil { + return manifest{}, err + } + return value, nil +} + +func (value manifest) validate() error { + if len(value.Parents) > 4_096 || len(value.Packs) > 4_096 || len(value.CAS) > 100_000 || len(value.Actions) > 100_000 { + return errors.New("manifest exceeds entry limit") + } + 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) { + return errors.New("manifest has invalid pack descriptor") + } + if _, duplicate := packIDs[pack.ID]; duplicate { + return errors.New("manifest repeats a pack descriptor") + } + packIDs[pack.ID] = struct{}{} + } + seenCAS := make(map[string]struct{}, len(value.CAS)) + for _, object := range value.CAS { + if !digestPattern.MatchString(object.Digest) || object.Size < 0 || !validRawCID(object.CID, object.Digest) { + return errors.New("manifest has invalid CAS entry") + } + if _, ok := packIDs[object.PackID]; !ok { + return errors.New("CAS entry references an undeclared pack") + } + if _, duplicate := seenCAS[object.Digest]; duplicate { + return errors.New("manifest repeats a CAS digest") + } + seenCAS[object.Digest] = struct{}{} + } + seenActions := make(map[string]struct{}, len(value.Actions)) + for _, action := range value.Actions { + if !digestPattern.MatchString(action.Digest) || action.Size < 0 || !validCID(action.CID) { + return errors.New("manifest has invalid action entry") + } + 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") + } + seenActions[action.Digest] = struct{}{} + } + for _, parent := range value.Parents { + if !validCID(parent) { + return errors.New("manifest has invalid parent CID") + } + } + return nil +} + +func nodePacks(node datamodel.Node) ([]packDescriptor, error) { + list, err := node.LookupByString("packs") + if err != nil || list.Kind() != datamodel.Kind_List { + return nil, errors.New("manifest packs must be a list") + } + values := make([]packDescriptor, 0, list.Length()) + iterator := list.ListIterator() + for !iterator.Done() { + _, item, err := iterator.Next() + if err != nil || item.Kind() != datamodel.Kind_Map { + return nil, errors.New("manifest pack must be a map") + } + id, err := nodeString(item, "id") + if err != nil { + return nil, err + } + key, err := nodeString(item, "key") + if err != nil { + return nil, err + } + size, err := nodeInt(item, "size") + if err != nil { + return nil, err + } + values = append(values, packDescriptor{ID: id, Key: key, Size: size}) + } + return values, nil +} + +func nodeCAS(node datamodel.Node) ([]manifestObject, error) { + list, err := node.LookupByString("cas") + if err != nil || list.Kind() != datamodel.Kind_List { + return nil, errors.New("manifest cas must be a list") + } + values := make([]manifestObject, 0, list.Length()) + iterator := list.ListIterator() + for !iterator.Done() { + _, item, err := iterator.Next() + if err != nil || item.Kind() != datamodel.Kind_Map { + return nil, errors.New("manifest CAS entry must be a map") + } + value, err := nodeObject(item) + if err != nil { + return nil, err + } + values = append(values, value) + } + return values, nil +} + +func nodeActions(node datamodel.Node) ([]manifestAction, error) { + list, err := node.LookupByString("actions") + if err != nil || list.Kind() != datamodel.Kind_List { + return nil, errors.New("manifest actions must be a list") + } + values := make([]manifestAction, 0, list.Length()) + iterator := list.ListIterator() + for !iterator.Done() { + _, item, err := iterator.Next() + if err != nil || item.Kind() != datamodel.Kind_Map { + return nil, errors.New("manifest action entry must be a map") + } + digest, err := nodeString(item, "digest") + if err != nil { + return nil, err + } + contentCID, err := nodeString(item, "cid") + if err != nil { + return nil, err + } + packID, err := nodeString(item, "pack") + if err != nil { + return nil, err + } + size, err := nodeInt(item, "size") + if err != nil { + return nil, err + } + closure, err := nodeStringList(item, "closure") + if err != nil { + return nil, err + } + values = append(values, manifestAction{Digest: digest, CID: contentCID, PackID: packID, Size: size, ClosurePacks: closure}) + } + return values, nil +} + +func nodeObject(node datamodel.Node) (manifestObject, error) { + digest, err := nodeString(node, "digest") + if err != nil { + return manifestObject{}, err + } + contentCID, err := nodeString(node, "cid") + if err != nil { + return manifestObject{}, err + } + packID, err := nodeString(node, "pack") + if err != nil { + return manifestObject{}, err + } + size, err := nodeInt(node, "size") + if err != nil { + return manifestObject{}, err + } + return manifestObject{Digest: digest, CID: contentCID, PackID: packID, Size: size}, nil +} + +func nodeString(node datamodel.Node, key string) (string, error) { + value, err := node.LookupByString(key) + if err != nil || value.Kind() != datamodel.Kind_String { + return "", fmt.Errorf("manifest %s must be a string", key) + } + return value.AsString() +} + +func nodeInt(node datamodel.Node, key string) (int64, error) { + value, err := node.LookupByString(key) + if err != nil || value.Kind() != datamodel.Kind_Int { + return 0, fmt.Errorf("manifest %s must be an integer", key) + } + return value.AsInt() +} + +func nodeStringList(node datamodel.Node, key string) ([]string, error) { + list, err := node.LookupByString(key) + if err != nil || list.Kind() != datamodel.Kind_List { + return nil, fmt.Errorf("manifest %s must be a list", key) + } + values := make([]string, 0, list.Length()) + iterator := list.ListIterator() + for !iterator.Done() { + _, item, err := iterator.Next() + if err != nil || item.Kind() != datamodel.Kind_String { + return nil, fmt.Errorf("manifest %s must contain strings", key) + } + value, err := item.AsString() + if err != nil { + return nil, err + } + values = append(values, value) + } + return values, nil +} + +func dagCBORCID(data []byte) (cid.Cid, error) { + prefix := cid.Prefix{Version: 1, Codec: cid.DagCBOR, MhType: multihash.SHA2_256, MhLength: -1} + return prefix.Sum(data) +} + +func rawCIDForDigest(digest string) (cid.Cid, error) { + if !digestPattern.MatchString(digest) { + return cid.Undef, errors.New("invalid SHA-256 digest") + } + bytes, err := hex.DecodeString(digest) + if err != nil { + return cid.Undef, err + } + hash, err := multihash.Encode(bytes, multihash.SHA2_256) + if err != nil { + return cid.Undef, err + } + return cid.NewCidV1(cid.Raw, hash), nil +} + +func rawCIDForData(data []byte) (cid.Cid, error) { + sum := sha256.Sum256(data) + return rawCIDForDigest(hex.EncodeToString(sum[:])) +} + +func validRawCID(value, digest string) bool { + expected, err := rawCIDForDigest(digest) + return err == nil && value == expected.String() +} + +func validCID(value string) bool { + _, err := cid.Decode(value) + return err == nil +} + +func packKeyFor(prefix, id string) string { + return prefix + "-car-pack-v1-" + id +} + +func manifestKeyFor(prefix, id string) string { + return prefix + "-car-manifest-v1-" + id +} + +func stringsHasSuffix(value, suffix string) bool { + return len(value) >= len(suffix) && value[len(value)-len(suffix):] == suffix +} diff --git a/internal/server/manifest_test.go b/internal/server/manifest_test.go new file mode 100644 index 0000000..5a64449 --- /dev/null +++ b/internal/server/manifest_test.go @@ -0,0 +1,53 @@ +package server + +import ( + "bytes" + "testing" +) + +func TestManifestDAGCBORRoundTripIsDeterministic(t *testing.T) { + casDigest := digest([]byte("cas")) + casCID, err := rawCIDForDigest(casDigest) + if err != nil { + t.Fatal(err) + } + actionCID, err := rawCIDForData([]byte{0x08, 0x01}) + if err != nil { + t.Fatal(err) + } + packID := digest([]byte("pack")) + 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}}}, + } + encoded, manifestCID, err := encodeManifest(value) + if err != nil { + t.Fatal(err) + } + decoded, err := decodeManifest(encoded, manifestCID) + if err != nil { + t.Fatal(err) + } + reencoded, secondCID, err := encodeManifest(decoded) + if err != nil { + t.Fatal(err) + } + if manifestCID != secondCID || !bytes.Equal(encoded, reencoded) { + t.Fatal("DAG-CBOR manifest is not deterministic") + } +} + +func TestManifestRejectsTamperedCID(t *testing.T) { + value := manifest{Version: manifestFormatVersion} + encoded, manifestCID, err := encodeManifest(value) + if err != nil { + t.Fatal(err) + } + encoded[len(encoded)-1] ^= 1 + if _, err := decodeManifest(encoded, manifestCID); err == nil { + t.Fatal("tampered manifest was accepted") + } +} diff --git a/internal/server/pack_store.go b/internal/server/pack_store.go new file mode 100644 index 0000000..17f365b --- /dev/null +++ b/internal/server/pack_store.go @@ -0,0 +1,809 @@ +package server + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "sort" + "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" +) + +// packStore implements the CARv2/manifest-DAG storage mode. 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 + + keyPrefix string + targetSize int64 + flushInterval time.Duration + maxManifests int + + mu sync.Mutex + packs map[string]packDescriptor + cas map[string]manifestObject + actions map[string]manifestAction + actionConflicts map[string]struct{} + heads map[string]struct{} + pendingCAS map[string]object + pendingCASOrder []string + pendingActions map[string]pendingAction + pendingACOrder []string + pendingBytes int64 + loadedPacks map[string]string + loadingPacks map[string]*packLoad + + flushRequests chan struct{} + stop chan struct{} + closeOnce sync.Once + workers sync.WaitGroup +} + +type pendingAction struct { + object object + closure []digestReference + cid string +} + +type packLoad struct { + done chan struct{} + path string + err error +} + +func newPackStore(server *Server) (*packStore, error) { + if server.cfg.Catalog == nil { + return nil, errors.New("packed storage mode requires a manifest catalog") + } + packs := &packStore{ + server: server, + catalog: server.cfg.Catalog, + keyPrefix: server.cfg.KeyPrefix, + targetSize: server.cfg.PackSize, + flushInterval: server.cfg.PackFlushInterval, + maxManifests: server.cfg.MaxManifests, + packs: make(map[string]packDescriptor), + cas: make(map[string]manifestObject), + 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), + loadingPacks: make(map[string]*packLoad), + flushRequests: make(chan struct{}, 1), + stop: make(chan struct{}), + } + context, cancel := context.WithTimeout(context.Background(), server.cfg.BackendTimeout) + err := packs.discover(context) + cancel() + if err != nil { + server.stats.manifestDiscoveryErrors.Add(1) + if !server.cfg.FailOpen { + return nil, err + } + server.cfg.Logger.Printf("packed-cache manifest discovery failed; starting empty: %s", safeError(err)) + } + packs.workers.Add(1) + go packs.flushWorker() + return packs, nil +} + +func (p *packStore) flushWorker() { + defer p.workers.Done() + ticker := time.NewTicker(p.flushInterval) + defer ticker.Stop() + for { + select { + case <-p.stop: + return + case <-ticker.C: + case <-p.flushRequests: + } + context, cancel := context.WithTimeout(context.Background(), p.server.cfg.BackendTimeout) + if err := p.flush(context, false); err != nil { + p.server.stats.backendSaveErrors.Add(1) + p.server.cfg.Logger.Printf("packed-cache flush failed: %s", safeError(err)) + } + cancel() + } +} + +func (p *packStore) close(ctx context.Context) error { + p.closeOnce.Do(func() { close(p.stop) }) + p.workers.Wait() + return p.flush(ctx, true) +} + +func (p *packStore) stageCAS(digest string, value object) { + p.mu.Lock() + defer p.mu.Unlock() + if _, exists := p.pendingCAS[digest]; exists { + return + } + if _, exists := p.cas[digest]; exists { + return + } + p.pendingCAS[digest] = value + p.pendingCASOrder = append(p.pendingCASOrder, digest) + p.pendingBytes += value.size + p.requestFlushLocked() +} + +func (p *packStore) stageAction(digest string, value object, closure []digestReference) error { + data, err := os.ReadFile(value.path) + if err != nil { + return fmt.Errorf("read pending action result: %w", err) + } + contentCID, err := rawCIDForData(data) + if err != nil { + return err + } + 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{}{} + } + return nil + } + p.pendingActions[digest] = pendingAction{ + object: value, + closure: sortDigestReferences(closure), + cid: contentCID.String(), + } + p.pendingACOrder = append(p.pendingACOrder, digest) + p.pendingBytes += value.size + p.requestFlushLocked() + return nil +} + +func (p *packStore) requestFlushLocked() { + if p.pendingBytes < p.targetSize { + return + } + select { + case p.flushRequests <- struct{}{}: + default: + } +} + +func (p *packStore) resolve(ctx context.Context, key, kind, digest string) (object, bool, error) { + p.server.objectsMu.RLock() + value, exists := p.server.objects[key] + p.server.objectsMu.RUnlock() + if exists { + return value, true, nil + } + + p.mu.Lock() + var contentCID, packID string + var expectedSize int64 + if kind == "cas" { + entry, found := p.cas[digest] + if !found { + 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) + p.mu.Unlock() + return object{}, false, nil + } + entry, found := p.actions[digest] + if !found { + p.mu.Unlock() + return object{}, false, nil + } + contentCID, packID, expectedSize = entry.CID, entry.PackID, entry.Size + } + p.mu.Unlock() + + path, err := p.loadPack(ctx, packID) + if err != nil { + return object{}, false, err + } + data, err := readCARBlock(ctx, path, contentCID) + if err != nil { + return object{}, false, err + } + if int64(len(data)) != expectedSize { + return object{}, false, fmt.Errorf("packed %s/%s has size %d; manifest declares %d", kind, digest, len(data), expectedSize) + } + if kind == "cas" { + sum := sha256.Sum256(data) + if hex.EncodeToString(sum[:]) != digest { + 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 value, true, nil +} + +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) 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 + } + file, err := os.CreateTemp(p.server.cfg.CacheDir, "packed-object-*") + if err != nil { + return object{}, err + } + path := file.Name() + if err := file.Chmod(0o600); err != nil { + _ = file.Close() + return object{}, err + } + _, err = file.Write(data) + if err == nil { + err = file.Sync() + } + if closeErr := file.Close(); err == nil { + err = closeErr + } + if err != nil { + return object{}, err + } + 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 + } + p.server.objects[key] = value + p.server.objectsMu.Unlock() + return value, nil +} + +func (p *packStore) loadPack(ctx context.Context, packID string) (string, error) { + p.mu.Lock() + if path, exists := p.loadedPacks[packID]; exists { + p.mu.Unlock() + return path, nil + } + if loading, exists := p.loadingPacks[packID]; exists { + done := loading.done + p.mu.Unlock() + select { + case <-ctx.Done(): + return "", ctx.Err() + case <-done: + return loading.path, loading.err + } + } + descriptor, exists := p.packs[packID] + if !exists { + p.mu.Unlock() + return "", fmt.Errorf("manifest references unavailable pack %s", packID) + } + loading := &packLoad{done: make(chan struct{})} + p.loadingPacks[packID] = loading + p.mu.Unlock() + + path, err := p.downloadPack(ctx, descriptor) + p.mu.Lock() + if err == nil { + p.loadedPacks[packID] = path + loading.path = path + } + loading.err = err + delete(p.loadingPacks, packID) + close(loading.done) + p.mu.Unlock() + return path, err +} + +func (p *packStore) downloadPack(ctx context.Context, descriptor packDescriptor) (string, error) { + if err := p.server.acquire(ctx); err != nil { + return "", err + } + defer p.server.release() + file, err := os.CreateTemp(p.server.cfg.CacheDir, "pack-download-*") + if err != nil { + return "", err + } + path := file.Name() + 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) + cancel() + if closeErr := file.Close(); err == nil { + err = closeErr + } + if err != nil { + return "", err + } + if !found { + return "", fmt.Errorf("pack %s is missing", descriptor.ID) + } + p.server.stats.backendDownloads.Add(1) + p.server.stats.packDownloads.Add(1) + info, err := os.Stat(path) + if err != nil { + return "", err + } + if info.Size() != descriptor.Size { + return "", fmt.Errorf("pack %s has size %d; manifest declares %d", descriptor.ID, info.Size(), descriptor.Size) + } + verify, err := os.Open(path) + if err != nil { + return "", err + } + actual, hashErr := hashFile(verify) + closeErr := verify.Close() + if hashErr != nil { + return "", hashErr + } + if closeErr != nil { + return "", closeErr + } + if actual != descriptor.ID { + return "", fmt.Errorf("pack integrity check failed: expected %s, got %s", descriptor.ID, actual) + } + return path, nil +} + +func (p *packStore) flush(ctx context.Context, all bool) error { + p.mu.Lock() + defer p.mu.Unlock() + for { + flushed, err := p.flushOneLocked(ctx) + if err != nil || !flushed || !all { + return err + } + } +} + +func (p *packStore) flushOneLocked(ctx context.Context) (bool, error) { + casDigests := p.selectCASLocked() + selectedCAS := make(map[string]struct{}, len(casDigests)) + for _, digest := range casDigests { + selectedCAS[digest] = struct{}{} + } + actionDigests := p.selectActionsLocked(selectedCAS) + if len(casDigests) == 0 && len(actionDigests) == 0 { + return false, nil + } + + packPath, entries, packSize, packID, err := p.buildPackLocked(ctx, casDigests, actionDigests) + if err != nil { + return false, err + } + pack := packDescriptor{ID: packID, Key: packKeyFor(p.keyPrefix, packID), Size: packSize} + if err := p.publishFile(ctx, pack.Key, packPath, packSize); err != nil { + return false, fmt.Errorf("publish CARv2 pack: %w", err) + } + p.server.stats.packUploads.Add(1) + + manifestValue := p.manifestForPackLocked(pack, entries, selectedCAS) + manifestData, manifestID, err := encodeManifest(manifestValue) + if err != nil { + return false, err + } + manifestPath, err := writePrivateTemp(p.server.cfg.CacheDir, "manifest-*", manifestData) + if err != nil { + return false, err + } + if err := p.publishFile(ctx, manifestKeyFor(p.keyPrefix, manifestID), manifestPath, int64(len(manifestData))); err != nil { + return false, fmt.Errorf("publish manifest commit point: %w", err) + } + p.server.stats.manifestUploads.Add(1) + p.applyManifestLocked(manifestID, manifestValue) + p.removePendingLocked(casDigests, actionDigests) + return true, nil +} + +type packedEntries struct { + cas []manifestObject + actions []manifestAction +} + +func (p *packStore) buildPackLocked(ctx context.Context, casDigests, actionDigests []string) (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] + data, err := os.ReadFile(value.path) + if err != nil { + return "", packedEntries{}, 0, "", err + } + contentCID, err := rawCIDForDigest(digest) + 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] + data, err := os.ReadFile(value.object.path) + if err != nil { + return "", packedEntries{}, 0, "", err + } + contentCID, err := cid.Decode(value.cid) + 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}) + } + if len(blocksToWrite) == 0 { + return "", packedEntries{}, 0, "", errors.New("cannot build an empty CARv2 pack") + } + path, err := writePrivateTemp(p.server.cfg.CacheDir, "pack-*", nil) + if err != nil { + return "", packedEntries{}, 0, "", err + } + store, err := blockstore.OpenReadWrite(path, []cid.Cid{blocksToWrite[0].cid}, blockstore.UseWholeCIDs(true)) + if err != nil { + return "", packedEntries{}, 0, "", err + } + for _, entry := range blocksToWrite { + block, err := blocks.NewBlockWithCid(entry.data, entry.cid) + if err != nil { + store.Discard() + return "", packedEntries{}, 0, "", err + } + if err := store.Put(ctx, block); err != nil { + store.Discard() + return "", packedEntries{}, 0, "", err + } + } + if err := store.Finalize(); err != nil { + return "", packedEntries{}, 0, "", err + } + info, err := os.Stat(path) + if err != nil { + return "", packedEntries{}, 0, "", err + } + file, err := os.Open(path) + if err != nil { + return "", packedEntries{}, 0, "", err + } + packID, hashErr := hashFile(file) + closeErr := file.Close() + if hashErr != nil { + return "", packedEntries{}, 0, "", hashErr + } + if closeErr != nil { + return "", packedEntries{}, 0, "", closeErr + } + 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, + Parents: sortedStringsFromSet(p.heads), + Packs: []packDescriptor{pack}, + CAS: entries.cas, + Actions: entries.actions, + } +} + +func (p *packStore) selectCASLocked() []string { + selected := make([]string, 0) + var size int64 + for _, digest := range p.pendingCASOrder { + value, exists := p.pendingCAS[digest] + if !exists { + continue + } + if len(selected) > 0 && size+value.size > p.targetSize { + break + } + selected = append(selected, digest) + size += value.size + if size >= p.targetSize { + break + } + } + return selected +} + +func (p *packStore) selectActionsLocked(selectedCAS map[string]struct{}) []string { + selected := make([]string, 0) + for _, digest := range p.pendingACOrder { + value, exists := p.pendingActions[digest] + if !exists { + continue + } + eligible := true + for _, reference := range value.closure { + if isImplicitEmptyDigest(reference) { + continue + } + if _, selected := selectedCAS[reference.hash]; selected { + continue + } + if _, published := p.cas[reference.hash]; !published { + eligible = false + break + } + } + if eligible { + selected = append(selected, digest) + } + } + return selected +} + +func (p *packStore) publishFile(ctx context.Context, key, path string, size int64) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + deduplicated, err := p.server.publishOnce(ctx, key, file, size) + if err != nil { + return err + } + if deduplicated { + p.server.stats.deduplicatedUploads.Add(1) + } else { + p.server.stats.uploads.Add(1) + } + return nil +} + +func (p *packStore) removePendingLocked(casDigests, actionDigests []string) { + for _, digest := range casDigests { + if value, exists := p.pendingCAS[digest]; exists { + p.pendingBytes -= value.size + delete(p.pendingCAS, digest) + } + } + for _, digest := range actionDigests { + if value, exists := p.pendingActions[digest]; exists { + p.pendingBytes -= value.object.size + delete(p.pendingActions, digest) + } + } + p.pendingCASOrder = filterPending(p.pendingCASOrder, p.pendingCAS) + p.pendingACOrder = filterPending(p.pendingACOrder, p.pendingActions) +} + +func filterPending[T any](order []string, values map[string]T) []string { + filtered := order[:0] + for _, key := range order { + if _, exists := values[key]; exists { + filtered = append(filtered, key) + } + } + return filtered +} + +func (p *packStore) discover(ctx context.Context) error { + keys, err := p.catalog.List(ctx, manifestKeyFor(p.keyPrefix, ""), p.maxManifests) + 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) + 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)) + continue + } + manifests[manifestID] = value + for _, parent := range value.Parents { + parents[parent] = struct{}{} + } + } + ids := make([]string, 0, len(manifests)) + for id := range manifests { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + p.applyManifestLocked(id, manifests[id]) + if _, parent := parents[id]; !parent { + p.heads[id] = struct{}{} + } + } + return nil +} + +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) + cancel() + if err != nil { + return manifest{}, err + } + if !found { + return manifest{}, errors.New("manifest cache entry is missing") + } + p.server.stats.backendDownloads.Add(1) + if int64(data.Len()) > p.server.cfg.MaxBlobSize { + return manifest{}, errors.New("manifest exceeds maximum object size") + } + return decodeManifest(data.Bytes(), id) +} + +func (p *packStore) applyManifestLocked(id string, value manifest) { + for _, descriptor := range value.Packs { + if existing, found := p.packs[descriptor.ID]; !found || descriptor.Key < existing.Key { + 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 + } + } + for _, action := range value.Actions { + if existing, found := p.actions[action.Digest]; found { + if existing.CID != action.CID { + p.actionConflicts[action.Digest] = struct{}{} + } + continue + } + p.actions[action.Digest] = action + } + for _, parent := range value.Parents { + delete(p.heads, parent) + } + p.heads[id] = struct{}{} +} + +func parseManifestKey(prefix, key string) (string, bool) { + head := manifestKeyFor(prefix, "") + if len(key) <= len(head) || key[:len(head)] != head { + return "", false + } + id := key[len(head):] + return id, validCID(id) +} + +func readCARBlock(ctx context.Context, path, contentCID string) ([]byte, error) { + store, err := blockstore.OpenReadOnly(path, blockstore.UseWholeCIDs(true)) + if err != nil { + return nil, fmt.Errorf("open CARv2 pack: %w", err) + } + defer store.Close() + content, err := cid.Decode(contentCID) + if err != nil { + return nil, err + } + block, err := store.Get(ctx, content) + if err != nil { + return nil, fmt.Errorf("load block from CARv2 pack: %w", err) + } + data := block.RawData() + actual, err := rawCIDForData(data) + if err != nil || actual.String() != contentCID { + return nil, errors.New("CARv2 block CID integrity check failed") + } + return data, nil +} + +func writePrivateTemp(directory, pattern string, data []byte) (string, error) { + file, err := os.CreateTemp(directory, pattern) + if err != nil { + 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 + } + if err != nil { + return "", err + } + return path, nil +} + +type bytesBuffer struct{ data []byte } + +func (b *bytesBuffer) Write(data []byte) (int, error) { + b.data = append(b.data, data...) + return len(data), nil +} + +func (b *bytesBuffer) Bytes() []byte { return b.data } +func (b *bytesBuffer) Len() int { return len(b.data) } + +func sortDigestReferences(values []digestReference) []digestReference { + unique := make(map[string]digestReference, len(values)) + for _, value := range values { + if existing, found := unique[value.hash]; !found || existing.size == value.size { + unique[value.hash] = value + } + } + sorted := make([]digestReference, 0, len(unique)) + for _, value := range unique { + sorted = append(sorted, value) + } + sort.Slice(sorted, func(i, j int) bool { return sorted[i].hash < sorted[j].hash }) + return sorted +} + +func sortedStringsFromSet(values map[string]struct{}) []string { + result := make([]string, 0, len(values)) + for value := range values { + result = append(result, value) + } + sort.Strings(result) + return result +} + +var _ io.Writer = (*bytesBuffer)(nil) diff --git a/internal/server/pack_store_test.go b/internal/server/pack_store_test.go new file mode 100644 index 0000000..7724746 --- /dev/null +++ b/internal/server/pack_store_test.go @@ -0,0 +1,167 @@ +package server + +import ( + "context" + "net/http" + "sort" + "strings" + "testing" + "time" + + "github.com/cre4ture/bazel-github-actions-cache-v2/internal/cache" +) + +type memoryCatalog struct { + backend *memoryBackend +} + +func (c memoryCatalog) List(_ context.Context, prefix string, limit int) ([]string, error) { + c.backend.mu.Lock() + defer c.backend.mu.Unlock() + keys := make([]string, 0) + for key := range c.backend.objects { + if strings.HasPrefix(key, prefix) { + keys = append(keys, key) + } + } + sort.Strings(keys) + if len(keys) > limit { + return nil, context.DeadlineExceeded + } + return keys, nil +} + +var _ cache.Catalog = memoryCatalog{} + +func testPackedServer(t *testing.T, backend *memoryBackend) *Server { + t.Helper() + return testServer(t, backend, func(cfg *Config) { + cfg.StorageMode = "packs" + cfg.Catalog = memoryCatalog{backend: backend} + cfg.PackSize = 1024 + cfg.PackFlushInterval = time.Hour + cfg.MaxManifests = 100 + }) +} + +func closePackedServer(t *testing.T, server *Server) { + t.Helper() + context, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if err := server.Close(context); err != nil { + t.Fatal(err) + } +} + +func TestPackedStoreRoundTripCommitsPackBeforeManifest(t *testing.T) { + backend := newMemoryBackend() + seed := testPackedServer(t, backend) + output := []byte("packed output") + outputReference := referenceFor(output) + actionResult := bytesField(2, outputFileProto(outputReference, nil)) + actionDigest := digest([]byte("packed action")) + if response := putCacheObject(seed, "/cas/"+outputReference.hash, output); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + if response := putCacheObject(seed, "/ac/"+actionDigest, actionResult); response.Code != http.StatusNoContent { + t.Fatalf("AC PUT = %d", response.Code) + } + closePackedServer(t, seed) + stats := seed.Snapshot() + if stats.PackUploads != 1 || stats.ManifestUploads != 1 || stats.Uploads != 2 { + t.Fatalf("unexpected publication stats: %+v", stats) + } + + restore := testPackedServer(t, backend) + defer closePackedServer(t, restore) + if response := readCacheObject(restore, "/ac/"+actionDigest); response.Code != http.StatusOK { + t.Fatalf("AC GET = %d, body = %s", response.Code, response.Body.String()) + } + if response := readCacheObject(restore, "/cas/"+outputReference.hash); response.Code != http.StatusOK || response.Body.String() != string(output) { + t.Fatalf("CAS GET = %d, body = %q", response.Code, response.Body.String()) + } + stats = restore.Snapshot() + if stats.PackDownloads != 1 || stats.Hits != 2 || stats.ValidatedActionResults != 1 { + t.Fatalf("unexpected restore stats: %+v", stats) + } +} + +func TestPackedStoreMergesConcurrentManifestHeads(t *testing.T) { + backend := newMemoryBackend() + writerA := testPackedServer(t, backend) + writerB := testPackedServer(t, backend) + + for _, test := range []struct { + server *Server + body []byte + }{ + {writerA, []byte("writer A")}, + {writerB, []byte("writer B")}, + } { + reference := referenceFor(test.body) + if response := putCacheObject(test.server, "/cas/"+reference.hash, test.body); response.Code != http.StatusNoContent { + t.Fatalf("CAS PUT = %d", response.Code) + } + } + closePackedServer(t, writerA) + closePackedServer(t, writerB) + + restore := testPackedServer(t, backend) + defer closePackedServer(t, restore) + for _, body := range [][]byte{[]byte("writer A"), []byte("writer B")} { + response := readCacheObject(restore, "/cas/"+digest(body)) + if response.Code != http.StatusOK || response.Body.String() != string(body) { + t.Fatalf("concurrent CAS restore = %d/%q", response.Code, response.Body.String()) + } + } + if restore.Snapshot().ManifestsDiscovered != 2 { + t.Fatalf("manifest heads were not both discovered: %+v", restore.Snapshot()) + } +} + +func TestPackedStoreTreatsMissingPackAsActionCacheMiss(t *testing.T) { + backend := newMemoryBackend() + seed := testPackedServer(t, backend) + actionDigest := digest([]byte("action")) + if response := putCacheObject(seed, "/ac/"+actionDigest, []byte{0x08, 0x01}); response.Code != http.StatusNoContent { + t.Fatalf("AC PUT = %d", response.Code) + } + closePackedServer(t, seed) + + backend.mu.Lock() + for key := range backend.objects { + if strings.Contains(key, "-car-pack-v1-") { + delete(backend.objects, key) + } + } + backend.mu.Unlock() + restore := testPackedServer(t, backend) + defer closePackedServer(t, restore) + if response := readCacheObject(restore, "/ac/"+actionDigest); response.Code != http.StatusNotFound { + t.Fatalf("missing pack action result = %d", response.Code) + } +} + +func TestPackedStoreRejectsConflictingActionResults(t *testing.T) { + backend := newMemoryBackend() + writerA := testPackedServer(t, backend) + writerB := testPackedServer(t, backend) + actionDigest := digest([]byte("same action")) + if response := putCacheObject(writerA, "/ac/"+actionDigest, []byte{0x08, 0x01}); response.Code != http.StatusNoContent { + t.Fatalf("first AC PUT = %d", response.Code) + } + if response := putCacheObject(writerB, "/ac/"+actionDigest, []byte{0x08, 0x02}); response.Code != http.StatusNoContent { + t.Fatalf("second AC PUT = %d", response.Code) + } + 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) + } + if restore.Snapshot().ActionDigestConflicts != 1 { + t.Fatalf("conflict was not reported: %+v", restore.Snapshot()) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index ef8a8dc..bb8e321 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -30,18 +30,23 @@ var ( ) type Config struct { - Backend cache.Backend - CacheDir string - KeyPrefix string - 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 + 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 } type object struct { @@ -64,6 +69,7 @@ type Server struct { publishing map[string]*publication sem chan struct{} limiter *intervalLimiter + packs *packStore } func New(cfg Config) (*Server, error) { @@ -88,20 +94,48 @@ 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.StorageMode != "objects" && cfg.StorageMode != "packs" { + return nil, errors.New("storage mode must be objects or packs") + } + 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.Logger == nil { cfg.Logger = log.New(io.Discard, "", 0) } if err := os.MkdirAll(cfg.CacheDir, 0o700); err != nil { return nil, fmt.Errorf("create cache directory: %w", err) } - return &Server{ + 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), - }, nil + } + if cfg.StorageMode == "packs" { + packs, err := newPackStore(server) + if err != nil { + return nil, err + } + server.packs = packs + } + return server, nil } func (s *Server) Handler() http.Handler { @@ -112,6 +146,14 @@ func (s *Server) Snapshot() Stats { return s.stats.snapshot() } +// 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) +} + func (s *Server) serveHTTP(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/ready": @@ -290,6 +332,9 @@ func (s *Server) resolve(ctx context.Context, key, kind, digest string) (object, if ok { return obj, true, nil } + if s.packs != nil { + return s.packs.resolve(ctx, key, kind, digest) + } if err := s.acquire(ctx); err != nil { return object{}, false, err @@ -363,6 +408,13 @@ func (s *Server) exists(ctx context.Context, key string) (bool, error) { if ok { return 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):]) + } return s.backendExists(ctx, key) } @@ -434,8 +486,10 @@ func (s *Server) handlePut(w http.ResponseWriter, r *http.Request, key, kind, di } s.objectsMu.Lock() - if _, exists := s.objects[key]; !exists { - s.objects[key] = object{path: path, size: n} + stored, exists := s.objects[key] + if !exists { + stored = object{path: path, size: n} + s.objects[key] = stored keep = true } s.objectsMu.Unlock() @@ -445,6 +499,24 @@ func (s *Server) handlePut(w http.ResponseWriter, r *http.Request, key, kind, di 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 { @@ -486,6 +558,30 @@ func (s *Server) handlePut(w http.ResponseWriter, r *http.Request, key, kind, di 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)) + w.WriteHeader(http.StatusNoContent) + 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) + } + } +} + // publishOnce coalesces identical immutable keys for the lifetime of the // server. Only the request which creates the publication reaches the backend // and consumes an upload-rate-limit slot. A failed publication is not cached, diff --git a/internal/server/stats.go b/internal/server/stats.go index 8628755..b0637fc 100644 --- a/internal/server/stats.go +++ b/internal/server/stats.go @@ -25,6 +25,13 @@ type Stats struct { BytesServed uint64 `json:"bytes_served"` BytesReceived uint64 `json:"bytes_received"` ThrottleWaits uint64 `json:"throttle_waits"` + PackUploads uint64 `json:"pack_uploads"` + ManifestUploads uint64 `json:"manifest_uploads"` + PackDownloads uint64 `json:"pack_downloads"` + ManifestsDiscovered uint64 `json:"manifests_discovered"` + ManifestDiscoveryErrors uint64 `json:"manifest_discovery_errors"` + ManifestLoadErrors uint64 `json:"manifest_load_errors"` + ActionDigestConflicts uint64 `json:"action_digest_conflicts"` } type counters struct { @@ -46,6 +53,13 @@ type counters struct { bytesServed atomic.Uint64 bytesReceived atomic.Uint64 throttleWaits atomic.Uint64 + packUploads atomic.Uint64 + manifestUploads atomic.Uint64 + packDownloads atomic.Uint64 + manifestsDiscovered atomic.Uint64 + manifestDiscoveryErrors atomic.Uint64 + manifestLoadErrors atomic.Uint64 + actionDigestConflicts atomic.Uint64 } func (c *counters) snapshot() Stats { @@ -68,6 +82,13 @@ func (c *counters) snapshot() Stats { BytesServed: c.bytesServed.Load(), BytesReceived: c.bytesReceived.Load(), ThrottleWaits: c.throttleWaits.Load(), + PackUploads: c.packUploads.Load(), + ManifestUploads: c.manifestUploads.Load(), + PackDownloads: c.packDownloads.Load(), + ManifestsDiscovered: c.manifestsDiscovered.Load(), + ManifestDiscoveryErrors: c.manifestDiscoveryErrors.Load(), + ManifestLoadErrors: c.manifestLoadErrors.Load(), + ActionDigestConflicts: c.actionDigestConflicts.Load(), } }