# Remote cache

Share task results across machines, teammates and CI, through axle-server, an S3 bucket, an Azure container or a shared folder.

```sh
axle link <url> [--team <team>]
axle unlink
axle login [<url>] [--team <team>]
axle logout [<url>]
```

The [local cache](https://axlers.dev/docs/reference/cache.md) makes a second run on one machine instant. A remote cache does the same across machines: CI builds a commit once, and every teammate who checks it out gets the results instead of building again.

```toml
[cache.remote]
url = "https://cache.example.com"
team = "web"
```

With `[cache.remote]` in the root `axle.toml`, `axle run` and `axle watch` look in the remote cache for every task the local cache misses, and upload every result they store. A task from the remote cache is copied into the local cache, so the next hit needs no network, and its output says so:

```text
@acme/web#build  cached remotely, replaying output (6c0d5e93)
```

## Where the cache lives

`url` says where the entries are kept:

| `url`                                                      | What it is                                                                                                   |
| ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `https://…` or `http://…`                                  | an [`axle-server`](#running-axle-server), or any server that speaks the [HTTP API](#the-http-api)            |
| `s3://bucket/prefix`                                       | a bucket of AWS S3 or a service that speaks its API, such as Cloudflare R2, Google Cloud Storage or MinIO    |
| `azure://account/container/prefix`                         | a container of Azure Blob Storage, or a service that speaks its API, such as Azurite                         |
| a folder, such as `//fileserver/axle` or `/mnt/axle-cache` | a network folder that CI and the team share; in `axle.toml`, a relative path starts at the repository's root |

`team` keeps the entries of different teams or repositories apart in one place. It defaults to `default`, and may hold up to 64 lowercase letters, digits, `-`, `_` and `.`, but not start or end with `.` or be a Windows device name, such as `con`, `nul`, `aux`, `prn`, `com1` or `lpt1`.

A bucket uses the usual AWS variables: `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and `AWS_SESSION_TOKEN` for the credentials, and `AWS_REGION` (or `AWS_DEFAULT_REGION`, `us-east-1` without either). For a service other than AWS, `AWS_ENDPOINT_URL_S3` (or `AWS_ENDPOINT_URL` without it) gives its address, such as `https://<account>.r2.cloudflarestorage.com`. The credentials need `s3:GetObject`, `s3:PutObject` and `s3:ListBucket`; without `s3:ListBucket`, AWS answers a missing entry with `403` and Axle takes it for a refusal. Entries are kept as `<prefix>/<team>/<hash>.axle`; a bucket's own lifecycle rules remove old ones.

An Azure container takes the storage account's key in `AZURE_STORAGE_KEY`, which signs each request, or a shared access signature in `AZURE_STORAGE_SAS_TOKEN`, which needs read, write and create permissions. Without either, Axle asks without credentials, which a container only answers if it's public. `AZURE_STORAGE_ENDPOINT` gives the address of a service other than Azure, such as `http://127.0.0.1:10000/devstoreaccount1` for Azurite. Entries are kept as blobs named `<prefix>/<team>/<hash>.axle`; a lifecycle management policy removes old ones.

## Reading and writing

Without a `remote:` part in the [cache mode](https://axlers.dev/docs/reference/run.md#caching), a configured remote cache is read and written. A laptop that shouldn't add entries reads only:

| `--cache`, `AXLE_CACHE` or `mode` | Local cache      | Remote cache     |
| --------------------------------- | ---------------- | ---------------- |
| `local:rw` (the default)          | read and written | read and written |
| `local:rw,remote:r`               | read and written | read only        |
| `local:rw,remote:w`               | read and written | written only     |
| `remote:off`                      | read and written | not used         |
| `none`                            | not used         | not used         |

`--force` reads neither, and still writes both.

Uploads run in the background while other tasks run. When the run ends Axle waits for those still going for up to 30 seconds, then [warns](https://axlers.dev/docs/messages/remote-cache-upload-unfinished.md) about any it had to give up on.

A network failure never fails a build. The first one prints [a warning](https://axlers.dev/docs/messages/remote-cache-unreachable.md), and the run carries on with the local cache alone. A request that makes no progress for `timeout` under `[cache.remote]`, 30 seconds unless set to something like `"10s"` or `"2m"`, counts as a network failure, so a server that has stopped answering costs a run at most that long. A token that [may only read](https://axlers.dev/docs/messages/remote-cache-read-only.md) warns once and the run keeps reading. An entry that can't be used, such as one with a signature that doesn't match, is [skipped](https://axlers.dev/docs/messages/remote-cache-entry-refused.md) and its task runs. Whatever is in the cache, Axle only writes the files an entry lists as its outputs, never inside `.git` or through a linked folder, refuses links that point outside the repository, and [stops unpacking](https://axlers.dev/docs/messages/cache-entry-too-large.md) an entry that grows past the local cache's `maxSize`.

With `--json`, a hit says where it came from, `{ "event": "cache-hit", "task", "hash", "savedMs", "source": "remote" }`, and every stored result is `{ "event": "cache-stored", "task", "hash", "remote" }`, with `remote` true when it was also handed to the remote cache.

## Settings from variables

The address, the team, the timeout and the secrets can come from variables, so CI needs no change to `axle.toml`. A variable wins over the file. `signature` and `encryption` themselves are only set in `axle.toml`, so every machine agrees on them.

| Variable                           | Setting                                                                   |
| ---------------------------------- | ------------------------------------------------------------------------- |
| `AXLE_REMOTE_CACHE_URL`            | `url`                                                                     |
| `AXLE_REMOTE_CACHE_TEAM`           | `team`                                                                    |
| `AXLE_REMOTE_CACHE_TOKEN`          | the token for an `axle-server`, which wins over one saved by `axle login` |
| `AXLE_REMOTE_CACHE_SIGNATURE_KEY`  | the secret entries are signed with                                        |
| `AXLE_REMOTE_CACHE_ENCRYPTION_KEY` | the secret entries are encrypted with                                     |
| `AXLE_REMOTE_CACHE_TIMEOUT`        | `timeout`                                                                 |

A GitHub Actions job that writes to the team's server, in a repository that uses pnpm; with npm, Yarn, Bun, nub or aube, run `axle` through that package manager instead:

```yaml
- run: pnpm axle run build test --affected
  env:
      AXLE_REMOTE_CACHE_URL: https://cache.example.com
      AXLE_REMOTE_CACHE_TOKEN: ${{ secrets.AXLE_CACHE_TOKEN }}
```

## Connecting a repository

`axle link` writes `[cache.remote]` into the root `axle.toml`, keeping the rest of the file as it is:

```text
$ axle link https://cache.example.com --team web
Linked this repository to the remote cache at https://cache.example.com for the team web and saved the address in axle.toml. Log in with axle login, or set AXLE_REMOTE_CACHE_TOKEN in CI.
```

`axle unlink` takes `[cache.remote]` out of the root `axle.toml` again, with its `team`, `signature`, `encryption` and `timeout`, and `[cache]` too when nothing else is left in it. A token saved with `axle login` stays until `axle logout`.

## Logging in

A token is never written to the repository. `axle login` asks for one, checks it with the server and saves it for that address in your user's configuration folder: `%APPDATA%\axle\tokens.json` on Windows, `~/Library/Application Support/axle/tokens.json` on macOS and `$XDG_CONFIG_HOME/axle/tokens.json` (`~/.config/axle/tokens.json` without it) on Linux, or in `AXLE_CONFIG_DIR` when it's set. On macOS and Linux only your user can read the file.

```text
$ axle login
Token:
Logged in to https://cache.example.com: this token may read from the cache. It's saved in /home/sam/.config/axle/tokens.json.
```

Without an address, both commands use `AXLE_REMOTE_CACHE_URL` or the repository's `url`, and `axle login` checks the token against `AXLE_REMOTE_CACHE_TEAM` or the repository's `team` unless `--team` names another. Only an `axle-server` takes a token: a bucket uses the `AWS_*` variables, a container the `AZURE_STORAGE_*` variables, and a folder needs nothing. The token can also be piped in, such as `echo "$TOKEN" | axle login https://cache.example.com`. `axle logout` forgets it.

## Signed and encrypted entries

```toml
[cache.remote]
url = "s3://acme-axle-cache"
signature = true
encryption = true
```

- `signature = true` signs every uploaded entry with HMAC-SHA256 and the secret in `AXLE_REMOTE_CACHE_SIGNATURE_KEY`, and refuses every download without a matching signature. Only someone with the secret can add entries the team will use, and an entry can't be moved to another task's hash.
- `encryption = true` encrypts every entry with XChaCha20-Poly1305 and the secret in `AXLE_REMOTE_CACHE_ENCRYPTION_KEY` before it leaves the machine, so the server, the bucket or the folder never sees what's inside.
- A secret is any text of at least 32 characters, such as the output of `openssl rand -base64 48`. Axle derives the actual keys from it with HKDF-SHA256, so the two settings can even share one secret. Every machine that shares the cache needs the same settings and secrets. A secret that is [missing](https://axlers.dev/docs/messages/remote-cache-key-missing.md) or [too short](https://axlers.dev/docs/messages/remote-cache-key-too-short.md) stops the run.

The local cache always keeps entries as they are.

### Builds you don't trust

Whoever can write to the cache decides what everyone who reads from it gets: a build of a pull request from a fork could store a result under the hash of a task on `main`. Give such builds a way to read and no way to write:

- with `axle-server`, a token whose access is `r` in `AXLE_SERVER_TOKENS`;
- with a bucket, credentials that may only read, and with a container, a shared access signature with only read permission;
- with either, `AXLE_CACHE=local:rw,remote:r`.

With `signature = true`, keeping `AXLE_REMOTE_CACHE_SIGNATURE_KEY` away from those builds is enough, because Axle refuses every entry that wasn't signed with it.

## Running axle-server

`axle-server` is a small HTTP server for the remote cache, in the Docker image `ghcr.io/axle-rs/axle-server` and as a binary on each GitHub release:

```sh
docker run -p 8080:8080 -v axle-cache:/data \
  -e AXLE_SERVER_TOKENS="ci:rw:$CI_TOKEN,dev:r:$DEV_TOKEN" \
  ghcr.io/axle-rs/axle-server
```

It's set up with variables:

| Variable                      | Meaning                                                                                                                                                                 | Default                   |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |
| `AXLE_SERVER_TOKENS`          | `name:access:token` items separated by commas, where access is `r` or `rw`, and may name the token's [teams](#tokens-for-some-teams); each token at least 16 characters | none                      |
| `AXLE_SERVER_OPEN`            | `1` lets anyone read and write without a token, such as on a private network; not together with tokens                                                                  | `0`                       |
| `AXLE_SERVER_STORAGE`         | a folder, or `s3://bucket/prefix` with the `AWS_*` variables above                                                                                                      | `data`, `/data` in Docker |
| `AXLE_SERVER_ADDRESS`         | the address and port to listen on                                                                                                                                       | `0.0.0.0:8080`            |
| `AXLE_SERVER_MAX_AGE`         | in a folder, entries unused for this long are removed, such as `14d` or `12h`                                                                                           | `14d`                     |
| `AXLE_SERVER_MAX_SIZE`        | in a folder, above this size the least recently used entries are removed, such as `100GB`                                                                               | `100GB`                   |
| `AXLE_SERVER_MAX_ENTRY`       | entries larger than this are refused with `413`                                                                                                                         | `1GB`                     |
| `AXLE_SERVER_HEADER_TIMEOUT`  | a connection that takes longer than this to send a request's headers is closed, such as `30s` or `2m`                                                                   | `30s`                     |
| `AXLE_SERVER_MAX_CONNECTIONS` | the most connections served at once; more wait until one closes                                                                                                         | `1024`                    |

A server with no tokens refuses to start unless `AXLE_SERVER_OPEN=1` says it's meant to be open, so a forgotten setting never exposes a cache. Tokens are compared in constant time and never logged. The server removes old entries once an hour, logs one line per request, and serves `GET /v1/health` for load balancers. `axle-server --help` lists these variables and `axle-server --version` prints its version. Put it behind a proxy that terminates HTTPS when it's reached over the internet.

### Tokens for some teams

A token without teams may use every team. To keep one to some teams, put them after its access with `@`, separated by `+`:

```sh
AXLE_SERVER_TOKENS="ci:rw:$CI_TOKEN,web-ci:rw@web:$WEB_TOKEN,docs:r@docs+guides:$DOCS_TOKEN"
```

Here `ci` reads and writes every team, `web-ci` reads and writes only `web`, and `docs` only reads `docs` and `guides`. Asked for another team, the server answers `403` with `{ "error": "the token may not use the team api" }`, and Axle [warns](https://axlers.dev/docs/messages/remote-cache-unreachable.md) once and carries on with the local cache.

## The HTTP API

Any server that answers these requests works as a remote cache. Every request but `health` carries `Authorization: Bearer <token>`, and `team` defaults to `default`.

| Request                             | Answer                                                                          |
| ----------------------------------- | ------------------------------------------------------------------------------- |
| `GET /v1/health`                    | `200` with `{ "status": "ok", "version" }`                                      |
| `GET /v1/status?team=<team>`        | `200` with `{ "access": "r" }` or `{ "access": "rw" }`, `401` for a wrong token |
| `HEAD /v1/cache/<hash>?team=<team>` | `200` if the entry exists, `404` if not                                         |
| `GET /v1/cache/<hash>?team=<team>`  | `200` with the entry's bytes, `404` if not                                      |
| `PUT /v1/cache/<hash>?team=<team>`  | `201` once stored, `403` for a read-only token, `413` if it's too large         |
| `DELETE /v1/cache?team=<team>`      | `200` with the `{ "entries", "bytes" }` removed, `403` for a read-only token    |

`DELETE` takes `olderThan=<seconds>` to remove only the entries not used for that long, as [`axle cache clean --remote`](https://axlers.dev/docs/reference/cache.md#the-remote-cache) does. `<hash>` is 64 lowercase hexadecimal characters, and a wrong hash or team is `400`. A token that may not use the team gets `403` for every request. Errors carry `{ "error": "…" }`; Axle shows the error of a `403`, and takes a `403` to an upload as a read-only token unless its error says otherwise. An entry is a file the server never looks inside: `AXLE`, a format version and flags for signing and encryption, then the signature and nonce when there are any, then the compressed entry.
