# Remote S3 storage

spill can store verified torrent pieces directly as individual objects in an
S3-compatible bucket instead of local payload files, using its built-in HTTPS
(`reqwest`/`rustls`) and AWS SigV4 client.

Remote storage is designed for downloading and seeding large payloads without
holding them on local disk. Objects store raw piece bytes—not reconstructed
torrent files—so to materialize the actual files onto a local filesystem, use
[`spill extract`](#extracting-to-local-files).

## How it works

- **No local disk staging:** in-flight blocks are assembled in memory under a
  shared `assembly_bytes` budget, verified against the torrent's piece hashes,
  and uploaded with an `x-amz-checksum-sha256` integrity header.
- **Guarded reads:** each committed piece is recorded in `catalog.sqlite`
  together with an immutable object guard (either a strong ETag or an S3
  version ID). Every upload read verifies that guard (`If-Match` or
  `versionId`) and the returned `Content-Range`, so silently replaced objects
  are never served to peers.
- **v1, v2, and hybrid support:** remote storage supports all three formats,
  including serving BEP 52 Merkle hash proofs from stored pieces.

## Configuration

Add a `[remote_storage]` table to your TOML config (see
[Configuration](configuration.md#remote-s3-storage-remote_storage) for every
key) and supply credentials via environment variables:

- `AWS_ACCESS_KEY_ID` (required)
- `AWS_SECRET_ACCESS_KEY` (required)
- `AWS_SESSION_TOKEN` (optional)

`endpoint` must be an HTTPS origin without a path or query string, and `prefix`
must be dedicated to spill.

### Example: Cloudflare R2

```toml
[remote_storage]
endpoint = "https://<account-id>.r2.cloudflarestorage.com"
region = "auto"
bucket = "spill-pieces"
prefix = "host-a"
guard = "StableEtag"
path_style = true
```

For a systemd user service, store credentials in a mode `0600` file (for
example `~/.config/spill/r2.env` containing `AWS_ACCESS_KEY_ID=…` and
`AWS_SECRET_ACCESS_KEY=…`) and load it from a drop-in unit:

```ini
# ~/.config/systemd/user/spill.service.d/40-r2-storage.conf
[Service]
EnvironmentFile=%h/.config/spill/r2.env
```

### Example: AWS S3 (versioned bucket)

```toml
[remote_storage]
endpoint = "https://s3.us-east-1.amazonaws.com"
region = "us-east-1"
bucket = "my-spill-pieces"
prefix = "host-a"
guard = "Version"
path_style = false
```

### Choosing `guard`

- **`"StableEtag"`:** use only on providers where identical single-part PUTs
  return the same strong ETag and objects under `prefix` are not overwritten
  externally (for example Cloudflare R2).
- **`"Version"`:** use on buckets with object versioning enabled where every
  object version referenced by a restorable catalog snapshot is retained.

## Adding and inspecting remote torrents

- **CLI:** pass `--remote` to `spill add` (cannot be combined with `--output`):
  ```sh
  spill add archive.torrent --remote
  spill add 'magnet:?xt=urn:btih:…' --remote
  ```
- **Web UI:** enable **Store pieces in remote S3 bucket** in the Add dialog.
  Remote torrents display an **S3** badge in the table, the bucket/prefix
  banner in the **Files** tab, and live S3 request/retry counters in
  **Overview**.
- **Telemetry:** inspect per-torrent S3 counters with:
  ```sh
  spill --json get ID | jq '.transfer.storage.s3'
  ```
  See [Runtime diagnostics in JSON](cli.md#runtime-diagnostics-in-json) for the
  `put`, `get`, and `proof_get` fields.

## Caching, memory, and egress tradeoffs

- **Read cache and coalescing:** all remote torrents on a destination share a
  64 MiB LRU read cache of 512 KiB chunks with in-flight singleflight
  coalescing. Sequential and multi-peer seeding serves up to 32 blocks per S3
  GET instead of one GET per 16 KiB block.
- **Read amplification:** an isolated cold 16 KiB block read fetches up to
  512 KiB from the bucket (up to 32× amplification if neighboring blocks are
  never requested). This cuts request counts on zero-egress stores such as R2,
  but increases transferred bytes on providers that bill per-GB egress.
- **Concurrency:** remote torrents share 64 concurrent S3 GET slots and 64
  concurrent S3 PUT slots per configured destination. Each torrent caps its own
  in-flight GETs at `read_window` (`1`–`32`, default `4`).
- **Piece size limit:** each active piece reserves twice its logical length in
  `assembly_bytes` through PUT acknowledgement, so the largest supported remote
  piece is `assembly_bytes / 2`. By default `assembly_bytes` is 5% of
  host/cgroup memory (capped at 512 MiB, or 96 MiB if memory cannot be
  detected). Increase `assembly_bytes` if you need to add remote torrents with
  larger piece sizes.

## Extracting to local files

To download and reconstruct a complete remote torrent's files onto a local
filesystem directly from the bucket (without running a second BitTorrent
client):

```sh
# Against the default catalog without a config file (reads endpoint/bucket/prefix/guard from SQLite):
spill extract ID --output ./downloads --region auto --path-style

# Or using your existing daemon config (reuses region, path_style, ca_bundle, and state_dir):
spill extract ID --config ~/.config/spill/spill.toml --output ./downloads

# Or on another machine from an exported catalog snapshot (no daemon or config needed):
spill extract ID --catalog snapshot.sqlite --output ./downloads --region auto --path-style
```

`spill extract` accepts the torrent's full ID, hash alias, or unambiguous
prefix, supplies S3 credentials from the same `AWS_*` environment variables,
validates the destination binding and piece guards (`If-Match` / `versionId`),
verifies every piece's cryptographic hash, and writes files using spill's
sanitized local paths without overwriting existing files. When `--config` is
omitted, `--region` defaults to `AWS_REGION` / `AWS_DEFAULT_REGION` (pass
`--path-style` for path-style providers such as R2, and `--ca-bundle` if using
a custom CA). On error or `Ctrl-C`, partial files created by the run are
removed. Pass `--json` for structured output (`id`, `name`, `output_dir`,
`pieces`, `total_bytes`).

## Backup, restore, and limits

- **Catalog backups are required for recovery:** bucket objects alone do not
  store the verified piece bitmap or pinned object guards. Back up the catalog
  regularly with [`spill export-catalog`](cli.md#catalog-backup-and-restore)
  and restore into an empty `state_dir` with `spill restore-catalog` using the
  same `endpoint`, `bucket`, `prefix`, and `guard` mode. Restoring and starting
  a complete remote torrent requires zero S3 requests until peers request
  blocks.
- **No `recheck` or remote deletion:** `spill recheck ID` and
  `spill remove ID --delete-payload` are rejected for remote torrents. Running
  `spill remove ID` removes the torrent from the catalog and leaves all bucket
  objects untouched; reclaim storage directly in your bucket when objects are
  no longer needed.
- **Error handling:** transient errors (`429`, `5xx`, or transport resets)
  retry up to 3 attempts with backoff (honoring `Retry-After`). Permanent
  errors (`401`/`403`, `404`, `412`, or destination binding mismatches) pause
  the torrent with `last_error` instead of retrying indefinitely.

To use S3 piece storage directly from Rust without the daemon, see
[Remote S3 destination](library.md#remote-s3-destination).
