diff --git a/.github/scripts/start-moto-s3.sh b/.github/scripts/start-moto-s3.sh new file mode 100644 index 00000000..2c658c44 --- /dev/null +++ b/.github/scripts/start-moto-s3.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Start the CI S3 emulator (moto in server mode) on http://127.0.0.1:5000 as +# container `moto-s3`, storing objects in memory. Point a client at it with +# endpoint_url=http://127.0.0.1:5000 and any credentials: moto checks none. +# The image is pinned by digest, so the registry only carries the bytes: the +# daemon verifies them against the digest wherever they come from. Each +# registry's anonymous quota is per source IP and hosted runners share IPs, so +# the pull walks MOTO_REPOS in order, twice, and uses the first that serves it. +# +# CI: bash .github/scripts/start-moto-s3.sh +# Local: bash .github/scripts/start-moto-s3.sh (needs docker and a free port 5000) +# Test: put a stub `docker` first on PATH; MOTO_DIGEST / MOTO_REPOS override the pin. +set -u + +# motoserver/moto 5.2.6 multi-arch index, resolved 2026-12-03. +# Every registry listed serves this digest. Renovate does not bump it. +MOTO_DIGEST=${MOTO_DIGEST:-sha256:344e076f31ad1f5ff1ec4492f741e7d42911d1c7a1ef9b1590f56c340b968513} +MOTO_REPOS=${MOTO_REPOS:-mirror.gcr.io/motoserver/moto ghcr.io/getmoto/motoserver docker.io/motoserver/moto} + +image= +for round in 1 2; do + for repo in $MOTO_REPOS; do + if timeout 120 docker pull "$repo@$MOTO_DIGEST"; then image=$repo@$MOTO_DIGEST; break 2; fi + done + [ "$round" = 1 ] && sleep 15 +done +[ -n "$image" ] || { echo "::error::no registry served moto@${MOTO_DIGEST} (tried: ${MOTO_REPOS})"; exit 1; } + +docker run -d --name moto-s3 -p 5000:5000 "$image" || exit 1 + +# Ready when the server answers its own API on the published port. The 30s +# deadline covers the probes too, so a server that never comes up, or accepts +# but never answers, fails this step instead of hanging the job. +deadline=$((SECONDS + 30)) +while [ "$SECONDS" -lt "$deadline" ]; do + if curl --silent --fail --max-time 2 --output /dev/null http://127.0.0.1:5000/moto-api/; then + exit 0 + fi + sleep 1 +done +echo "::error::moto did not answer on 127.0.0.1:5000 within 30s" +docker logs moto-s3 +exit 1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a5afd931..d437bdfc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -167,6 +167,12 @@ jobs: if: github.event_name == 'push' run: bash .github/scripts/start-fake-gcs.sh + # Push runs only: tests/integration/test_s3_integration.py skips its whole module when + # nothing answers on 127.0.0.1:5000. + - name: Start the S3 emulator + if: github.event_name == 'push' + run: bash .github/scripts/start-moto-s3.sh + - name: Run full test suite (main) if: github.event_name == 'push' env: @@ -196,6 +202,10 @@ jobs: if: github.event_name == 'push' run: python3 .github/scripts/assert-junit-ran.py junit.xml tests.integration.test_gcs_integration + - name: Check the S3 integration tests ran + if: github.event_name == 'push' + run: python3 .github/scripts/assert-junit-ran.py junit.xml tests.integration.test_s3_integration + # Executable docs are tests: docstring examples, tests/docs/ and the docs/ # markdown blocks. None of them sit under tests/unit or tests/critical, so # the runs above never collect them. diff --git a/README.md b/README.md index 07a974bc..531e029e 100644 --- a/README.md +++ b/README.md @@ -226,7 +226,7 @@ def test_cached_function(): ```bash # Backend selection: set exactly ONE of CACHEKIT_REDIS_URL, CACHEKIT_API_KEY, -# CACHEKIT_MEMCACHED_SERVERS, CACHEKIT_FILE_CACHE_DIR, CACHEKIT_GCS_BUCKET. Two or more is a ConfigurationError at +# CACHEKIT_MEMCACHED_SERVERS, CACHEKIT_FILE_CACHE_DIR, CACHEKIT_GCS_BUCKET, CACHEKIT_S3_BUCKET. Two or more is a ConfigurationError at # first call, and decorators relying on env auto-detection run uncached (docs/backends/README.md). # REDIS_URL is only a fallback and never conflicts. With none of them set, decorators cache # L1-only, in process (encrypted decorators still use localhost Redis; interop decorators refuse @@ -252,6 +252,13 @@ CACHEKIT_MEMCACHED_KEY_PREFIX="myapp:" # Default: "" (none) CACHEKIT_GCS_PREFIX="cachekit/" # Default: "" (bucket root) CACHEKIT_GCS_TIMEOUT=10.0 # Default: 10.0 seconds +# S3 Backend (optional: pip install cachekit[s3]; boto3's default credential chain) +# CACHEKIT_S3_BUCKET="my-cache-bucket" # Required to select it +CACHEKIT_S3_PREFIX="cachekit/" # Default: "" (bucket root) +CACHEKIT_S3_REGION="eu-west-2" # Default: none (boto3's own lookup) +# CACHEKIT_S3_ENDPOINT_URL="https://s3.example.com" # Default: none (AWS S3); set for an S3-compatible store +CACHEKIT_S3_TIMEOUT=10.0 # Default: 10.0 seconds + # Optional Configuration CACHEKIT_MAX_VALUE_SIZE=104857600 CACHEKIT_ARROW_COMPRESSION=zstd @@ -270,6 +277,7 @@ backend that fits your infrastructure — they're peers behind the same `@cache` | CacheKit Cloud | Managed, zero-ops (closed beta) | `CACHEKIT_API_KEY` | | Memcached | High-throughput, existing infra | `CACHEKIT_MEMCACHED_SERVERS` | | Google Cloud Storage | Durable results on Cloud Run and jobs, no server | `CACHEKIT_GCS_BUCKET` | +| S3 | Durable results on Lambda, ECS tasks and batch jobs, no server; or an S3-compatible store | `CACHEKIT_S3_BUCKET` | | File / L1-only | Local dev, tests, no external deps | `CACHEKIT_FILE_CACHE_DIR` / nothing (or `backend=None`) | ```bash @@ -361,6 +369,28 @@ One object per entry, in the file backend's format. See [Google Cloud Storage Ba +
+S3 — Optional + +```python notest +from cachekit import cache +from cachekit.backends.s3 import S3Backend, S3BackendConfig + +# pip install cachekit[s3] + +backend = S3Backend(S3BackendConfig(bucket="my-cache-bucket")) # boto3's default credential chain + +@cache(backend=backend, ttl=3600) +def expensive_api_call(user_id: int): + return fetch_user_data(user_id) +``` + +One object per entry, in the file backend's format, in Amazon S3 or an S3-compatible store (`endpoint_url`). See [S3 Backend](docs/backends/s3.md) for IAM and the bucket lifecycle rule. + +*Requires: `pip install cachekit[s3]` or `uv add cachekit[s3]`* + +
+ > **CacheKit Cloud (Closed Beta)** > Managed caching with zero infrastructure. L1+L2 caching, circuit breaker, and automatic failover — no Redis to manage. > *CacheKit Cloud is in closed beta: sign-up is by waitlist at [dash.cachekit.io](https://dash.cachekit.io).* @@ -401,7 +431,7 @@ See [SECURITY.md][security-url] for vulnerability reporting and detailed documen - Connection pooling with thread affinity - The CacheKit Cloud backend keeps idle connections pooled until the server closes them, with TCP keepalive probes, so a request after a pause skips a new TLS handshake - Distributed locking guards against cache stampedes across pods, best effort (async functions, on a backend that supports it) -- Pluggable backend abstraction (Redis, CacheKit Cloud, File, Memcached, Google Cloud Storage, custom) +- Pluggable backend abstraction (Redis, CacheKit Cloud, File, Memcached, Google Cloud Storage, S3, custom) - Untrusted-decode bounds: nesting depth and header-declared allocation are capped on every cache read (a forged entry is a bounded cache miss), verified against the protocol's shared [`decode-bounds.json`](https://github.com/cachekit-io/protocol/blob/42ea601f3c1656df0a06904afa2406604f43f57d/test-vectors/decode-bounds.json) vectors > [!NOTE] diff --git a/docs/README.md b/docs/README.md index 885dde84..3d3164d1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -32,6 +32,7 @@ Choose your storage backend: | [File](backends/file.md) | Local filesystem, zero dependencies | | [Memcached](backends/memcached.md) | High-throughput, consistent hashing | | [Google Cloud Storage](backends/gcs.md) | Durable, one object per entry, no server | +| [S3](backends/s3.md) | Durable, one object per entry, no server; Amazon S3 and S3-compatible stores | | [CacheKit Cloud](backends/cachekitio.md) | Managed, zero infrastructure | | [L1-Only (None)](backends/none.md) | In-memory only, no external services | | [Custom](backends/custom.md) | Implement your own backend | @@ -92,6 +93,7 @@ docs/ │ ├── redis.md, file.md # Built-in backends │ ├── memcached.md, cachekitio.md # Optional backends │ ├── gcs.md # Google Cloud Storage (optional) +│ ├── s3.md # Amazon S3 and S3-compatible stores (optional) │ ├── none.md # L1-only mode │ └── custom.md # Custom backend guide │ diff --git a/docs/api-reference.md b/docs/api-reference.md index 15781278..ca42485a 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -711,7 +711,7 @@ For error examples and handling patterns, see [Troubleshooting Guide](troublesho ## Backend Abstraction -cachekit uses a protocol-based backend abstraction (PEP 544) that allows pluggable storage backends for L2 cache. Built-in backends include Redis, CacheKit Cloud, File, Memcached, and Google Cloud Storage. You can also implement custom backends for any key-value store. +cachekit uses a protocol-based backend abstraction (PEP 544) that allows pluggable storage backends for L2 cache. Built-in backends include Redis, CacheKit Cloud, File, Memcached, Google Cloud Storage, and S3. You can also implement custom backends for any key-value store. For comprehensive backend guide with examples and implementation patterns, see **[Backend Guide](backends/README.md)**. diff --git a/docs/backends/README.md b/docs/backends/README.md index fe16f788..9c093ffb 100644 --- a/docs/backends/README.md +++ b/docs/backends/README.md @@ -2,7 +2,7 @@ # Backend Guide -Pluggable L2 cache storage for cachekit. Five backends are included out of the box — Redis, File (local), Memcached, Google Cloud Storage, and CacheKit Cloud (managed). With no backend configured, a plaintext decorator runs in [L1-only mode](none.md), as `backend=None` does; encrypted and interop decorators still need a backend ([Nothing Configured](#4-nothing-configured-l1-only)). You can also implement custom backends for any key-value store. +Pluggable L2 cache storage for cachekit. Six backends are included out of the box — Redis, File (local), Memcached, Google Cloud Storage, S3, and CacheKit Cloud (managed). With no backend configured, a plaintext decorator runs in [L1-only mode](none.md), as `backend=None` does; encrypted and interop decorators still need a backend ([Nothing Configured](#4-nothing-configured-l1-only)). You can also implement custom backends for any key-value store. ## Overview @@ -99,6 +99,7 @@ class BaseBackend(Protocol): | **[Redis](redis.md)** | One network round trip per operation ([not measured here](../performance.md#not-measured-here)) | Yes (RDB/AOF) | Yes | Yes | Yes | | **[Memcached](memcached.md)** | One network round trip per operation ([not measured here](../performance.md#not-measured-here)) | No | Yes | Yes (max 30d) | No | | **[Google Cloud Storage](gcs.md)** | One HTTPS request to GCS per ordinary operation ([request counts](gcs.md#requests-per-operation); [not measured here](../performance.md#not-measured-here)) | Yes | Yes | Yes (checked on read) | No | +| **[S3](s3.md)** | One HTTPS request to S3 per operation ([request counts](s3.md#requests-per-operation); [not measured here](../performance.md#not-measured-here)) | Yes | Yes | Yes (checked on read) | No | | **[CacheKit Cloud](cachekitio.md)** | 42–45ms p50 hit, measured from MEL ([varies by vantage](cachekitio.md#characteristics)) | Yes | Yes | Yes | Yes | | **[HTTP (custom)](custom.md)** | One HTTP request per operation ([not measured here](../performance.md#not-measured-here)) | Varies | Yes | Varies | Varies | | **[DynamoDB (custom)](custom.md)** | One DynamoDB API request per operation ([not measured here](../performance.md#not-measured-here)) | Yes | Yes | Yes | No | @@ -109,6 +110,8 @@ class BaseBackend(Protocol): `refresh_ttl_on_get` does not apply to it (see [Memcached](memcached.md#ttl-inspection--refresh)). **Google Cloud Storage** supports neither: an object cannot be edited in place (see [Google Cloud Storage](gcs.md#limitations)). +**S3** supports neither, for the same reason +(see [S3](s3.md#limitations)). **Cross-process whole-function invalidation** (a server-side key registry, via the `KeyTrackableBackend` protocol): supported only by the tenant-scoped **Redis** backend that env @@ -142,6 +145,12 @@ calling process knows (see [Whole-Function Invalidation](../features/l1-invalida - The cached call is expensive and its result is worth keeping for hours or days - A round trip to GCS on each L1 miss is acceptable ([not measured here](../performance.md#not-measured-here)) +**Use [S3Backend](s3.md) when**: +- The workload runs on Lambda, ECS tasks or batch jobs, with no Redis and no disk that survives a run +- Your bucket is in an S3-compatible store rather than AWS S3: point `endpoint_url` at it ([S3-Compatible Stores](s3.md#s3-compatible-stores)) +- The cached call is expensive and its result is worth keeping for hours or days +- A round trip to S3 on each L1 miss is acceptable ([not measured here](../performance.md#not-measured-here)) + **Use [CacheKit Cloud](cachekitio.md) (`CachekitIOBackend`) when** *(closed beta: sign-up is by waitlist at [dash.cachekit.io](https://dash.cachekit.io))*: - You want managed, zero-ops distributed caching - Multi-region caching without operating Redis @@ -228,7 +237,7 @@ it builds its own `CachekitIOBackend` and never consults `set_default_backend()` If no explicit backend and no module-level default, `DefaultBackendProvider` picks a backend at the function's first call from the one environment selector that is -set. The five prefixed selectors are mutually exclusive, with no precedence between them: +set. The six prefixed selectors are mutually exclusive, with no precedence between them: set exactly one. | Environment variable | Backend | @@ -238,6 +247,7 @@ set exactly one. | `CACHEKIT_MEMCACHED_SERVERS`| `MemcachedBackend` | | `CACHEKIT_FILE_CACHE_DIR` | `FileBackend` | | `CACHEKIT_GCS_BUCKET` | `GCSBackend` | +| `CACHEKIT_S3_BUCKET` | `S3Backend` | | none of the above: `REDIS_URL` | Redis, as above | | nothing set at all | plaintext, non-interop decorators: [L1-only](#4-nothing-configured-l1-only), no backend; secure and `encryption=True` decorators: Redis at `redis://localhost:6379`, tenant-scoped as above; `interop=` decorators: the same Redis, which interop refuses (see below) | @@ -246,7 +256,7 @@ set exactly one. `backend=RedisBackend()` instead ([Interop Mode](../features/interop-mode.md)). A `CachekitIOBackend` from `CACHEKIT_API_KEY` prefixes nothing and serves interop as resolved. -Setting more than one of the five `CACHEKIT_*` selectors is ambiguous and raises +Setting more than one of the six `CACHEKIT_*` selectors is ambiguous and raises `ConfigurationError` at first call. The decorator catches it, logs a WARNING on the `cachekit.decorators.orchestrator` logger, and runs the function uncached: @@ -425,6 +435,7 @@ first call (and runs uncached if nothing listens there): give it `backend=RedisB | **DynamoDB** | One DynamoDB API request per operation ([not measured here](../performance.md#not-measured-here)) | Serverless, low-traffic | High availability | | **Memcached** | One network round trip per operation ([not measured here](../performance.md#not-measured-here)) | Alternative to Redis | No persistence | | **Google Cloud Storage** | One HTTPS request to GCS per ordinary operation ([request counts](gcs.md#requests-per-operation); [not measured here](../performance.md#not-measured-here)) | Expensive results kept across runs, no server | No locking; expiry checked on read | +| **S3** | One HTTPS request to S3 per operation ([request counts](s3.md#requests-per-operation); [not measured here](../performance.md#not-measured-here)) | Expensive results kept across runs, no server; S3-compatible stores | No locking; expiry checked on read; only the lifecycle rule removes expired entries | --- @@ -434,6 +445,7 @@ first call (and runs uncached if nothing listens there): give it `backend=RedisB - [File Backend](file.md) — Local disk, single-process, no infrastructure - [Memcached Backend](memcached.md) — High-throughput, volatile, multi-process - [Google Cloud Storage Backend](gcs.md) — Durable, one object per entry, no server +- [S3 Backend](s3.md) — Durable, one object per entry, no server; Amazon S3 and S3-compatible stores - [CacheKit Cloud Backend](cachekitio.md) — Managed, zero-ops, zero-knowledge - [Custom Backends](custom.md) — HTTP, DynamoDB, and your own implementations diff --git a/docs/backends/gcs.md b/docs/backends/gcs.md index 9bbd1345..2c228ddb 100644 --- a/docs/backends/gcs.md +++ b/docs/backends/gcs.md @@ -181,6 +181,7 @@ STORAGE_EMULATOR_HOST=http://localhost:4443 uv run pytest tests/integration/test - [Backend Guide](README.md) — Backend comparison and resolution priority - [File Backend](file.md) — The same entry format on local disk +- [S3 Backend](s3.md) — The same entry format in an S3 bucket - [Redis Backend](redis.md) — Low-latency shared caching with locking support - [Configuration Guide](../configuration.md) — Full environment variable reference diff --git a/docs/backends/s3.md b/docs/backends/s3.md new file mode 100644 index 00000000..c4b7aaf0 --- /dev/null +++ b/docs/backends/s3.md @@ -0,0 +1,245 @@ +**[Home](../README.md)** › **[Backends](README.md)** › **S3 Backend** + +# S3 Backend + +> Requires: `pip install cachekit[s3]` + +Store each cache entry as one object in an Amazon S3 bucket, or in any store that serves the S3 API at an endpoint you name. Durable, shared across processes and machines, and needs no server to run: a fit for jobs and services that keep no local disk between runs and have no Redis. + +## Basic Usage + +```python notest +from cachekit import cache +from cachekit.backends.s3 import S3Backend, S3BackendConfig + +backend = S3Backend(S3BackendConfig(bucket="my-cache-bucket", region="eu-west-2")) + +@cache(backend=backend, ttl=3600) +def cached_function(): + return expensive_computation() +``` + +Or select it from the environment, with no `backend=`: + +```bash +export CACHEKIT_S3_BUCKET="my-cache-bucket" +``` + +`CACHEKIT_S3_BUCKET` is a backend selector like `CACHEKIT_REDIS_URL` or `CACHEKIT_FILE_CACHE_DIR`: set exactly one of them ([Backend Resolution Priority](README.md#backend-resolution-priority)). + +## Configuration via Environment Variables + +```bash +export CACHEKIT_S3_BUCKET="my-cache-bucket" # Required. A bucket name, not an s3:// URL +export CACHEKIT_S3_PREFIX="cachekit/" # Default: "" (objects at the bucket root) +export CACHEKIT_S3_REGION="eu-west-2" # Default: none (boto3 looks for AWS_DEFAULT_REGION, then the shared config file) +export CACHEKIT_S3_ENDPOINT_URL="https://s3.example.com" # Default: none (AWS S3) +export CACHEKIT_S3_TIMEOUT=10.0 # Default: 10.0 seconds (range: 0.1-600.0) +``` + +## Configuration via Python + +Config objects need neither credentials nor the `s3` extra: + +```python +from cachekit.backends.s3 import S3BackendConfig + +config = S3BackendConfig( + bucket="my-cache-bucket", + prefix="cachekit/", + region="eu-west-2", + timeout=5.0, +) +``` + +`timeout` is how long to wait for a connection, and between bytes of a response. It is not a +deadline for the whole request. + +Set `region` to the bucket's own region. With the wrong one, AWS answers the first request with a redirect, and the client looks the region up and sends the request again: extra requests on a backend that otherwise sends one per operation. + +## Authentication + +The backend authenticates through [boto3's default credential chain](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html) and has no credential settings of its own: + +- **On AWS** (ECS, EKS, EC2, Lambda): the role attached to the workload. Nothing to configure. +- **Anywhere else**: `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` in the environment, or a profile in the shared credentials file, chosen with `AWS_PROFILE`. + +Building the backend sends no request to S3. A missing credential raises an AUTHENTICATION `BackendError` on the first operation; under `@cache`, a failed read is a miss and the function runs. + +## IAM + +The identity needs three actions on the objects and one on the bucket: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], + "Resource": "arn:aws:s3:::my-cache-bucket/*" + }, + { + "Effect": "Allow", + "Action": "s3:ListBucket", + "Resource": "arn:aws:s3:::my-cache-bucket" + } + ] +} +``` + +> [!WARNING] +> `s3:ListBucket` is not optional. Without it, S3 answers a read of an absent object with 403 instead of 404, so every cache miss raises an AUTHENTICATION `BackendError` instead of returning a miss. `health_check()` lists the bucket, so call it when your service starts and it reports the missing permission. + +The bucket must already exist: the backend does not create it. + +## S3-Compatible Stores + +Set `endpoint_url` to address a store other than AWS S3, and `region` to the value that store documents: + +```python +from cachekit.backends.s3 import S3BackendConfig + +config = S3BackendConfig( + bucket="my-cache-bucket", + endpoint_url="https://s3.example.com", + region="us-east-1", +) +``` + +Credentials come from the same chain, so the store's access key goes in `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`. With an `endpoint_url`, requests name the bucket in the path (`https://s3.example.com/my-cache-bucket/`). + +The backend uses four S3 operations: `GetObject` (whole, and with a `Range` header), `PutObject`, `DeleteObject` and `ListObjectsV2`. This repository's tests run it against the [moto](https://github.com/getmoto/moto) emulator; no other store is tested here, so check yours with `health_check()` and a round trip before relying on it. + +> [!NOTE] +> boto3 adds a CRC32 checksum to each upload and asks for one on each download. Over HTTPS the upload carries it as a trailer after an `aws-chunked` body. A store that refuses either answers with an error on `set`; `AWS_REQUEST_CHECKSUM_CALCULATION=when_required` and `AWS_RESPONSE_CHECKSUM_VALIDATION=when_required` turn them off. + +## Object Names and the Prefix + +An entry's object key is the prefix followed by 32 hex characters, the BLAKE2b-128 hash of the cache key: + +``` + +cachekit/0e2a03b49262c15a063c04d5a29c0158 +``` + +The prefix is used verbatim, so end it with `/` if you want a folder. It is a storage location only, like the file backend's `cache_dir`: it does not change the cache key, and two backends with different prefixes on one bucket never see each other's entries. + +The object holds the bytes the [File backend](file.md) writes for the same key, value and expiry: the [file-backend format](https://github.com/cachekit-io/protocol/blob/main/spec/file-backend-format.md) of the CacheKit protocol, a 14-byte header that carries the expiry, then the payload. A cache directory copied into the bucket with `aws s3 sync`, or a bucket prefix copied to a directory, stays readable from the other backend. So does a bucket written by the [Google Cloud Storage backend](gcs.md). + +## Expiry and the Lifecycle Rule + +Expiry lives in each object's header and is checked when the entry is read. An expired entry is a miss, and it stays in the bucket: **the backend never deletes on a read.** Removing an expired entry safely needs a delete that is conditional on the object the read saw, and not every S3-compatible store honours a conditional `DeleteObject`. Without one, a reader that removed an expired entry could remove one a writer stored a moment later. + +A bucket lifecycle rule is therefore the only thing that removes expired entries. Give the bucket one, with `Days` above your longest TTL (here 8 days, for TTLs of up to 7) and a `Filter` whose `Prefix` is the backend's `prefix` (here `cachekit/`): + +```json +{ + "Rules": [ + { + "ID": "expire-cachekit-entries", + "Status": "Enabled", + "Filter": {"Prefix": "cachekit/"}, + "Expiration": {"Days": 8} + } + ] +} +``` + +```bash +aws s3api put-bucket-lifecycle-configuration --bucket my-cache-bucket \ + --lifecycle-configuration file://lifecycle.json +``` + +`Days` counts from when the object was written, and storing an entry again writes a new object. The rule removes only the objects whose keys begin with its `Prefix`, so set it to exactly the backend's `prefix`: a longer or different one leaves entries behind, and a shorter one also removes whatever else is stored under it. With no `prefix` configured, entries sit at the bucket root: use `"Filter": {"Prefix": ""}`, which covers every object in the bucket. + +> [!CAUTION] +> `put-bucket-lifecycle-configuration` replaces the bucket's whole lifecycle configuration. If the bucket already has rules, read them first (`aws s3api get-bucket-lifecycle-configuration --bucket my-cache-bucket`) and apply a file that holds them and the cache rule together. + +> [!WARNING] +> The rule deletes by age alone. An entry cached with no TTL, or with a TTL longer than `Days`, is deleted when it reaches `Days` and becomes a miss. + +> [!WARNING] +> Use a bucket without versioning. On a versioned bucket every `set` keeps the previous object as a noncurrent version, and `Expiration` only hides the current one, so the bucket grows until the rule also carries a `NoncurrentVersionExpiration`. + +## Requests per Operation + +| Operation | Requests | +|-----------|----------| +| `get` | One `GetObject`, with no `HeadObject` first. A hit, a miss, an expired entry and an absent object each cost one request. | +| `set` | One `PutObject` that replaces the object, whatever its size. No multipart upload. | +| `exists` | One `GetObject` with `Range: bytes=0-13`, the 14-byte header. | +| `delete` | One `DeleteObject`. | +| `health_check()` | One `ListObjectsV2` of at most one object under the prefix. | + +The backend retries no request: botocore's retries are off, whatever `AWS_MAX_ATTEMPTS` and `AWS_RETRY_MODE` say. Two things outside the backend can add requests: a wrong `region` (see [Configuration via Python](#configuration-via-python)), and a credential provider refreshing a temporary credential. A failed request raises a `BackendError`: + +| Failure | `BackendErrorType` | +|---------|--------------------| +| HTTP 401, 403 (`AccessDenied`, `InvalidAccessKeyId`, `SignatureDoesNotMatch`); `ExpiredToken`; credentials missing | `AUTHENTICATION` | +| HTTP 429, 5xx (`SlowDown`, `InternalError`); connection failed; credential provider unreachable; checksum mismatch | `TRANSIENT` | +| Connect or read timeout; HTTP 408; `RequestTimeout` | `TIMEOUT` | +| Any other HTTP error, such as `NoSuchBucket`; a request boto3 refuses to build | `PERMANENT` | + +A 404 for the object on a read is not an error: `get` returns `None` and `exists` returns `False`. A 404 for the bucket (`NoSuchBucket`) is one, on every operation, so a wrong bucket name raises instead of reading as an empty cache. Under `@cache`, a failed read is a miss and the function runs, and a failed write skips the backend only. + +`delete` returns `True` whenever the key is gone afterwards. S3's `DeleteObject` answers the same whether or not the object existed, so `True` does not mean an entry was there; a store that answers 404 for an absent object gets the same `True`. + +## When to Use + +**Use S3Backend when**: +- The workload runs on Lambda, ECS tasks or batch jobs: no local disk that survives, no Redis +- The cached call is expensive (seconds, or money) and its result is worth keeping for hours or days +- Several machines should share results, and a round trip to S3 on each L1 miss is acceptable + +**When NOT to use**: +- Hot paths that need low-latency reads: every L1 miss is an HTTPS request to S3 (use [Redis](redis.md) or [Memcached](memcached.md)) +- You need distributed locking for stampede protection (use [Redis](redis.md) or [CacheKit Cloud](cachekitio.md)) +- You need sliding expiration via `refresh_ttl_on_get` (see [Limitations](#limitations)) +- Many small, short-lived entries: each write is a billed S3 request, and each expired entry is stored until the lifecycle rule removes it + +## Characteristics + +- Latency: one HTTPS request to S3 per operation, which depends on your network and region ([not measured here](../performance.md#not-measured-here)) +- TTL support: Yes, checked on read; no upper bound below the file format's 10 years +- Cross-process: Yes (shared by every process that can reach the bucket) +- Persistence: Yes +- Threads: threads may share one backend +- Fork: build the backend after `fork()`, not before + +## Limitations + +1. **No TTL inspection or refresh.** An S3 object cannot be edited in place, so refreshing a TTL would rewrite the whole entry. The backend is not a `TTLInspectableBackend`: `refresh_ttl_on_get` does not apply to it (the decorator warns once and serves the hit). +2. **No locking.** No distributed lock, so no cross-process stampede protection. +3. **Last writer wins.** Two processes that store the same key at once each upload a whole object, and the later upload replaces the earlier one. A reader sees one or the other, never a mix. +4. **Whole-function invalidation is per process.** `invalidate_cache()` with no arguments deletes only the keys the calling process knows ([Whole-Function Invalidation](../features/l1-invalidation.md#whole-function-invalidation)). +5. **No eviction, no size cap, no cleanup on read.** The bucket grows until the lifecycle rule deletes entries. +6. **Encrypted entries are not bound to their location.** `@cache.secure` binds each entry to its cache key. The bucket and the prefix are not part of that binding, as with the file backend's directory. +7. **No S3 Express One Zone directory buckets.** Not tested, not supported. + +## Testing Against an Emulator + +The backend runs unchanged against [moto](https://github.com/getmoto/moto) in server mode, with made-up credentials: + +```bash +bash .github/scripts/start-moto-s3.sh +uv run pytest tests/integration/test_s3_integration.py +``` + +`S3_EMULATOR_ENDPOINT` points the tests at another endpoint than `http://127.0.0.1:5000`. + +## See Also + +- [Backend Guide](README.md) — Backend comparison and resolution priority +- [File Backend](file.md) — The same entry format on local disk +- [Google Cloud Storage Backend](gcs.md) — The same entry format in a GCS bucket +- [Redis Backend](redis.md) — Low-latency shared caching with locking support +- [Configuration Guide](../configuration.md) — Full environment variable reference + +--- + +
+ +**[GitHub Issues](https://github.com/cachekit-io/cachekit-py/issues)** · **[Documentation](../README.md)** + +
diff --git a/docs/comparison.md b/docs/comparison.md index 35ed97bd..e192ab55 100644 --- a/docs/comparison.md +++ b/docs/comparison.md @@ -168,7 +168,7 @@ sequenceDiagram **Why cachekit wins**: - **Same code**: `@cache` decorator works with or without Redis -- **Pluggable backends**: Redis, CacheKit Cloud, File, Memcached built-in, plus custom protocol +- **Pluggable backends**: Redis, CacheKit Cloud, File, Memcached, Google Cloud Storage, S3 built-in, plus custom protocol - **Graceful degradation**: Redis down? L1 cache serves, app continues - **No vendor lock-in**: Backend protocol is documented, implement your own @@ -514,7 +514,7 @@ A: Yes. Works with any framework (FastAPI, Django, Flask, etc). Metrics integrat A: The app keeps working. Redis errors are logged, and your function runs and returns its result. If Redis was down when the backend was first built, nothing is cached and repeated failures open the circuit breaker, so calls stop waiting on Redis. If Redis goes away later, L1 still caches results in-process. While the breaker is open, L1 hits are still served and a miss runs the function. **Q: Can I use my own backend?** -A: Yes. Four built-in backends (Redis, CacheKit Cloud, File, Memcached) or implement the BaseBackend protocol (~100 LOC) for custom storage. +A: Yes. Six built-in backends (Redis, CacheKit Cloud, File, Memcached, Google Cloud Storage, S3) or implement the BaseBackend protocol (~100 LOC) for custom storage. --- diff --git a/docs/configuration.md b/docs/configuration.md index 6a782e51..895e5dd5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -11,7 +11,7 @@ ## Backend Options -cachekit supports five backends. Pick the one that fits your infrastructure: +cachekit supports six backends. Pick the one that fits your infrastructure: | Backend | Best For | Required Config | |---------|----------|----------------| @@ -20,8 +20,9 @@ cachekit supports five backends. Pick the one that fits your infrastructure: | File | Local dev, testing | None | | Memcached | High-throughput, existing infra | `CACHEKIT_MEMCACHED_SERVERS` | | Google Cloud Storage | Durable results on Cloud Run and jobs, no server | `CACHEKIT_GCS_BUCKET` | +| S3 | Durable results on Lambda, ECS tasks and batch jobs, no server; or an S3-compatible store | `CACHEKIT_S3_BUCKET` | -`@cache` picks its backend from env vars at a function's first call; with nothing configured it caches L1-only, in process, and connects to nothing ([details](backends/README.md#4-nothing-configured-l1-only)). CacheKit Cloud is a managed alternative (currently in closed beta). File backend is intended for local development and testing only. Memcached is an optional backend (`pip install cachekit[memcached]`), and so is Google Cloud Storage (`pip install cachekit[gcs]`). +`@cache` picks its backend from env vars at a function's first call; with nothing configured it caches L1-only, in process, and connects to nothing ([details](backends/README.md#4-nothing-configured-l1-only)). CacheKit Cloud is a managed alternative (currently in closed beta). File backend is intended for local development and testing only. Memcached is an optional backend (`pip install cachekit[memcached]`), and so are Google Cloud Storage (`pip install cachekit[gcs]`) and S3 (`pip install cachekit[s3]`). ### Redis Backend @@ -68,6 +69,14 @@ One object per cache entry in a GCS bucket, authenticated with Application Defau **Configuration:** See the [Google Cloud Storage Backend](#google-cloud-storage-backend-environment-variables) section below. +### S3 Backend + +> Requires: `pip install cachekit[s3]` + +One object per cache entry in an Amazon S3 bucket, or in an S3-compatible store named with `endpoint_url`, authenticated through boto3's default credential chain. See [S3 Backend](backends/s3.md) for IAM and the bucket lifecycle rule. + +**Configuration:** See the [S3 Backend](#s3-backend-environment-variables) section below. + --- ## Environment Variables @@ -277,6 +286,29 @@ CACHEKIT_GCS_TIMEOUT=10.0 There is no credential variable: the backend uses [Application Default Credentials](backends/gcs.md#authentication). +### S3 Backend Environment Variables + +> Requires: `pip install cachekit[s3]` or `uv add cachekit[s3]` + +```bash +# Bucket that holds the entries (required; a bucket name, not an s3:// URL). Setting it selects the backend +CACHEKIT_S3_BUCKET=my-cache-bucket + +# Object-key prefix, used verbatim (default: "", the bucket root). A storage location only +CACHEKIT_S3_PREFIX=cachekit/ + +# Region of the bucket (default: none; boto3 looks for AWS_DEFAULT_REGION, then the shared config file) +CACHEKIT_S3_REGION=eu-west-2 + +# Endpoint of an S3-compatible store (default: none, AWS S3) +CACHEKIT_S3_ENDPOINT_URL=https://s3.example.com + +# Seconds to wait for a connection, and between bytes of a response (default: 10.0, range: 0.1-600.0) +CACHEKIT_S3_TIMEOUT=10.0 +``` + +There is no credential variable: the backend uses [boto3's default credential chain](backends/s3.md#authentication). + --- ## L1 Cache Configuration @@ -440,7 +472,7 @@ def secure_function(): > [!IMPORTANT] > When multiple environment variables could apply, cachekit follows this priority order. -> The five backend selectors are the exception: they have no order, so set exactly one +> The six backend selectors are the exception: they have no order, so set exactly one > ([details](backends/README.md#3-environment-variable-auto-detection)). ### Redis URL Priority diff --git a/docs/data-flow-architecture.md b/docs/data-flow-architecture.md index d74e583c..ba159236 100644 --- a/docs/data-flow-architecture.md +++ b/docs/data-flow-architecture.md @@ -30,7 +30,7 @@ cachekit uses a hybrid Python-Rust architecture to provide production caching wi > [!TIP] > **Architecture Principles:** > - **L1 + L2 Caching**: In-memory bytes cache (L1) + pluggable backend storage (L2) for optimal performance -> - **Backend Abstraction**: Protocol-based L2 backend layer (Redis, CacheKit Cloud, File, Memcached, custom) +> - **Backend Abstraction**: Protocol-based L2 backend layer (Redis, CacheKit Cloud, File, Memcached, Google Cloud Storage, S3, custom) > - **Bytes-Only Storage**: with a backend configured, L1 stores serialized bytes (encrypted or plaintext), not Python objects; L1-only mode (`backend=None`) stores the object itself. After its first hit, a plaintext entry of the default or auto serializer with integrity checking on is held as its verified MessagePack where that is no longer than the envelope, so later hits skip the decompress and checksum, and an orjson entry as its checksummed JSON, so later hits skip the checksum; every hit still runs the bounded decode (see [Storage Architecture](#storage-architecture)); encrypted caches keep the ciphertext > - **Security First**: Decompression bomb protection, checksum validation, size limits, encrypted-at-rest > - **Performance Optimized**: Thread affinity, connection pooling, pre-cached serializers @@ -528,7 +528,7 @@ class BaseBackend(Protocol): - **Bytes-only interface**: Language-agnostic, no Python-specific types - **Stateless operations**: No connection management in protocol - **Simple and focused**: Four operations only (get/set/delete/exists) -- **Works for any backend**: Redis, CacheKit Cloud, File, Memcached, custom implementations +- **Works for any backend**: Redis, CacheKit Cloud, File, Memcached, Google Cloud Storage, S3, custom implementations ### RedisBackend diff --git a/docs/getting-started.md b/docs/getting-started.md index a07f2a67..23b0879b 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -23,7 +23,7 @@ ## Quick Start CacheKit provides a unified caching API with pluggable backends. You write `@cache` -once; the backend (Redis, CacheKit Cloud, Memcached, Google Cloud Storage, or File / L1-only) is selected from +once; the backend (Redis, CacheKit Cloud, Memcached, Google Cloud Storage, S3, or File / L1-only) is selected from your environment. See [Choose Your Backend](#choose-your-backend) for the full menu. With nothing configured, `@cache` caches in L1 only, in process, like `lru_cache`. It @@ -252,7 +252,7 @@ export CACHEKIT_CONNECTION_POOL_SIZE=50 ## Choose Your Backend -Five paths depending on your situation: +Six paths depending on your situation: | Backend | When to use | Setup effort | |:--------|:------------|:-------------| @@ -260,6 +260,7 @@ Five paths depending on your situation: | **CacheKit Cloud** (closed beta) | Skip Redis ops, managed edge caching | Low — API key only | | **Memcached** (optional) | High-throughput, existing Memcached infra | Low — `pip install cachekit[memcached]` | | **Google Cloud Storage** (optional) | Cloud Run and jobs: durable results, no server | Low — `pip install cachekit[gcs]` and a bucket | +| **S3** (optional) | Lambda, ECS tasks and batch jobs: durable results, no server; or an S3-compatible store | Low — `pip install cachekit[s3]` and a bucket | | **File / L1-only** | Local dev, tests, no external deps | None | ### Redis (Recommended) @@ -345,6 +346,28 @@ def get_user(user_id: int): See [Google Cloud Storage Backend](backends/gcs.md) for IAM and the bucket lifecycle rule. +### S3 (Optional) + +One object per cache entry in a bucket you own, in Amazon S3 or an S3-compatible store (`endpoint_url`). Durable and shared, with no server to run; each L1 miss is a request to S3. + +```bash +pip install cachekit[s3] +# Auth: boto3's default credential chain (the workload's role on AWS, or AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY or AWS_PROFILE elsewhere) +``` + +```python notest +from cachekit import cache +from cachekit.backends.s3 import S3Backend, S3BackendConfig + +backend = S3Backend(S3BackendConfig(bucket="my-cache-bucket")) + +@cache(backend=backend, ttl=3600) +def get_user(user_id: int): + return fetch_from_db(user_id) +``` + +See [S3 Backend](backends/s3.md) for IAM and the bucket lifecycle rule. Expired entries stay in the bucket until that rule removes them. + ### File / L1-Only (Dev and Testing) No external dependencies. Pure in-process memory cache. Not suitable for multi-pod or production. diff --git a/llms.txt b/llms.txt index b4e776b7..a1c1e281 100644 --- a/llms.txt +++ b/llms.txt @@ -1,8 +1,8 @@ # cachekit -> Caching for Python, TypeScript and Rust, with opt-in zero-knowledge encryption, circuit breakers and stampede protection. This is the Python SDK: intent-based decorators with distributed locking, Prometheus metrics and AES-256-GCM encryption on a Rust-powered core. Zero-config L1 in-memory; scales to Redis, Memcached, File, Google Cloud Storage, or CacheKit Cloud. +> Caching for Python, TypeScript and Rust, with opt-in zero-knowledge encryption, circuit breakers and stampede protection. This is the Python SDK: intent-based decorators with distributed locking, Prometheus metrics and AES-256-GCM encryption on a Rust-powered core. Zero-config L1 in-memory; scales to Redis, Memcached, File, Google Cloud Storage, S3, or CacheKit Cloud. -cachekit provides decorator-based caching with circuit breaker, distributed locking, Prometheus metrics, L1+L2 dual-layer caching, and optional zero-knowledge encryption. Supports 5 built-in backends (Redis, Memcached, File, Google Cloud Storage, CacheKit Cloud) plus custom backends via the BaseBackend protocol. +cachekit provides decorator-based caching with circuit breaker, distributed locking, Prometheus metrics, L1+L2 dual-layer caching, and optional zero-knowledge encryption. Supports 6 built-in backends (Redis, Memcached, File, Google Cloud Storage, S3, CacheKit Cloud) plus custom backends via the BaseBackend protocol. ## Quick Start @@ -30,7 +30,7 @@ def get_patient(id: int): ## Backends -5 built-in backends, all implementing the BaseBackend protocol (get/set/delete/exists/health_check): +6 built-in backends, all implementing the BaseBackend protocol (get/set/delete/exists/health_check): | Backend | Install | Use Case | |---------|---------|----------| @@ -38,6 +38,7 @@ def get_patient(id: int): | **Memcached** | `pip install cachekit[memcached]` | High-throughput, existing infra | | **File** | included | Single-machine, zero-dependency | | **Google Cloud Storage** | `pip install cachekit[gcs]` | Durable shared cache with no server (Cloud Run, jobs) | +| **S3** | `pip install cachekit[s3]` | Durable shared cache with no server (Lambda, ECS tasks, batch jobs), or an S3-compatible store | | **CacheKit Cloud** (`CachekitIOBackend`) | included | Managed, zero infrastructure (closed beta) | ### Redis @@ -88,6 +89,20 @@ def cached_fn(): return data ``` +### S3 +```python +from cachekit.backends.s3 import S3Backend, S3BackendConfig + +# Environment: CACHEKIT_S3_BUCKET=my-cache-bucket (auth: boto3's default credential chain) +# An S3-compatible store: add endpoint_url="https://s3.example.com" (CACHEKIT_S3_ENDPOINT_URL) +config = S3BackendConfig(bucket="my-cache-bucket", prefix="cachekit/") +backend = S3Backend(config) + +@cache(backend=backend, ttl=3600) +def cached_fn(): + return data +``` + ### CacheKit Cloud (managed, closed beta) ```python # Environment: CACHEKIT_API_KEY=your-api-key @@ -157,6 +172,10 @@ CACHEKIT_FILE_MAX_SIZE_MB=500 CACHEKIT_GCS_BUCKET=my-cache-bucket CACHEKIT_GCS_PREFIX=cachekit/ +# S3 (auth: boto3's default credential chain) +CACHEKIT_S3_BUCKET=my-cache-bucket +CACHEKIT_S3_PREFIX=cachekit/ + # CacheKit Cloud CACHEKIT_API_KEY=your-api-key CACHEKIT_API_URL=https://api.cachekit.io @@ -183,6 +202,7 @@ CACHEKIT_MASTER_KEY=hex-encoded-32-byte-key - [File](docs/backends/file.md): Local filesystem caching - [Memcached](docs/backends/memcached.md): High-throughput caching - [Google Cloud Storage](docs/backends/gcs.md): One object per entry, file-backend format, IAM and lifecycle rule +- [S3](docs/backends/s3.md): One object per entry, file-backend format, IAM and lifecycle rule; Amazon S3 and S3-compatible stores - [CacheKit Cloud](docs/backends/cachekitio.md): Managed backend (closed beta) - [Custom Backends](docs/backends/custom.md): Implement BaseBackend diff --git a/pyproject.toml b/pyproject.toml index 2efe2579..18849950 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -97,6 +97,9 @@ memcached = [ gcs = [ "google-cloud-storage>=3.0.0", ] +s3 = [ + "boto3>=1.36.0", +] [project.urls] Homepage = "https://github.com/cachekit-io/cachekit-py" @@ -242,6 +245,7 @@ test = [ "pytest-xdist>=3.8.0", "time-machine>=2.19.0", "h11>=0.16.0", + "boto3>=1.36.0", ] dev = [ { include-group = "test" }, diff --git a/src/cachekit/backends/__init__.py b/src/cachekit/backends/__init__.py index 7e567ac1..9e8a52cf 100644 --- a/src/cachekit/backends/__init__.py +++ b/src/cachekit/backends/__init__.py @@ -17,6 +17,7 @@ - RedisBackend: Redis implementation - MemcachedBackend: Memcached implementation (requires pymemcache) - GCSBackend: Google Cloud Storage implementation (requires google-cloud-storage) + - S3Backend: S3 implementation, for AWS S3 and S3-compatible stores (requires boto3) Usage: >>> from cachekit.backends import BaseBackend, RedisBackend, BackendError @@ -51,6 +52,7 @@ from cachekit.backends.gcs import GCSBackend from cachekit.backends.memcached import MemcachedBackend from cachekit.backends.redis import RedisBackend + from cachekit.backends.s3 import S3Backend __all__ = [ "BaseBackend", @@ -67,6 +69,7 @@ "RedisBackend", "MemcachedBackend", "GCSBackend", + "S3Backend", ] @@ -112,7 +115,7 @@ def get_backend(self) -> BaseBackend: def __getattr__(name: str): - """Lazy imports: pymemcache or google-cloud-storage may not be installed, and redis-py loads only for a program that uses Redis. + """Lazy imports: pymemcache, google-cloud-storage or boto3 may not be installed, and redis-py loads only for a program that uses Redis. Loading redis-py loads hiredis, which re-enables the GIL on a free-threaded build, so ``import cachekit`` must not load it (see cachekit.hiredis_compat). @@ -129,4 +132,8 @@ def __getattr__(name: str): from cachekit.backends.gcs import GCSBackend return GCSBackend + if name == "S3Backend": + from cachekit.backends.s3 import S3Backend + + return S3Backend raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/src/cachekit/backends/provider.py b/src/cachekit/backends/provider.py index 05a85db1..c30beb32 100644 --- a/src/cachekit/backends/provider.py +++ b/src/cachekit/backends/provider.py @@ -168,7 +168,7 @@ async def get_async_client(self) -> redis_async.Redis: class _BackendEnv(BaseSettings): """The backend env vars as pydantic-settings reads them, for DefaultBackendProvider._is_configured(): - its five _SELECTORS plus REDIS_URL.""" + its six _SELECTORS plus REDIS_URL.""" model_config = SettingsConfigDict(case_sensitive=False, extra="ignore", hide_input_in_errors=True) @@ -178,6 +178,7 @@ class _BackendEnv(BaseSettings): cachekit_memcached_servers: Optional[SecretStr] = None cachekit_file_cache_dir: Optional[SecretStr] = None cachekit_gcs_bucket: Optional[SecretStr] = None + cachekit_s3_bucket: Optional[SecretStr] = None redis_url: Optional[SecretStr] = None @@ -191,6 +192,7 @@ class DefaultBackendProvider(BackendProviderInterface): - CACHEKIT_MEMCACHED_SERVERS → MemcachedBackend - CACHEKIT_FILE_CACHE_DIR → FileBackend - CACHEKIT_GCS_BUCKET → GCSBackend + - CACHEKIT_S3_BUCKET → S3Backend With none of them set, ``REDIS_URL`` → Redis, as above (12-factor). With nothing set at all, ``_is_configured()`` is False and a plaintext decorator @@ -198,7 +200,7 @@ class DefaultBackendProvider(BackendProviderInterface): Only the decorators that cannot run L1-only (encryption, ``interop=``) still call it then, and get Redis at ``RedisBackendConfig``'s localhost default. - Setting more than one of the five prefixed selectors raises + Setting more than one of the six prefixed selectors raises ``ConfigurationError`` — auto-detection must be unambiguous; pass ``backend=`` explicitly to override. The non-prefixed ``REDIS_URL`` is only a fallback and never counts as a conflict (12-factor convention). @@ -219,6 +221,7 @@ class DefaultBackendProvider(BackendProviderInterface): ("CACHEKIT_MEMCACHED_SERVERS", "memcached"), ("CACHEKIT_FILE_CACHE_DIR", "file"), ("CACHEKIT_GCS_BUCKET", "gcs"), + ("CACHEKIT_S3_BUCKET", "s3"), ) def __init__(self): @@ -227,6 +230,7 @@ def __init__(self): self._memcached_backend = None self._file_backend = None self._gcs_backend = None + self._s3_backend = None def _matched(self) -> list[tuple[str, str]]: """The prefixed selectors set to a non-empty value, matched by exact name.""" @@ -247,8 +251,8 @@ def _detect(self): raise ConfigurationError( f"Ambiguous backend auto-detection: multiple selectors set ({names}). " "Set exactly one of CACHEKIT_API_KEY / CACHEKIT_REDIS_URL / " - "CACHEKIT_MEMCACHED_SERVERS / CACHEKIT_FILE_CACHE_DIR / CACHEKIT_GCS_BUCKET, " - "or pass backend= explicitly." + "CACHEKIT_MEMCACHED_SERVERS / CACHEKIT_FILE_CACHE_DIR / CACHEKIT_GCS_BUCKET / " + "CACHEKIT_S3_BUCKET, or pass backend= explicitly." ) return matched[0][1] if matched else None @@ -301,6 +305,13 @@ def get_backend(self): self._gcs_backend = GCSBackend(GCSBackendConfig.from_env()) return self._gcs_backend + if choice == "s3": + if self._s3_backend is None: + from cachekit.backends.s3 import S3Backend, S3BackendConfig + + self._s3_backend = S3Backend(S3BackendConfig.from_env()) + return self._s3_backend + # choice == "redis" (explicit CACHEKIT_REDIS_URL) or None: REDIS_URL, else RedisBackendConfig's default. # Shared backend: it resolves the tenant per operation, so caching it cannot pin a tenant. if self._redis_backend is None: diff --git a/src/cachekit/backends/s3/__init__.py b/src/cachekit/backends/s3/__init__.py new file mode 100644 index 00000000..ef8caf7d --- /dev/null +++ b/src/cachekit/backends/s3/__init__.py @@ -0,0 +1,26 @@ +"""S3 backend for cachekit. + +Stores each cache entry as one S3 object, in the bytes and under the name the file backend uses, +on AWS S3 or any store that serves the S3 API at an ``endpoint_url``. Authenticates through +boto3's default credential chain. Requires the ``s3`` extra: ``pip install 'cachekit[s3]'``. + +Public API: + - S3Backend: Main backend implementation + - S3BackendConfig: Configuration class + +Example: + >>> from cachekit.backends.s3 import S3Backend, S3BackendConfig + >>> config = S3BackendConfig(bucket="my-cache-bucket", prefix="cachekit/") + >>> backend = S3Backend(config) # doctest: +SKIP + >>> backend.set("key", b"value", ttl=60) # doctest: +SKIP +""" + +from __future__ import annotations + +from cachekit.backends.s3.backend import S3Backend +from cachekit.backends.s3.config import S3BackendConfig + +__all__ = [ + "S3Backend", + "S3BackendConfig", +] diff --git a/src/cachekit/backends/s3/backend.py b/src/cachekit/backends/s3/backend.py new file mode 100644 index 00000000..17024459 --- /dev/null +++ b/src/cachekit/backends/s3/backend.py @@ -0,0 +1,227 @@ +"""S3 backend implementation for cachekit. + +One S3 object per cache entry, in the file backend's entry format: a 14-byte header that carries +the expiry, then the payload, named by the BLAKE2b-128 hex of the cache key. Implements +BaseBackend protocol. +""" + +from __future__ import annotations + +import hashlib +import struct +import time +from typing import Any + +# The entry format has one definition, the file backend's: an object this backend writes is the +# file that backend would write, so the header is built and judged by the same code. +from cachekit.backends.file.backend import FORMAT_VERSION, HEADER_SIZE, MAGIC, FileBackend, _has_unknown_transform +from cachekit.backends.s3.config import S3BackendConfig +from cachekit.backends.s3.error_handler import classify_s3_error, error_response + +_CONTENT_TYPE = "application/octet-stream" +_HEADER_RANGE = f"bytes=0-{HEADER_SIZE - 1}" + + +def _build_client(config: S3BackendConfig) -> Any: + """An S3 client on boto3's default credential chain, which sends each request once. + + The retry settings are explicit, so ``AWS_MAX_ATTEMPTS`` and ``AWS_RETRY_MODE`` do not reach + this client. The session is the client's own: boto3's shared default session is not safe to + build clients from on several threads at once. + + Raises: + ImportError: If boto3 is not installed. + """ + try: + import boto3.session + from botocore.config import Config + except ImportError as exc: + raise ImportError("S3Backend requires boto3. Install it with: pip install 'cachekit[s3]'") from exc + return boto3.session.Session().client( + "s3", + endpoint_url=config.endpoint_url, + region_name=config.region, + config=Config( + retries={"total_max_attempts": 1, "mode": "standard"}, + connect_timeout=config.timeout, + read_timeout=config.timeout, + ), + ) + + +def _is_absent(exc: Exception, header_only: bool) -> bool: + """Whether a failed read means there is no entry: no such object, or no header in an empty one. + + A 404 for the bucket itself is not a miss. S3 names which of the two is absent, so a wrong + bucket name raises instead of reading as an empty cache. + """ + status, code = error_response(exc) + if status == 404: + return code != "NoSuchBucket" + # An empty object has no byte range to serve, so a ranged read of it is refused. + return header_only and status == 416 + + +class S3Backend: + """S3 backend implementing BaseBackend protocol, for AWS S3 and S3-compatible stores. + + Each entry is one object named ````, holding the bytes the + file backend would write for the same key, value and expiry. Expiry is checked on read: an + expired entry is a miss. No read deletes anything, so expired entries stay until a bucket + lifecycle rule removes them (see docs/backends/s3.md). + + Authentication is boto3's default credential chain only. The backend retries no request: a + failed one raises a ``BackendError`` and the next call tries again. + + Examples: + Create a backend (requires credentials and a bucket): + + >>> from cachekit.backends.s3 import S3Backend, S3BackendConfig + >>> backend = S3Backend(S3BackendConfig(bucket="my-cache-bucket")) # doctest: +SKIP + >>> backend.set("key", b"value", ttl=60) # doctest: +SKIP + >>> backend.get("key") # doctest: +SKIP + b'value' + >>> backend.delete("key") # doctest: +SKIP + True + """ + + def __init__(self, config: S3BackendConfig | None = None) -> None: + """Initialize S3Backend. Builds the client and sends no request to S3. + + A missing credential does not fail here: it raises on the first operation. + + Args: + config: Optional configuration. Defaults to loading from environment. + + Raises: + ImportError: If boto3 is not installed. + BackendError: If boto3 cannot build a client from the configuration. + """ + self._config = config or S3BackendConfig.from_env() + try: + self._client = _build_client(self._config) + except ImportError: + raise + except Exception as exc: + raise classify_s3_error(exc, operation="init") from exc + self._bucket = self._config.bucket + self._prefix = self._config.prefix + + def _object_key(self, key: str) -> str: + """The key's object: the prefix, then the file backend's name for the key.""" + return self._prefix + hashlib.blake2b(key.encode("utf-8"), digest_size=16).hexdigest() + + def _read(self, operation: str, key: str, header_only: bool) -> bytes | None: + """Download the key's entry in one request, or its header alone; None for a miss. + + An expired or corrupt entry is a miss and stays where it is. Removing it safely needs a + delete that is conditional on the object the read saw, and not every S3-compatible store + honours one: an unconditional delete could remove an entry a writer stored in between. + + Raises: + BackendError: If the request fails for any reason but the object being absent. + """ + request: dict[str, str] = {"Bucket": self._bucket, "Key": self._object_key(key)} + if header_only: + request["Range"] = _HEADER_RANGE + try: + data: bytes = self._client.get_object(**request)["Body"].read() + except Exception as exc: + if _is_absent(exc, header_only): + return None + raise classify_s3_error(exc, operation=operation, key=key) from exc + + header = data[:HEADER_SIZE] + if len(header) < HEADER_SIZE or header[0:2] != MAGIC or header[2] != FORMAT_VERSION: + return None # corrupt + if _has_unknown_transform(header): + return None # a transform this reader does not implement + expiry_timestamp = struct.unpack(">Q", header[6:14])[0] + if expiry_timestamp > 0 and time.time() >= expiry_timestamp: + return None + return data + + def get(self, key: str) -> bytes | None: + """Retrieve value from S3, in one GetObject request. + + Args: + key: Cache key to retrieve. + + Returns: + Bytes value if found and not expired, None otherwise. + + Raises: + BackendError: If the request fails. + """ + data = self._read("get", key, header_only=False) + return None if data is None else data[HEADER_SIZE:] + + def set(self, key: str, value: bytes, ttl: int | None = None) -> None: + """Store value in S3, replacing the key's object in one PutObject request. + + Args: + key: Cache key to store. + value: Bytes value to store. + ttl: Time-to-live in seconds. None or 0 means no expiry. + + Raises: + BackendError: If the TTL is out of range or the upload fails. + """ + body = FileBackend._build_header(FileBackend._expiry_from_ttl(ttl)) + value + try: + self._client.put_object(Bucket=self._bucket, Key=self._object_key(key), Body=body, ContentType=_CONTENT_TYPE) + except Exception as exc: + raise classify_s3_error(exc, operation="set", key=key) from exc + + def delete(self, key: str) -> bool: + """Delete key from S3. + + Args: + key: Cache key to delete. + + Returns: + True whenever the key is gone afterwards, whether or not it existed: S3's + DeleteObject answers the same for both. A store that answers 404 for an absent + object gets the same True. + + Raises: + BackendError: If the request fails. + """ + try: + self._client.delete_object(Bucket=self._bucket, Key=self._object_key(key)) + except Exception as exc: + if not _is_absent(exc, header_only=False): + raise classify_s3_error(exc, operation="delete", key=key) from exc + return True + + def exists(self, key: str) -> bool: + """Check if key exists and is not expired, reading only the entry's 14-byte header. + + Args: + key: Cache key to check. + + Returns: + True if key exists and is not expired, False otherwise. + + Raises: + BackendError: If the request fails. + """ + return self._read("exists", key, header_only=True) is not None + + def health_check(self) -> tuple[bool, dict[str, Any]]: + """Check that the bucket answers, by listing at most one object under the prefix. + + A listing needs ``s3:ListBucket``, the permission without which S3 answers a read of an + absent object with 403 instead of 404. It also fails for a bucket that does not exist. + + Returns: + Tuple of (is_healthy, details_dict) with latency_ms and backend_type. + """ + details: dict[str, Any] = {"backend_type": "s3", "bucket": self._bucket} + start = time.perf_counter() + try: + self._client.list_objects_v2(Bucket=self._bucket, Prefix=self._prefix, MaxKeys=1) + except Exception as exc: + details["error"] = str(classify_s3_error(exc, operation="health_check")) + details["latency_ms"] = round((time.perf_counter() - start) * 1000, 2) + return "error" not in details, details diff --git a/src/cachekit/backends/s3/config.py b/src/cachekit/backends/s3/config.py new file mode 100644 index 00000000..a18d67ab --- /dev/null +++ b/src/cachekit/backends/s3/config.py @@ -0,0 +1,116 @@ +"""S3 backend configuration. + +Holds no credential fields: the backend authenticates through boto3's default credential chain. +""" + +from __future__ import annotations + +from pydantic import Field, field_validator +from pydantic_settings import SettingsConfigDict + +from cachekit.backends.base_config import BaseBackendConfig, inherit_config + +# S3 caps an object key at 1024 bytes of UTF-8; an entry's key is the prefix plus 32 hex characters. +MAX_PREFIX_BYTES: int = 1024 - 32 + + +class S3BackendConfig(BaseBackendConfig): + """S3 backend configuration. + + Attributes: + bucket: Name of the bucket that holds the entries. Required. + prefix: Object-key prefix, used verbatim (``"cache/"`` gives ``cache/``). A storage + location only: it does not change the cache key. + endpoint_url: Endpoint of an S3-compatible store. Optional: without it the client + addresses AWS S3. + region: Region of the bucket. Optional: without it boto3 looks for one in + ``AWS_DEFAULT_REGION`` and the shared config file. + timeout: Seconds to wait for the server to connect, and between bytes of a response. + + Examples: + Create with a bucket: + + >>> config = S3BackendConfig(bucket="my-cache-bucket") + >>> config.prefix + '' + >>> config.timeout + 10.0 + + Address an S3-compatible store: + + >>> S3BackendConfig(bucket="my-cache-bucket", endpoint_url="https://s3.example.com").endpoint_url + 'https://s3.example.com' + """ + + model_config = SettingsConfigDict( + **inherit_config(BaseBackendConfig), + env_prefix="CACHEKIT_S3_", + ) + + bucket: str = Field( + ..., # Required field + min_length=1, + description="Bucket that holds the cache entries (a name, not an s3:// URL)", + ) + prefix: str = Field( + default="", + description="Object-key prefix, used verbatim; a storage location only", + ) + endpoint_url: str | None = Field( + default=None, + description="Endpoint of an S3-compatible store; AWS S3 when unset", + ) + region: str | None = Field( + default=None, + description="Region of the bucket; boto3's own lookup when unset", + ) + timeout: float = Field( + default=10.0, + ge=0.1, + le=600.0, + description="Seconds to wait for a connection, and between bytes of a response", + ) + + @field_validator("bucket", mode="after") + @classmethod + def validate_bucket(cls, v: str) -> str: + """Reject a URL or a path: the client would address a bucket of that literal name.""" + if "/" in v: + raise ValueError("bucket must be a bucket name, without s3:// or a path; put a path in prefix") + return v + + @field_validator("prefix", mode="after") + @classmethod + def validate_prefix(cls, v: str) -> str: + """Reject a line break, and a prefix that leaves no room for the name within S3's key limit.""" + if "\r" in v or "\n" in v: + raise ValueError("prefix must not contain a carriage return or line feed") + if len(v.encode("utf-8")) > MAX_PREFIX_BYTES: + raise ValueError(f"prefix must be at most {MAX_PREFIX_BYTES} bytes of UTF-8") + return v + + @field_validator("endpoint_url", "region", mode="before") + @classmethod + def empty_is_unset(cls, v: object) -> object: + """An empty value, as an environment variable set to nothing gives, means unset.""" + return None if isinstance(v, str) and not v.strip() else v + + @field_validator("endpoint_url", mode="after") + @classmethod + def validate_endpoint_url(cls, v: str | None) -> str | None: + """Reject an endpoint without a scheme: boto3 would refuse it only when the backend is built.""" + if v is not None and not v.startswith(("https://", "http://")): + raise ValueError("endpoint_url must start with https:// or http://") + return v + + @classmethod + def from_env(cls) -> S3BackendConfig: + """Create configuration from environment variables. + + Reads CACHEKIT_S3_BUCKET, CACHEKIT_S3_PREFIX, CACHEKIT_S3_ENDPOINT_URL, CACHEKIT_S3_REGION + and CACHEKIT_S3_TIMEOUT. + + Returns: + S3BackendConfig instance loaded from environment. + """ + return cls() # type: ignore[call-arg] diff --git a/src/cachekit/backends/s3/error_handler.py b/src/cachekit/backends/s3/error_handler.py new file mode 100644 index 00000000..436ef1f3 --- /dev/null +++ b/src/cachekit/backends/s3/error_handler.py @@ -0,0 +1,130 @@ +"""S3 exception classification for backend abstraction. + +Maps botocore and transport exceptions to BackendErrorType for the circuit breaker. +""" + +from __future__ import annotations + +import re +from typing import Any + +from cachekit.backends.errors import BackendError, BackendErrorType + +# S3 answers these with HTTP 400, so the status alone would read as a caller's mistake. +_CREDENTIAL_CODES = frozenset({"ExpiredToken", "InvalidToken", "TokenRefreshRequired"}) + +# The shape of an S3 error code. Anything else in the field is the server's free text. +_ERROR_CODE = re.compile(r"[A-Za-z0-9.]{1,64}") + + +def error_response(exc: Exception) -> tuple[int | None, str | None]: + """The HTTP status and S3 error code of a botocore ClientError; (None, None) for anything else.""" + response: Any = getattr(exc, "response", None) + if not isinstance(response, dict): + return None, None + status = response.get("ResponseMetadata", {}).get("HTTPStatusCode") + code = response.get("Error", {}).get("Code") + return (status if isinstance(status, int) else None), (code if isinstance(code, str) else None) + + +def _classify(exc: Exception) -> tuple[BackendErrorType, str]: + """The error type for exc, and the word that names it in the message.""" + from botocore.exceptions import ( + BotoCoreError, + ClientError, + ConnectTimeoutError, + CredentialRetrievalError, + FlexibleChecksumError, + HTTPClientError, + IncompleteReadError, + MetadataRetrievalError, + NoCredentialsError, + PartialCredentialsError, + ReadTimeoutError, + SSOError, + ) + from botocore.exceptions import ConnectionError as BotoConnectionError + + # Before the connection branches: botocore's ConnectTimeoutError is also its ConnectionError, + # and its ReadTimeoutError an HTTPClientError. + if isinstance(exc, (ConnectTimeoutError, ReadTimeoutError, TimeoutError)): + return BackendErrorType.TIMEOUT, "timeout" + if isinstance(exc, ClientError): + status, code = error_response(exc) + if status in (401, 403) or code in _CREDENTIAL_CODES: + return BackendErrorType.AUTHENTICATION, "authentication error" + if status == 408 or code == "RequestTimeout": # S3 sends RequestTimeout as a 400 + return BackendErrorType.TIMEOUT, "timeout" + if status == 429 or (status is not None and status >= 500): + return BackendErrorType.TRANSIENT, "transient error" + return BackendErrorType.PERMANENT, "permanent error" + if isinstance(exc, (NoCredentialsError, PartialCredentialsError, SSOError)): + return BackendErrorType.AUTHENTICATION, "authentication error" + # A credential provider that did not answer (a container or instance metadata endpoint, a + # credential process) is not a refused credential. IncompleteReadError: the response body + # ended early. FlexibleChecksumError: the bytes received do not match the checksum sent with them. + if isinstance( + exc, + ( + HTTPClientError, + BotoConnectionError, + IncompleteReadError, + FlexibleChecksumError, + CredentialRetrievalError, + MetadataRetrievalError, + OSError, + ), + ): + return BackendErrorType.TRANSIENT, "transient error" + if isinstance(exc, BotoCoreError): + # What is left is the request never being sendable: a parameter botocore refuses, a + # configuration it cannot use. The next call fails the same way. + return BackendErrorType.PERMANENT, "permanent error" + return BackendErrorType.UNKNOWN, "unknown error" + + +def classify_s3_error( + exc: Exception, + operation: str | None = None, + key: str | None = None, +) -> BackendError: + """Classify an S3 exception into BackendError with error_type. + + Args: + exc: Original exception from boto3, botocore or the HTTP transport. + operation: Operation that failed (get, set, delete, exists, health_check). + key: Cache key involved (optional, for debugging). + + Returns: + BackendError with appropriate error_type classification. + + Examples: + A 403 is an authentication error: + + >>> from botocore.exceptions import ClientError + >>> def failure(code: str, status: int) -> ClientError: + ... return ClientError({"Error": {"Code": code}, "ResponseMetadata": {"HTTPStatusCode": status}}, "GetObject") + >>> classify_s3_error(failure("AccessDenied", 403), operation="get").error_type.value + 'authentication' + + A 503 is transient, and a transport timeout gets its own category: + + >>> classify_s3_error(failure("SlowDown", 503), operation="set").error_type.value + 'transient' + >>> classify_s3_error(TimeoutError(), operation="get").error_type.value + 'timeout' + """ + error_type, label = _classify(exc) + # Only the error code and the HTTP status, or the exception TYPE, go in the message: S3's error + # text names the bucket, the object and the caller's identity, and the message reaches log + # sinks via str(e) (CWE-532). Full details stay on original_exception. + status, code = error_response(exc) + name = code if code is not None and _ERROR_CODE.fullmatch(code) else type(exc).__name__ + detail = f"{name} (HTTP {status})" if status is not None else name + return BackendError( + message=f"S3 {label} during {operation}: {detail}", + error_type=error_type, + original_exception=exc, + operation=operation, + key=key, + ) diff --git a/src/cachekit/decorators/wrapper.py b/src/cachekit/decorators/wrapper.py index d55dc812..7610b80f 100644 --- a/src/cachekit/decorators/wrapper.py +++ b/src/cachekit/decorators/wrapper.py @@ -946,7 +946,8 @@ def create_cache_wrapper( "objects, which cannot be ciphertext. Drop backend=None (the backend then " "resolves from set_default_backend(), else the one CACHEKIT_* selector set: " "CACHEKIT_API_KEY, CACHEKIT_REDIS_URL, CACHEKIT_MEMCACHED_SERVERS, " - "CACHEKIT_FILE_CACHE_DIR or CACHEKIT_GCS_BUCKET, else REDIS_URL / localhost Redis; see " + "CACHEKIT_FILE_CACHE_DIR, CACHEKIT_GCS_BUCKET or CACHEKIT_S3_BUCKET, else REDIS_URL / " + "localhost Redis; see " "docs/backends/README.md) or pass one explicitly to keep @cache.secure / " "encryption=True." ) diff --git a/tests/architecture/test_backend_config_consistency.py b/tests/architecture/test_backend_config_consistency.py index ef43df48..aa26287a 100644 --- a/tests/architecture/test_backend_config_consistency.py +++ b/tests/architecture/test_backend_config_consistency.py @@ -21,6 +21,7 @@ from cachekit.backends.gcs.config import GCSBackendConfig from cachekit.backends.memcached.config import MemcachedBackendConfig from cachekit.backends.redis.config import RedisBackendConfig +from cachekit.backends.s3.config import S3BackendConfig # All backend config classes that must follow the pattern BACKEND_CONFIGS: list[type[BaseBackendConfig]] = [ @@ -29,10 +30,14 @@ CachekitIOBackendConfig, MemcachedBackendConfig, GCSBackendConfig, + S3BackendConfig, ] # Constructor arguments for a config that has a required field and is still instantiated below. -REQUIRED_KWARGS: dict[type[BaseBackendConfig], dict[str, str]] = {GCSBackendConfig: {"bucket": "cache-bucket"}} +REQUIRED_KWARGS: dict[type[BaseBackendConfig], dict[str, str]] = { + GCSBackendConfig: {"bucket": "cache-bucket"}, + S3BackendConfig: {"bucket": "cache-bucket"}, +} # Required model_config settings from BaseBackendConfig REQUIRED_MODEL_CONFIG_KEYS = { diff --git a/tests/fixtures/zero_config.py b/tests/fixtures/zero_config.py index 0965733d..4a4e6523 100644 --- a/tests/fixtures/zero_config.py +++ b/tests/fixtures/zero_config.py @@ -15,6 +15,7 @@ "CACHEKIT_MEMCACHED_SERVERS", "CACHEKIT_FILE_CACHE_DIR", "CACHEKIT_GCS_BUCKET", + "CACHEKIT_S3_BUCKET", ) BACKEND_ENV = (*SELECTORS, "REDIS_URL") diff --git a/tests/integration/test_s3_integration.py b/tests/integration/test_s3_integration.py new file mode 100644 index 00000000..270a66c8 --- /dev/null +++ b/tests/integration/test_s3_integration.py @@ -0,0 +1,303 @@ +"""Integration tests for S3Backend against an S3 emulator. + +Requires a running moto server. Start one with: + bash .github/scripts/start-moto-s3.sh + +Set S3_EMULATOR_ENDPOINT to override the default http://127.0.0.1:5000. The tests only ever talk +to that endpoint, never to AWS, and sign with made-up credentials. They are skipped when it is +unreachable. CI push runs start the emulator and fail the job if any test here skips. +""" + +from __future__ import annotations + +import os +import threading +import time +import urllib.error +import urllib.request +import uuid +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pytest + +from cachekit.backends.errors import BackendError, BackendErrorType +from cachekit.backends.file import FileBackend, FileBackendConfig + +EMULATOR_ENDPOINT = os.environ.get("S3_EMULATOR_ENDPOINT", "http://127.0.0.1:5000") + + +def _emulator_reachable() -> bool: + """Whether something answers HTTP at the endpoint, and boto3 is installed.""" + try: + import boto3 # noqa: F401 + except ImportError: + return False + if not EMULATOR_ENDPOINT.startswith(("http://", "https://")): + return False + try: + # The scheme is checked above, and the host is this test run's own emulator. + with urllib.request.urlopen(EMULATOR_ENDPOINT, timeout=2): # noqa: S310 + return True + except urllib.error.HTTPError: + return True # an S3 endpoint that refuses an unsigned request is still an endpoint + except (urllib.error.URLError, OSError): + return False + + +pytestmark = [ + pytest.mark.integration, + pytest.mark.skipif(not _emulator_reachable(), reason="S3 emulator not reachable, or the s3 extra is not installed"), +] + + +# Override autouse Redis fixture — S3 tests don't need Redis +@pytest.fixture(autouse=True) +def setup_di_for_redis_isolation(): + """Override global Redis fixture — S3Backend doesn't need Redis.""" + pass + + +@pytest.fixture(autouse=True) +def _emulator_env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """Every client built in a test signs with made-up credentials and reads no ambient AWS configuration.""" + for name in ("AWS_PROFILE", "AWS_SESSION_TOKEN", "AWS_ENDPOINT_URL", "AWS_ENDPOINT_URL_S3"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("AWS_ACCESS_KEY_ID", "test-access-key") + monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "test-secret-key") # pragma: allowlist secret + monkeypatch.setenv("AWS_DEFAULT_REGION", "us-east-1") + monkeypatch.setenv("AWS_EC2_METADATA_DISABLED", "true") + monkeypatch.setenv("AWS_CONFIG_FILE", str(tmp_path / "no-aws-config")) + monkeypatch.setenv("AWS_SHARED_CREDENTIALS_FILE", str(tmp_path / "no-aws-credentials")) + + +@pytest.fixture +def admin(_emulator_env: None) -> Any: + """A plain S3 client, to look at the bucket independently of the backend.""" + import boto3 + + return boto3.session.Session().client("s3", endpoint_url=EMULATOR_ENDPOINT) + + +def _names(admin: Any, bucket: str) -> list[str]: + return sorted(entry["Key"] for entry in admin.list_objects_v2(Bucket=bucket).get("Contents", [])) + + +def _body(admin: Any, bucket: str, name: str) -> bytes: + return admin.get_object(Bucket=bucket, Key=name)["Body"].read() + + +@pytest.fixture +def bucket(admin: Any) -> Iterator[str]: + """A bucket no other test, xdist worker or concurrent run uses.""" + name = f"cachekit-it-{uuid.uuid4().hex[:16]}" + admin.create_bucket(Bucket=name) + yield name + for key in _names(admin, name): + admin.delete_object(Bucket=name, Key=key) + admin.delete_bucket(Bucket=name) + + +def _backend(bucket: str, prefix: str = "") -> Any: + from cachekit.backends.s3 import S3Backend, S3BackendConfig + + return S3Backend(S3BackendConfig(bucket=bucket, prefix=prefix, endpoint_url=EMULATOR_ENDPOINT)) + + +@pytest.fixture +def backend(bucket: str) -> Any: + return _backend(bucket) + + +class TestRoundTrip: + def test_set_get_exists_delete(self, backend: Any) -> None: + assert backend.get("k") is None + assert backend.exists("k") is False + + backend.set("k", b"value", ttl=60) + + assert backend.get("k") == b"value" + assert backend.exists("k") is True + assert backend.delete("k") is True + assert backend.get("k") is None + assert backend.exists("k") is False + + def test_delete_of_an_absent_key_succeeds(self, backend: Any) -> None: + """S3 does not say whether the object existed, so delete reports the request, not the object.""" + assert backend.delete("never-stored") is True + + def test_set_replaces(self, backend: Any, admin: Any, bucket: str) -> None: + backend.set("k", b"one", ttl=60) + backend.set("k", b"two") + + assert backend.get("k") == b"two" + assert len(_names(admin, bucket)) == 1 + + @pytest.mark.parametrize("value", [b"", b"\x00\xff" * 512, os.urandom(9 * 1024 * 1024)], ids=["empty", "binary", "9MiB"]) + def test_values_survive(self, backend: Any, value: bytes) -> None: + """9 MiB is past the size at which boto3's transfer manager goes multipart; this backend sends one PutObject.""" + backend.set("k", value, ttl=60) + assert backend.get("k") == value + + def test_concurrent_threads_share_a_backend(self, backend: Any) -> None: + errors: list[BaseException] = [] + + def work(i: int) -> None: + try: + for j in range(10): + key = f"thread-{i}-{j}" + backend.set(key, key.encode(), ttl=60) + assert backend.get(key) == key.encode() + except BaseException as exc: # noqa: BLE001 (reported below, on the main thread) + errors.append(exc) + + threads = [threading.Thread(target=work, args=(i,)) for i in range(8)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=60) + + assert not any(thread.is_alive() for thread in threads) + assert errors == [] + + +class TestObjectFormat: + @pytest.mark.parametrize("ttl", [None, 3600]) + def test_object_is_the_file_backends_file( + self, backend: Any, admin: Any, bucket: str, tmp_path: Path, ttl: int | None + ) -> None: + """Same key, value and expiry: the stored object and the file backend's file are the same bytes, same name.""" + import time_machine + + key = "ns:app:func:mod.fn:args:" + "ab" * 32 + ":1s" + cache_dir = tmp_path / "file-backend" + with time_machine.travel(time.time(), tick=False): + FileBackend(FileBackendConfig(cache_dir=cache_dir)).set(key, b"payload", ttl=ttl) + backend.set(key, b"payload", ttl=ttl) + + (written,) = [p for p in cache_dir.iterdir() if p.is_file()] + assert _names(admin, bucket) == [written.name] + assert _body(admin, bucket, written.name) == written.read_bytes() + + def test_a_file_backend_entry_uploaded_as_is_is_readable( + self, backend: Any, admin: Any, bucket: str, tmp_path: Path + ) -> None: + cache_dir = tmp_path / "file-backend" + FileBackend(FileBackendConfig(cache_dir=cache_dir)).set("k", b"from a file", ttl=60) + (written,) = [p for p in cache_dir.iterdir() if p.is_file()] + admin.put_object(Bucket=bucket, Key=written.name, Body=written.read_bytes()) + + assert backend.get("k") == b"from a file" + assert backend.exists("k") is True + + def test_prefix_is_part_of_the_object_name_only(self, admin: Any, bucket: str) -> None: + plain = _backend(bucket) + prefixed = _backend(bucket, prefix="cachekit/") + plain.set("k", b"plain") + prefixed.set("k", b"prefixed") + + plain_name, prefixed_name = _names(admin, bucket) + assert prefixed_name == f"cachekit/{plain_name}" + assert (plain.get("k"), prefixed.get("k")) == (b"plain", b"prefixed") + + +# What a miss is, exactly: no other falsy value will do. +_MISS: dict[str, Any] = {"get": None, "exists": False} + + +class TestExpiry: + @pytest.mark.parametrize("read", ["get", "exists"]) + def test_expired_entry_is_a_miss_and_stays_in_the_bucket(self, backend: Any, admin: Any, bucket: str, read: str) -> None: + # The expiry is a whole second, rounded down: a 1-second TTL lasts at most 1 second. + backend.set("k", b"v", ttl=1) + (name,) = _names(admin, bucket) + stored = _body(admin, bucket, name) + + time.sleep(1.1) + + assert getattr(backend, read)("k") is _MISS[read] + assert _body(admin, bucket, name) == stored # no read deletes: the lifecycle rule does + + @pytest.mark.parametrize("body", [b"", b"CK", b"not a cachekit entry at all"], ids=["empty", "truncated", "bad-magic"]) + @pytest.mark.parametrize("read", ["get", "exists"]) + def test_corrupt_object_is_a_miss_and_stays_in_the_bucket( + self, backend: Any, admin: Any, bucket: str, body: bytes, read: str + ) -> None: + backend.set("k", b"v") + (name,) = _names(admin, bucket) + admin.put_object(Bucket=bucket, Key=name, Body=body) + + assert getattr(backend, read)("k") is _MISS[read] + assert _body(admin, bucket, name) == body + + @pytest.mark.parametrize("read", ["get", "exists"]) + def test_unknown_flag_is_a_miss_left_untouched(self, backend: Any, admin: Any, bucket: str, read: str) -> None: + backend.set("k", b"v") + (name,) = _names(admin, bucket) + flagged = b"CK\x01\x00\x00\x01" + b"\x00" * 8 + b"transformed" + admin.put_object(Bucket=bucket, Key=name, Body=flagged) + + assert getattr(backend, read)("k") is _MISS[read] + assert _body(admin, bucket, name) == flagged + + +class TestHealthCheck: + def test_healthy(self, backend: Any) -> None: + healthy, details = backend.health_check() + + assert healthy is True + assert details["backend_type"] == "s3" + assert details["latency_ms"] >= 0 + + def test_missing_bucket_is_unhealthy(self) -> None: + healthy, details = _backend(f"cachekit-absent-{uuid.uuid4().hex[:16]}").health_check() + + assert healthy is False + assert "NoSuchBucket (HTTP 404)" in details["error"] + + @pytest.mark.parametrize( + "operation", + [lambda b: b.get("k"), lambda b: b.exists("k"), lambda b: b.set("k", b"v"), lambda b: b.delete("k")], + ids=["get", "exists", "set", "delete"], + ) + def test_every_operation_on_a_missing_bucket_raises(self, operation: Any) -> None: + """A wrong bucket name does not read as an empty cache.""" + with pytest.raises(BackendError) as exc_info: + operation(_backend(f"cachekit-absent-{uuid.uuid4().hex[:16]}")) + assert exc_info.value.error_type is BackendErrorType.PERMANENT + + +class TestDecoratorIntegration: + def test_cache_with_explicit_backend(self, backend: Any, admin: Any, bucket: str) -> None: + from cachekit import cache + + calls = 0 + + @cache(ttl=60, namespace="s3_it", backend=backend, l1_enabled=False) + def add(a: int, b: int) -> int: + nonlocal calls + calls += 1 + return a + b + + assert (add(2, 3), add(2, 3), calls) == (5, 5, 1) + assert add(10, 20) == 30 + assert calls == 2 + assert len(_names(admin, bucket)) == 2 + + def test_env_selection_builds_a_working_backend(self, admin: Any, bucket: str, monkeypatch: pytest.MonkeyPatch) -> None: + from cachekit.backends.provider import DefaultBackendProvider + from cachekit.backends.s3 import S3Backend + from tests.fixtures.zero_config import clear_cachekit_env + + clear_cachekit_env(monkeypatch) + monkeypatch.setenv("CACHEKIT_S3_BUCKET", bucket) + monkeypatch.setenv("CACHEKIT_S3_PREFIX", "env/") + monkeypatch.setenv("CACHEKIT_S3_ENDPOINT_URL", EMULATOR_ENDPOINT) + + selected = DefaultBackendProvider().get_backend() + + assert isinstance(selected, S3Backend) + selected.set("k", b"v", ttl=60) + assert selected.get("k") == b"v" + assert _names(admin, bucket)[0].startswith("env/") diff --git a/tests/unit/backends/test_provider.py b/tests/unit/backends/test_provider.py index c86ab572..7e460d59 100644 --- a/tests/unit/backends/test_provider.py +++ b/tests/unit/backends/test_provider.py @@ -418,7 +418,7 @@ def test_gcs_bucket_with_file_cache_dir_is_ambiguous(self, tmp_path: Path) -> No message = str(exc_info.value) assert "(CACHEKIT_FILE_CACHE_DIR, CACHEKIT_GCS_BUCKET)" in message - assert "CACHEKIT_FILE_CACHE_DIR / CACHEKIT_GCS_BUCKET, or pass backend=" in message + assert "CACHEKIT_FILE_CACHE_DIR / CACHEKIT_GCS_BUCKET / CACHEKIT_S3_BUCKET, or pass backend=" in message def test_gcs_bucket_counts_as_configured(self) -> None: """With only CACHEKIT_GCS_BUCKET set, in any casing, a decorator must not fall back to L1 only.""" @@ -426,6 +426,46 @@ def test_gcs_bucket_counts_as_configured(self) -> None: with mock.patch.dict("os.environ", {name: "cache-bucket"}, clear=True): assert DefaultBackendProvider()._is_configured() is True + def test_get_backend_returns_s3_when_bucket_set(self) -> None: + """CACHEKIT_S3_BUCKET alone → S3Backend, built once from the environment.""" + from cachekit.backends.s3 import S3BackendConfig + + provider = DefaultBackendProvider() + assert provider._s3_backend is None + + with mock.patch.dict("os.environ", {"CACHEKIT_S3_BUCKET": "cache-bucket"}, clear=True): + with mock.patch("cachekit.backends.s3.S3Backend") as mock_s3: + backend = provider.get_backend() + + assert backend is mock_s3.return_value + assert provider.get_backend() is backend + mock_s3.assert_called_once() + (config,) = mock_s3.call_args.args + assert isinstance(config, S3BackendConfig) + assert config.bucket == "cache-bucket" + + def test_s3_bucket_with_gcs_bucket_is_ambiguous(self) -> None: + """CACHEKIT_S3_BUCKET is a selector like the others: a second one raises, and the message lists it.""" + from cachekit.config.validation import ConfigurationError + + provider = DefaultBackendProvider() + + with mock.patch.dict( + "os.environ", {"CACHEKIT_S3_BUCKET": "cache-bucket", "CACHEKIT_GCS_BUCKET": "cache-bucket"}, clear=True + ): + with pytest.raises(ConfigurationError, match="Ambiguous backend") as exc_info: + provider.get_backend() + + message = str(exc_info.value) + assert "(CACHEKIT_GCS_BUCKET, CACHEKIT_S3_BUCKET)" in message + assert "CACHEKIT_GCS_BUCKET / CACHEKIT_S3_BUCKET, or pass backend=" in message + + def test_s3_bucket_counts_as_configured(self) -> None: + """With only CACHEKIT_S3_BUCKET set, in any casing, a decorator must not fall back to L1 only.""" + for name in ("CACHEKIT_S3_BUCKET", "cachekit_s3_bucket"): + with mock.patch.dict("os.environ", {name: "cache-bucket"}, clear=True): + assert DefaultBackendProvider()._is_configured() is True + def test_get_backend_explicit_redis_url(self) -> None: """CACHEKIT_REDIS_URL is an explicit selector → RedisBackend.""" provider = DefaultBackendProvider() diff --git a/tests/unit/backends/test_s3_backend.py b/tests/unit/backends/test_s3_backend.py new file mode 100644 index 00000000..276534c9 --- /dev/null +++ b/tests/unit/backends/test_s3_backend.py @@ -0,0 +1,765 @@ +"""Unit tests for S3Backend. + +The backend runs on the real boto3 client, built by the backend's own code, with every HTTP +exchange answered from a script at botocore's ``before-send`` event. Each test sees the requests +the backend sends: how many, which method, which headers. Nothing leaves the process. +tests/integration/test_s3_integration.py covers a live server. +""" + +from __future__ import annotations + +import base64 +import contextlib +import hashlib +import io +import json +import struct +import subprocess +import sys +import zlib +from pathlib import Path +from typing import Any +from urllib.parse import parse_qs, unquote, urlsplit + +import pytest +import time_machine + +pytest.importorskip("boto3", reason="needs the s3 extra") + +import urllib3 +from botocore.awsrequest import AWSPreparedRequest, AWSResponse +from botocore.exceptions import ( + ClientError, + ConnectionClosedError, + ConnectTimeoutError, + CredentialRetrievalError, + EndpointConnectionError, + FlexibleChecksumError, + HTTPClientError, + IncompleteReadError, + NoCredentialsError, + ParamValidationError, + PartialCredentialsError, + ReadTimeoutError, + SSLError, + UnauthorizedSSOTokenError, +) + +from cachekit.backends.base import BaseBackend, TTLInspectableBackend +from cachekit.backends.errors import BackendError, BackendErrorType +from cachekit.backends.file import FileBackend, FileBackendConfig +from cachekit.backends.s3 import S3Backend, S3BackendConfig +from cachekit.backends.s3 import backend as backend_module +from cachekit.backends.s3.error_handler import classify_s3_error + +BUCKET = "cache-bucket" +FIXTURE_PATH = Path(__file__).parents[1] / "protocol" / "fixtures" / "file-backend.json" +VECTORS: list[dict[str, Any]] = json.loads(FIXTURE_PATH.read_text(encoding="utf-8"))["vectors"] + +# Every AWS_* variable that could point the client at ambient credentials, config or an endpoint. +_AMBIENT_AWS_ENV = ( + "AWS_PROFILE", + "AWS_DEFAULT_PROFILE", + "AWS_SESSION_TOKEN", + "AWS_REGION", + "AWS_ENDPOINT_URL", + "AWS_ENDPOINT_URL_S3", + "AWS_MAX_ATTEMPTS", + "AWS_RETRY_MODE", + "AWS_REQUEST_CHECKSUM_CALCULATION", + "AWS_RESPONSE_CHECKSUM_VALIDATION", + "AWS_WEB_IDENTITY_TOKEN_FILE", + "AWS_ROLE_ARN", + "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", + "AWS_CONTAINER_CREDENTIALS_FULL_URI", + "CACHEKIT_S3_BUCKET", + "CACHEKIT_S3_PREFIX", + "CACHEKIT_S3_ENDPOINT_URL", + "CACHEKIT_S3_REGION", + "CACHEKIT_S3_TIMEOUT", +) + + +def _header(expiry: int = 0, reserved: int = 0, flags: int = 0) -> bytes: + return b"CK\x01" + bytes([reserved]) + struct.pack(">H", flags) + struct.pack(">Q", expiry) + + +def _name(key: str) -> str: + return hashlib.blake2b(key.encode("utf-8"), digest_size=16).hexdigest() + + +class _Reply: + """One scripted HTTP response, or the exception the transport raises instead. + + ``code`` makes the body the XML error document S3 sends with a failure. + """ + + def __init__( + self, + status: int = 200, + body: bytes = b"", + code: str | None = None, + error: Exception | None = None, + headers: dict[str, str] | None = None, + raw: Any = None, + ): + if code is not None: + body = f'{code}about {BUCKET}'.encode() + self.status = status + self.body = body + self.error = error + self.headers = {"Content-Length": str(len(body)), **(headers or {})} + self.raw = raw + + +class _Wire: + """Answers each request with the next scripted reply, and records the request.""" + + def __init__(self) -> None: + self.replies: list[_Reply] = [] + self.requests: list[AWSPreparedRequest] = [] + + def __call__(self, request: AWSPreparedRequest, **kwargs: Any) -> AWSResponse: + self.requests.append(request) + assert self.replies, f"unscripted request: {request.method} {request.url}" + reply = self.replies.pop(0) + if reply.error is not None: + raise reply.error + raw = reply.raw or urllib3.HTTPResponse( + body=io.BytesIO(reply.body), headers=reply.headers, status=reply.status, preload_content=False + ) + return AWSResponse(request.url, reply.status, reply.headers, raw) + + def script(self, *replies: _Reply) -> None: + self.replies.extend(replies) + + def sent(self) -> list[tuple[str, str]]: + """(method, path) of every request so far. The bucket is in the host name, so the path is the object key.""" + return [(r.method, unquote(urlsplit(r.url).path)) for r in self.requests] + + def query(self, index: int = 0) -> dict[str, list[str]]: + return parse_qs(urlsplit(self.requests[index].url).query, keep_blank_values=True) + + +@pytest.fixture +def wire(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> _Wire: + """The wire every client built by S3Backend talks to, with credentials that reach nothing.""" + for name in _AMBIENT_AWS_ENV: + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("AWS_ACCESS_KEY_ID", "test-access-key") + monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "test-secret-key") # pragma: allowlist secret + monkeypatch.setenv("AWS_DEFAULT_REGION", "us-east-1") + monkeypatch.setenv("AWS_EC2_METADATA_DISABLED", "true") + monkeypatch.setenv("AWS_CONFIG_FILE", str(tmp_path / "no-aws-config")) + monkeypatch.setenv("AWS_SHARED_CREDENTIALS_FILE", str(tmp_path / "no-aws-credentials")) + + wire = _Wire() + build_client = backend_module._build_client + + def build(config: S3BackendConfig) -> Any: + client = build_client(config) + # A handler that returns a response stands in for the HTTP send, on every attempt. + client.meta.events.register("before-send.s3", wire) + return client + + monkeypatch.setattr(backend_module, "_build_client", build) + return wire + + +@pytest.fixture +def backend(wire: _Wire) -> S3Backend: + return S3Backend(S3BackendConfig(bucket=BUCKET)) + + +def _uploaded(request: AWSPreparedRequest) -> bytes: + """The object bytes of a PutObject request. + + Over HTTPS botocore frames the body as ``aws-chunked``: hex-sized chunks, then the checksum as + a trailer. The framing is transfer encoding, so it is undone here; what S3 stores is the bytes inside. + """ + body = request.body + if not isinstance(body, (bytes, bytearray)): + assert body is not None + body.seek(0) + body = body.read() + if request.headers.get("Content-Encoding") not in ("aws-chunked", b"aws-chunked"): + return bytes(body) + stored = bytearray() + while True: + size, _, body = body.partition(b"\r\n") + length = int(size, 16) + if length == 0: + return bytes(stored) + stored += body[:length] + assert body[length : length + 2] == b"\r\n" + body = body[length + 2 :] + + +def _crc32(data: bytes) -> str: + return base64.b64encode(struct.pack(">I", zlib.crc32(data))).decode() + + +@pytest.mark.unit +class TestProtocolCompliance: + def test_is_a_base_backend(self, backend: S3Backend) -> None: + assert isinstance(backend, BaseBackend) + + def test_is_not_ttl_inspectable(self, backend: S3Backend) -> None: + """Objects are immutable: refreshing a TTL would rewrite the whole object.""" + assert not isinstance(backend, TTLInspectableBackend) + + def test_construction_sends_no_request(self, wire: _Wire) -> None: + S3Backend(S3BackendConfig(bucket=BUCKET)) + assert wire.requests == [] + + +@pytest.mark.unit +class TestGet: + def test_hit_is_one_unranged_get_object(self, backend: S3Backend, wire: _Wire) -> None: + wire.script(_Reply(body=_header() + b"value")) + + assert backend.get("k") == b"value" + + assert wire.sent() == [("GET", f"/{_name('k')}")] # no HeadObject first + assert urlsplit(wire.requests[0].url).hostname == f"{BUCKET}.s3.amazonaws.com" + assert "Range" not in wire.requests[0].headers + + @pytest.mark.parametrize("reply", [_Reply(status=404, code="NoSuchKey"), _Reply(status=404)], ids=["NoSuchKey", "bare-404"]) + def test_absent_object_is_a_miss_in_one_request(self, backend: S3Backend, wire: _Wire, reply: _Reply) -> None: + wire.script(reply) + + assert backend.get("k") is None + assert len(wire.requests) == 1 + + def test_empty_payload_round_trips(self, backend: S3Backend, wire: _Wire) -> None: + wire.script(_Reply(body=_header())) + assert backend.get("k") == b"" + + @time_machine.travel(1_000_000, tick=False) + def test_entry_is_live_until_its_expiry_second(self, backend: S3Backend, wire: _Wire) -> None: + wire.script(_Reply(body=_header(expiry=1_000_001) + b"v")) + assert backend.get("k") == b"v" + + @time_machine.travel(1_000_000, tick=False) + def test_expired_entry_is_a_miss_and_is_not_deleted(self, backend: S3Backend, wire: _Wire) -> None: + wire.script(_Reply(body=_header(expiry=1_000_000) + b"v")) + + assert backend.get("k") is None + assert wire.sent() == [("GET", f"/{_name('k')}")] + + @pytest.mark.parametrize( + "body", + [b"", b"CK\x01", _header()[:13], b"XX" + _header()[2:] + b"v", b"CK\x02" + _header()[3:] + b"v"], + ids=["empty", "short", "one-byte-short", "bad-magic", "bad-version"], + ) + def test_corrupt_entry_is_a_miss_and_is_not_deleted(self, backend: S3Backend, wire: _Wire, body: bytes) -> None: + wire.script(_Reply(body=body)) + + assert backend.get("k") is None + assert [method for method, _ in wire.sent()] == ["GET"] + + @pytest.mark.parametrize("reserved,flags", [(1, 0), (0, 1), (0, 0x8000)]) + def test_unknown_transform_is_a_miss_and_is_not_deleted( + self, backend: S3Backend, wire: _Wire, reserved: int, flags: int + ) -> None: + wire.script(_Reply(body=_header(reserved=reserved, flags=flags) + b"v")) + + assert backend.get("k") is None + assert [method for method, _ in wire.sent()] == ["GET"] + + def test_body_is_checked_against_the_checksum_sent_with_it(self, backend: S3Backend, wire: _Wire) -> None: + body = _header() + b"value" + wire.script( + _Reply(body=body, headers={"x-amz-checksum-crc32": _crc32(body)}), + _Reply(body=body, headers={"x-amz-checksum-crc32": _crc32(b"other bytes")}), + ) + + assert backend.get("k") == b"value" + with pytest.raises(BackendError) as exc_info: + backend.get("k") + assert exc_info.value.error_type is BackendErrorType.TRANSIENT + assert isinstance(exc_info.value.original_exception, FlexibleChecksumError) + + def test_body_that_ends_early_is_transient(self, backend: S3Backend, wire: _Wire) -> None: + wire.script(_Reply(body=_header(), headers={"Content-Length": "100"})) + + with pytest.raises(BackendError) as exc_info: + backend.get("k") + assert exc_info.value.error_type is BackendErrorType.TRANSIENT + assert isinstance(exc_info.value.original_exception, IncompleteReadError) + + def test_timeout_part_way_through_the_body_is_a_timeout(self, backend: S3Backend, wire: _Wire) -> None: + class _Stalls: + def read(self, amt: int | None = None) -> bytes: + raise urllib3.exceptions.ReadTimeoutError(None, None, "Read timed out.") # type: ignore[arg-type] + + wire.script(_Reply(headers={"Content-Length": "100"}, raw=_Stalls())) + + with pytest.raises(BackendError) as exc_info: + backend.get("k") + assert exc_info.value.error_type is BackendErrorType.TIMEOUT + + +@pytest.mark.unit +class TestExists: + def test_reads_only_the_header(self, backend: S3Backend, wire: _Wire) -> None: + wire.script(_Reply(status=206, body=_header())) + + assert backend.exists("k") is True + + assert wire.sent() == [("GET", f"/{_name('k')}")] + assert wire.requests[0].headers["Range"] in ("bytes=0-13", b"bytes=0-13") + + def test_store_that_ignores_the_range_still_answers(self, backend: S3Backend, wire: _Wire) -> None: + wire.script(_Reply(body=_header() + b"the whole object")) + assert backend.exists("k") is True + + def test_absent_object(self, backend: S3Backend, wire: _Wire) -> None: + wire.script(_Reply(status=404, code="NoSuchKey")) + assert backend.exists("k") is False + + @time_machine.travel(1_000_000, tick=False) + def test_expired_entry_is_a_miss_and_is_not_deleted(self, backend: S3Backend, wire: _Wire) -> None: + wire.script(_Reply(status=206, body=_header(expiry=999_999))) + + assert backend.exists("k") is False + assert [method for method, _ in wire.sent()] == ["GET"] + + def test_empty_object_is_a_miss_in_one_request(self, backend: S3Backend, wire: _Wire) -> None: + """An empty object has no first byte, so the ranged read is refused with a 416.""" + wire.script(_Reply(status=416, code="InvalidRange")) + + assert backend.exists("k") is False + assert [method for method, _ in wire.sent()] == ["GET"] + + @pytest.mark.parametrize("body", [b"CK\x01", b"XX" + _header()[2:]], ids=["short", "bad-magic"]) + def test_corrupt_entry_is_a_miss_and_is_not_deleted(self, backend: S3Backend, wire: _Wire, body: bytes) -> None: + wire.script(_Reply(status=206, body=body)) + + assert backend.exists("k") is False + assert [method for method, _ in wire.sent()] == ["GET"] + + def test_unknown_transform_is_a_miss_and_is_not_deleted(self, backend: S3Backend, wire: _Wire) -> None: + wire.script(_Reply(status=206, body=_header(flags=1))) + + assert backend.exists("k") is False + assert len(wire.requests) == 1 + + +@pytest.mark.unit +class TestSet: + @time_machine.travel(1_000_000, tick=False) + def test_is_one_put_object_of_header_and_value(self, backend: S3Backend, wire: _Wire) -> None: + wire.script(_Reply()) + + backend.set("k", b"value", ttl=60) + + assert wire.sent() == [("PUT", f"/{_name('k')}")] + assert wire.query() == {} # a plain PutObject: no uploads, no uploadId + assert _uploaded(wire.requests[0]) == _header(expiry=1_000_060) + b"value" + assert wire.requests[0].headers["Content-Type"] in ("application/octet-stream", b"application/octet-stream") + + def test_large_value_is_still_one_put_object(self, backend: S3Backend, wire: _Wire) -> None: + """Past the size at which boto3's transfer manager would switch to a multipart upload.""" + value = bytes(9 * 1024 * 1024) + wire.script(_Reply()) + + backend.set("k", value) + + assert wire.sent() == [("PUT", f"/{_name('k')}")] + assert wire.query() == {} + assert len(_uploaded(wire.requests[0])) == 14 + len(value) + + def test_upload_carries_a_crc32_checksum(self, backend: S3Backend, wire: _Wire) -> None: + """boto3's default. Over HTTPS it is a trailer after an aws-chunked body (docs/backends/s3.md).""" + wire.script(_Reply()) + + backend.set("k", b"value") + + headers = wire.requests[0].headers + assert headers["X-Amz-Trailer"] in ("x-amz-checksum-crc32", b"x-amz-checksum-crc32") + assert headers["Content-Encoding"] in ("aws-chunked", b"aws-chunked") + + def test_checksums_are_off_when_the_environment_says_so(self, wire: _Wire, monkeypatch: pytest.MonkeyPatch) -> None: + """The switch docs/backends/s3.md names for a store that refuses them: a plain body, no checksum asked for.""" + monkeypatch.setenv("AWS_REQUEST_CHECKSUM_CALCULATION", "when_required") + monkeypatch.setenv("AWS_RESPONSE_CHECKSUM_VALIDATION", "when_required") + backend = S3Backend(S3BackendConfig(bucket=BUCKET)) + wire.script(_Reply(), _Reply(body=_header() + b"value")) + + backend.set("k", b"value") + backend.get("k") + + put, get = wire.requests + assert not {"Content-Encoding", "X-Amz-Trailer", "x-amz-checksum-crc32"} & set(put.headers.keys()) + assert _uploaded(put) == _header() + b"value" + assert "x-amz-checksum-mode" not in get.headers + + @pytest.mark.parametrize("ttl", [None, 0]) + def test_no_ttl_writes_no_expiry(self, backend: S3Backend, wire: _Wire, ttl: int | None) -> None: + wire.script(_Reply()) + backend.set("k", b"v", ttl=ttl) + assert _uploaded(wire.requests[0]) == _header(expiry=0) + b"v" + + @pytest.mark.parametrize("ttl", [-1, 10 * 365 * 24 * 60 * 60 + 1]) + def test_out_of_range_ttl_is_refused_before_any_request(self, backend: S3Backend, wire: _Wire, ttl: int) -> None: + with pytest.raises(BackendError) as exc_info: + backend.set("k", b"v", ttl=ttl) + + assert exc_info.value.error_type is BackendErrorType.PERMANENT + assert wire.requests == [] + + @pytest.mark.parametrize("ttl", [None, 0, 1, 3600]) + @pytest.mark.parametrize("value", [b"", b"value", bytes(range(256)) * 4]) + @time_machine.travel(1_700_000_000, tick=False) + def test_object_is_byte_identical_to_the_file_backend( + self, backend: S3Backend, wire: _Wire, tmp_path: Path, value: bytes, ttl: int | None + ) -> None: + key = "ns:app:func:mod.fn:args:" + "ab" * 32 + ":1s" + cache_dir = tmp_path / "file-backend" + FileBackend(FileBackendConfig(cache_dir=cache_dir)).set(key, value, ttl=ttl) + (written,) = [p for p in cache_dir.iterdir() if p.is_file()] + wire.script(_Reply()) + + backend.set(key, value, ttl=ttl) + + assert _uploaded(wire.requests[0]) == written.read_bytes() + assert wire.sent() == [("PUT", f"/{written.name}")] + + +@pytest.mark.unit +class TestDelete: + def test_is_one_delete_object_and_true(self, backend: S3Backend, wire: _Wire) -> None: + """S3 answers 204 whether or not the object existed, so True means the request succeeded.""" + wire.script(_Reply(status=204)) + + assert backend.delete("k") is True + assert wire.sent() == [("DELETE", f"/{_name('k')}")] + + @pytest.mark.parametrize("reply", [_Reply(status=404, code="NoSuchKey"), _Reply(status=404)], ids=["NoSuchKey", "bare-404"]) + def test_store_that_answers_404_for_an_absent_object_is_still_true( + self, backend: S3Backend, wire: _Wire, reply: _Reply + ) -> None: + wire.script(reply) + assert backend.delete("k") is True + + +@pytest.mark.unit +class TestPrefix: + def test_prefix_precedes_the_name_verbatim(self, wire: _Wire) -> None: + backend = S3Backend(S3BackendConfig(bucket=BUCKET, prefix="cachekit/v1-")) + wire.script(_Reply(status=404, code="NoSuchKey"), _Reply(status=404, code="NoSuchKey"), _Reply(status=204), _Reply()) + + backend.get("k") + backend.exists("k") + backend.delete("k") + backend.set("k", b"v") + + assert {path for _, path in wire.sent()} == {f"/cachekit/v1-{_name('k')}"} + + def test_prefix_is_not_a_key_prefix(self, wire: _Wire) -> None: + """A storage location only: nothing reads it as part of the cache key or the AAD.""" + assert not hasattr(S3Backend(S3BackendConfig(bucket=BUCKET, prefix="p/")), "key_prefix") + + +_STATUS_CASES = [ + (401, "Unauthorized", BackendErrorType.AUTHENTICATION), + (403, "AccessDenied", BackendErrorType.AUTHENTICATION), + (403, "InvalidAccessKeyId", BackendErrorType.AUTHENTICATION), + (403, "SignatureDoesNotMatch", BackendErrorType.AUTHENTICATION), + (400, "ExpiredToken", BackendErrorType.AUTHENTICATION), + (400, "InvalidToken", BackendErrorType.AUTHENTICATION), + (429, "TooManyRequests", BackendErrorType.TRANSIENT), + (500, "InternalError", BackendErrorType.TRANSIENT), + (502, None, BackendErrorType.TRANSIENT), + (503, "SlowDown", BackendErrorType.TRANSIENT), + (503, "ServiceUnavailable", BackendErrorType.TRANSIENT), + (504, None, BackendErrorType.TRANSIENT), + (408, None, BackendErrorType.TIMEOUT), + (400, "RequestTimeout", BackendErrorType.TIMEOUT), + (400, "InvalidRequest", BackendErrorType.PERMANENT), + (404, "NoSuchBucket", BackendErrorType.PERMANENT), + (412, "PreconditionFailed", BackendErrorType.PERMANENT), +] +_TRANSPORT_CASES = [ + (ReadTimeoutError(endpoint_url="https://s3"), BackendErrorType.TIMEOUT), + (ConnectTimeoutError(endpoint_url="https://s3"), BackendErrorType.TIMEOUT), + (TimeoutError(), BackendErrorType.TIMEOUT), + (EndpointConnectionError(endpoint_url="https://s3"), BackendErrorType.TRANSIENT), + (ConnectionClosedError(endpoint_url="https://s3"), BackendErrorType.TRANSIENT), + (HTTPClientError(error="broken"), BackendErrorType.TRANSIENT), + (SSLError(endpoint_url="https://s3", error="handshake"), BackendErrorType.TRANSIENT), + (ConnectionResetError(), BackendErrorType.TRANSIENT), + (CredentialRetrievalError(provider="container-role", error_msg="no answer"), BackendErrorType.TRANSIENT), + (NoCredentialsError(), BackendErrorType.AUTHENTICATION), + (PartialCredentialsError(provider="env", cred_var="AWS_SECRET_ACCESS_KEY"), BackendErrorType.AUTHENTICATION), + (UnauthorizedSSOTokenError(), BackendErrorType.AUTHENTICATION), + (ParamValidationError(report="bad parameter"), BackendErrorType.PERMANENT), + (ValueError("?"), BackendErrorType.UNKNOWN), +] +_OPERATIONS = { + "get": lambda b: b.get("k"), + "set": lambda b: b.set("k", b"v", ttl=60), + "delete": lambda b: b.delete("k"), + "exists": lambda b: b.exists("k"), +} + + +@pytest.mark.unit +class TestErrors: + @pytest.mark.parametrize("operation", _OPERATIONS) + @pytest.mark.parametrize("status,code,error_type", _STATUS_CASES) + def test_http_status_mapping( + self, backend: S3Backend, wire: _Wire, operation: str, status: int, code: str | None, error_type: BackendErrorType + ) -> None: + wire.script(_Reply(status=status, code=code)) + + with pytest.raises(BackendError) as exc_info: + _OPERATIONS[operation](backend) + + assert exc_info.value.error_type is error_type + assert exc_info.value.operation == operation + assert isinstance(exc_info.value.original_exception, ClientError) + assert len(wire.requests) == 1 # no retry + + @pytest.mark.parametrize("operation", _OPERATIONS) + @pytest.mark.parametrize( + "error,error_type", _TRANSPORT_CASES, ids=[f"{i}-{type(e).__name__}" for i, (e, _) in enumerate(_TRANSPORT_CASES)] + ) + def test_transport_error_mapping( + self, backend: S3Backend, wire: _Wire, operation: str, error: Exception, error_type: BackendErrorType + ) -> None: + wire.script(_Reply(error=error)) + + with pytest.raises(BackendError) as exc_info: + _OPERATIONS[operation](backend) + + assert exc_info.value.error_type is error_type + assert exc_info.value.original_exception is error + assert len(wire.requests) == 1 # no retry + + @pytest.mark.parametrize("read", ["get", "exists"]) + def test_miss_without_list_permission_is_an_authentication_error(self, backend: S3Backend, wire: _Wire, read: str) -> None: + """S3 answers 403, not 404, for an absent object when the caller lacks s3:ListBucket.""" + wire.script(_Reply(status=403, code="AccessDenied")) + + with pytest.raises(BackendError) as exc_info: + getattr(backend, read)("k") + assert exc_info.value.error_type is BackendErrorType.AUTHENTICATION + + @pytest.mark.parametrize("read", ["get", "exists"]) + def test_missing_bucket_is_not_a_miss(self, backend: S3Backend, wire: _Wire, read: str) -> None: + wire.script(_Reply(status=404, code="NoSuchBucket")) + + with pytest.raises(BackendError) as exc_info: + getattr(backend, read)("k") + assert exc_info.value.error_type is BackendErrorType.PERMANENT + + def test_unsatisfiable_range_on_a_whole_read_is_an_error(self, backend: S3Backend, wire: _Wire) -> None: + """Only the header read asks for a range, so only there does a 416 mean an empty object.""" + wire.script(_Reply(status=416, code="InvalidRange")) + + with pytest.raises(BackendError) as exc_info: + backend.get("k") + assert exc_info.value.error_type is BackendErrorType.PERMANENT + + def test_ambient_retry_settings_do_not_reach_the_client(self, wire: _Wire, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("AWS_MAX_ATTEMPTS", "5") + monkeypatch.setenv("AWS_RETRY_MODE", "adaptive") + backend = S3Backend(S3BackendConfig(bucket=BUCKET)) + wire.script(_Reply(status=503, code="SlowDown")) + + with pytest.raises(BackendError): + backend.get("k") + assert len(wire.requests) == 1 + + def test_message_carries_no_bucket_object_or_key(self, backend: S3Backend, wire: _Wire) -> None: + """S3's error text names the resource and the caller; only the code and status reach str(e).""" + wire.script(_Reply(status=403, code="AccessDenied")) + + with pytest.raises(BackendError) as exc_info: + backend.get("tenant-42:secret-key") + + text = str(exc_info.value) + assert "AccessDenied (HTTP 403)" in text + for leak in (BUCKET, _name("tenant-42:secret-key"), "tenant-42", "about"): + assert leak not in text + + def test_error_code_that_is_free_text_stays_out_of_the_message(self, backend: S3Backend, wire: _Wire) -> None: + wire.script(_Reply(status=400, code=f"denied for {BUCKET}")) + + with pytest.raises(BackendError) as exc_info: + backend.get("k") + assert "ClientError (HTTP 400)" in str(exc_info.value) + assert BUCKET not in str(exc_info.value) + + def test_classifier_defaults(self) -> None: + error = classify_s3_error(KeyError("x")) + assert error.error_type is BackendErrorType.UNKNOWN + assert error.operation is None + + +@pytest.mark.unit +class TestHealthCheck: + def test_healthy_is_one_object_listing(self, backend: S3Backend, wire: _Wire) -> None: + wire.script(_Reply(body=b'0')) + + healthy, details = backend.health_check() + + assert healthy is True + assert details["backend_type"] == "s3" + assert details["bucket"] == BUCKET + assert isinstance(details["latency_ms"], float) + assert "error" not in details + assert wire.sent() == [("GET", "/")] + query = wire.query() + assert (query["list-type"], query["max-keys"], query["prefix"]) == (["2"], ["1"], [""]) + + def test_listing_is_scoped_to_the_prefix(self, wire: _Wire) -> None: + wire.script(_Reply(body=b'')) + S3Backend(S3BackendConfig(bucket=BUCKET, prefix="p/")).health_check() + assert wire.query()["prefix"] == ["p/"] + + @pytest.mark.parametrize( + "reply", + [ + _Reply(status=403, code="AccessDenied"), # an identity without s3:ListBucket + _Reply(status=404, code="NoSuchBucket"), + _Reply(error=ReadTimeoutError(endpoint_url="https://s3")), + ], + ids=["no-list-permission", "no-such-bucket", "timeout"], + ) + def test_unhealthy_reports_the_error_and_does_not_raise(self, backend: S3Backend, wire: _Wire, reply: _Reply) -> None: + wire.script(reply) + + healthy, details = backend.health_check() + + assert healthy is False + assert details["backend_type"] == "s3" + assert "latency_ms" in details + assert "operation=health_check" in details["error"] + assert len(wire.requests) == 1 + + +@pytest.mark.unit +class TestConstruction: + def test_config_defaults_to_the_environment(self, wire: _Wire, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("CACHEKIT_S3_BUCKET", BUCKET) + monkeypatch.setenv("CACHEKIT_S3_PREFIX", "env/") + wire.script(_Reply(status=404, code="NoSuchKey")) + + S3Backend().get("k") + + assert wire.sent() == [("GET", f"/env/{_name('k')}")] + + def test_client_sends_each_request_once_within_the_configured_timeout(self, wire: _Wire) -> None: + client_config = S3Backend(S3BackendConfig(bucket=BUCKET, timeout=2.5))._client.meta.config + + assert client_config.retries == {"total_max_attempts": 1, "mode": "standard"} + assert (client_config.connect_timeout, client_config.read_timeout) == (2.5, 2.5) + + def test_endpoint_url_and_region_reach_the_client(self, wire: _Wire) -> None: + backend = S3Backend(S3BackendConfig(bucket=BUCKET, endpoint_url="http://127.0.0.1:9", region="eu-west-2")) + wire.script(_Reply(status=404, code="NoSuchKey")) + + backend.get("k") + + assert backend._client.meta.region_name == "eu-west-2" + assert wire.requests[0].url == f"http://127.0.0.1:9/{BUCKET}/{_name('k')}" + + def test_missing_library_names_the_extra(self) -> None: + """In an interpreter where boto3 cannot load: the imports work, the constructor explains.""" + script = ( + "import sys\n" + "sys.modules['boto3'] = None\n" + "sys.modules['botocore'] = None\n" + "import cachekit, cachekit.backends, cachekit.backends.s3\n" + "from cachekit.backends.s3 import S3Backend, S3BackendConfig\n" + "try:\n" + " S3Backend(S3BackendConfig(bucket='cache-bucket'))\n" + "except ImportError as exc:\n" + " print(exc)\n" + ) + result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=60) # noqa: S603 + + assert result.returncode == 0, result.stderr + assert "pip install 'cachekit[s3]'" in result.stdout + + def test_missing_credentials_raise_on_the_first_operation(self, wire: _Wire, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("AWS_ACCESS_KEY_ID") + monkeypatch.delenv("AWS_SECRET_ACCESS_KEY") + backend = S3Backend(S3BackendConfig(bucket=BUCKET)) + + with pytest.raises(BackendError) as exc_info: + backend.get("k") + + assert exc_info.value.error_type is BackendErrorType.AUTHENTICATION + assert wire.requests == [] + + def test_client_boto3_cannot_build_is_a_backend_error(self, monkeypatch: pytest.MonkeyPatch) -> None: + def refuses(config: S3BackendConfig) -> Any: + raise ValueError("Invalid endpoint") + + monkeypatch.setattr(backend_module, "_build_client", refuses) + + with pytest.raises(BackendError) as exc_info: + S3Backend(S3BackendConfig(bucket=BUCKET)) + assert exc_info.value.operation == "init" + + +def _serve(wire: _Wire, vector: dict[str, Any], ranged: bool) -> None: + body = bytes.fromhex(vector["file_hex"]) + wire.script(_Reply(status=206 if ranged else 200, body=body[:14] if ranged else body)) + + +def _reader_clock(vector: dict[str, Any]) -> contextlib.AbstractContextManager[Any]: + if "reader_now_unix_seconds" not in vector: + return contextlib.nullcontext() + return time_machine.travel(vector["reader_now_unix_seconds"], tick=False) + + +@pytest.mark.unit +@pytest.mark.parametrize("vector", VECTORS, ids=lambda v: v["name"]) +class TestProtocolVectors: + """The protocol's file-backend vectors, served as objects (tests/unit/protocol/fixtures/file-backend.json).""" + + def test_object_name(self, backend: S3Backend, wire: _Wire, vector: dict[str, Any]) -> None: + wire.script(_Reply(status=404, code="NoSuchKey")) + backend.get(vector["key_utf8"]) + assert wire.sent() == [("GET", f"/{vector['filename']}")] + + def test_get(self, backend: S3Backend, wire: _Wire, vector: dict[str, Any]) -> None: + _serve(wire, vector, ranged=False) + + with _reader_clock(vector): + result = backend.get(vector["key_utf8"]) + + self._check(wire, vector, result, miss=None, hit=bytes.fromhex(vector["payload_hex"])) + + def test_exists(self, backend: S3Backend, wire: _Wire, vector: dict[str, Any]) -> None: + _serve(wire, vector, ranged=True) + + with _reader_clock(vector): + result = backend.exists(vector["key_utf8"]) + + self._check(wire, vector, result, miss=False, hit=True) + + def test_set_writes_the_vector_bytes(self, backend: S3Backend, wire: _Wire, vector: dict[str, Any]) -> None: + """A writer never sets the reserved byte or a flag, so only unflagged vectors can be written.""" + if vector["reader_action"] == "miss_preserve": + pytest.skip("this writer emits no reserved byte or flag") + expiry = vector["expiry_unix_seconds"] + wire.script(_Reply()) + + with time_machine.travel(expiry - 60 if expiry else 0, tick=False): + backend.set(vector["key_utf8"], bytes.fromhex(vector["payload_hex"]), ttl=60 if expiry else None) + + assert _uploaded(wire.requests[0]).hex() == vector["file_hex"] + + @staticmethod + def _check(wire: _Wire, vector: dict[str, Any], result: Any, miss: Any, hit: Any) -> None: + """Whatever the vector's action, the read is one GET: this backend removes nothing on a read.""" + action = vector["reader_action"] + assert action in ("return_payload", "miss_preserve", "miss_expired") + assert result == hit if action == "return_payload" else result is miss + assert [method for method, _ in wire.sent()] == ["GET"] diff --git a/tests/unit/backends/test_s3_config.py b/tests/unit/backends/test_s3_config.py new file mode 100644 index 00000000..5e9ebc95 --- /dev/null +++ b/tests/unit/backends/test_s3_config.py @@ -0,0 +1,94 @@ +"""Unit tests for S3BackendConfig. They need no boto3: the config imports none of it.""" + +from __future__ import annotations + +import pytest +from pydantic import ValidationError + +from cachekit.backends.s3.config import MAX_PREFIX_BYTES, S3BackendConfig + + +@pytest.fixture(autouse=True) +def _no_s3_env(monkeypatch: pytest.MonkeyPatch) -> None: + for field in S3BackendConfig.model_fields: + monkeypatch.delenv(f"CACHEKIT_S3_{field.upper()}", raising=False) + + +@pytest.mark.unit +class TestS3BackendConfig: + def test_defaults(self) -> None: + config = S3BackendConfig(bucket="cache-bucket") + + assert (config.bucket, config.prefix, config.endpoint_url, config.region, config.timeout) == ( + "cache-bucket", + "", + None, + None, + 10.0, + ) + + def test_fields_are_exactly_these(self) -> None: + """No credential field: authentication is boto3's default credential chain only.""" + assert set(S3BackendConfig.model_fields) == {"bucket", "prefix", "endpoint_url", "region", "timeout"} + + def test_bucket_is_required(self) -> None: + with pytest.raises(ValidationError): + S3BackendConfig.from_env() + + @pytest.mark.parametrize("bucket", ["", "s3://cache-bucket", "cache-bucket/prefix"]) + def test_bucket_must_be_a_bare_name(self, bucket: str) -> None: + with pytest.raises(ValidationError): + S3BackendConfig(bucket=bucket) + + @pytest.mark.parametrize("prefix", ["a\nb", "a\rb", "x" * (MAX_PREFIX_BYTES + 1), "é" * (MAX_PREFIX_BYTES // 2 + 1)]) + def test_prefix_with_a_line_break_or_too_long_is_rejected(self, prefix: str) -> None: + with pytest.raises(ValidationError): + S3BackendConfig(bucket="cache-bucket", prefix=prefix) + + def test_longest_prefix_is_accepted(self) -> None: + assert len(S3BackendConfig(bucket="cache-bucket", prefix="x" * MAX_PREFIX_BYTES).prefix) == MAX_PREFIX_BYTES + + def test_empty_endpoint_url_and_region_mean_unset(self, monkeypatch: pytest.MonkeyPatch) -> None: + """A variable set to nothing, as a compose file gives for an unset one, must not fail or reach boto3.""" + monkeypatch.setenv("CACHEKIT_S3_BUCKET", "env-bucket") + monkeypatch.setenv("CACHEKIT_S3_ENDPOINT_URL", "") + monkeypatch.setenv("CACHEKIT_S3_REGION", " ") + + config = S3BackendConfig.from_env() + + assert (config.endpoint_url, config.region) == (None, None) + + @pytest.mark.parametrize("endpoint_url", ["s3.example.com", "ftp://s3.example.com"]) + def test_endpoint_url_needs_an_http_scheme(self, endpoint_url: str) -> None: + with pytest.raises(ValidationError): + S3BackendConfig(bucket="cache-bucket", endpoint_url=endpoint_url) + + @pytest.mark.parametrize("endpoint_url", ["https://s3.example.com", "http://localhost:5000"]) + def test_endpoint_url_is_kept_verbatim(self, endpoint_url: str) -> None: + assert S3BackendConfig(bucket="cache-bucket", endpoint_url=endpoint_url).endpoint_url == endpoint_url + + @pytest.mark.parametrize("timeout", [0, 0.05, 601]) + def test_timeout_bounds(self, timeout: float) -> None: + with pytest.raises(ValidationError): + S3BackendConfig(bucket="cache-bucket", timeout=timeout) + + def test_from_env(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("CACHEKIT_S3_BUCKET", "env-bucket") + monkeypatch.setenv("CACHEKIT_S3_PREFIX", "cachekit/") + monkeypatch.setenv("CACHEKIT_S3_ENDPOINT_URL", "https://s3.example.com") + monkeypatch.setenv("CACHEKIT_S3_REGION", "eu-west-2") + monkeypatch.setenv("CACHEKIT_S3_TIMEOUT", "2.5") + + config = S3BackendConfig.from_env() + + assert (config.bucket, config.prefix, config.endpoint_url, config.region, config.timeout) == ( + "env-bucket", + "cachekit/", + "https://s3.example.com", + "eu-west-2", + 2.5, + ) + + def test_constructor_beats_env(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("CACHEKIT_S3_BUCKET", "env-bucket") + assert S3BackendConfig(bucket="explicit").bucket == "explicit" diff --git a/tests/unit/test_l1_only_mode.py b/tests/unit/test_l1_only_mode.py index 74e177ea..232f9259 100644 --- a/tests/unit/test_l1_only_mode.py +++ b/tests/unit/test_l1_only_mode.py @@ -623,6 +623,7 @@ def leaks() -> str: "CACHEKIT_MEMCACHED_SERVERS", "CACHEKIT_FILE_CACHE_DIR", "CACHEKIT_GCS_BUCKET", + "CACHEKIT_S3_BUCKET", ): assert selector in msg diff --git a/uv.lock b/uv.lock index af625323..e7569d48 100644 --- a/uv.lock +++ b/uv.lock @@ -203,6 +203,34 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e5/ca/78d423b324b8d77900030fa59c4aa9054261ef0925631cd2501dd015b7b7/boolean_py-5.0-py3-none-any.whl", hash = "sha256:ef28a70bd43115208441b53a045d1549e2f0ec6e3d08a9d142cbc41c1938e8d9", size = 26577, upload-time = "2025-04-03T10:39:48.449Z" }, ] +[[package]] +name = "boto3" +version = "1.44.18" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "botocore" }, + { name = "jmespath" }, + { name = "s3transfer" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/32/20/88578d1af4a43f0f7af294b7acc5950659331389b0e80bff675f89672623/boto3-1.44.18.tar.gz", hash = "sha256:232b51762ec4dc19e3d309f06494b5107101fd487aac9a976f7dfab2a2277304", size = 113600, upload-time = "2026-12-02T17:38:25.246Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/14/ff/b6afdb80b12550d58f4fc0b6ba889bf944846c981c14de5f24c6626ee4fc/boto3-1.44.18-py3-none-any.whl", hash = "sha256:f5a718e7a500dbbaa4a229d64f60f3251f66b1d7923eafc7943ac35ffd156797", size = 140590, upload-time = "2026-12-02T17:38:23.841Z" }, +] + +[[package]] +name = "botocore" +version = "1.44.18" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jmespath" }, + { name = "python-dateutil" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/02/4c/8b1727b2f2ca0de756e4c5c74093a6cf782658179891087af959737cd252/botocore-1.44.18.tar.gz", hash = "sha256:c78f0a2346b4700d77702530d04c1fed525ef0bb9723218eb8a7cfeae07b6b28", size = 17789186, upload-time = "2026-12-02T17:38:20.598Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/98/07/bcaaa60914561acd75f0414ad0cee98228324fc67ee59ceec29525301f06/botocore-1.44.18-py3-none-any.whl", hash = "sha256:300bc45095e810c5d915cefacdd6ea9ef786fe566aa4e221bf0449b4e0e95076", size = 17501549, upload-time = "2026-12-02T17:38:17.946Z" }, +] + [[package]] name = "cachecontrol" version = "0.14.3" @@ -253,12 +281,16 @@ json = [ memcached = [ { name = "pymemcache" }, ] +s3 = [ + { name = "boto3" }, +] [package.dev-dependencies] dev = [ { name = "aiocache" }, { name = "basedpyright" }, { name = "bashlex" }, + { name = "boto3" }, { name = "cachetools" }, { name = "faker" }, { name = "fakeredis" }, @@ -292,6 +324,7 @@ fuzz = [ { name = "atheris" }, ] test = [ + { name = "boto3" }, { name = "faker" }, { name = "fakeredis" }, { name = "h11" }, @@ -314,6 +347,7 @@ test = [ [package.metadata] requires-dist = [ { name = "blake3", specifier = ">=1.0.5" }, + { name = "boto3", marker = "extra == 's3'", specifier = ">=1.36.0" }, { name = "google-cloud-storage", marker = "extra == 'gcs'", specifier = ">=3.0.0" }, { name = "msgpack", specifier = ">=1.2.1" }, { name = "numpy", marker = "extra == 'data'", specifier = ">=2.0.2" }, @@ -328,13 +362,14 @@ requires-dist = [ { name = "urllib3", specifier = ">=2.8.0" }, { name = "xxhash", specifier = ">=3.5.0" }, ] -provides-extras = ["data", "json", "memcached", "gcs"] +provides-extras = ["data", "json", "memcached", "gcs", "s3"] [package.metadata.requires-dev] dev = [ { name = "aiocache", specifier = ">=0.12.0" }, { name = "basedpyright", specifier = ">=1.32.1" }, { name = "bashlex", specifier = ">=0.18" }, + { name = "boto3", specifier = ">=1.36.0" }, { name = "cachetools", specifier = ">=5.3.0" }, { name = "faker", specifier = ">=20.0.0" }, { name = "fakeredis", specifier = ">=2.21.0" }, @@ -365,6 +400,7 @@ dev = [ ] fuzz = [{ name = "atheris", specifier = ">=2.3.0" }] test = [ + { name = "boto3", specifier = ">=1.36.0" }, { name = "faker", specifier = ">=20.0.0" }, { name = "fakeredis", specifier = ">=2.21.0" }, { name = "h11", specifier = ">=0.16.0" }, @@ -1073,6 +1109,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] +[[package]] +name = "jmespath" +version = "1.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d3/59/322338183ecda247fb5d1763a6cbe46eff7222eaeebafd9fa65d4bf5cb11/jmespath-1.1.0.tar.gz", hash = "sha256:472c87d80f36026ae83c6ddd0f1d05d4e510134ed462851fd5f754c8c3cbb88d", size = 27377, upload-time = "2026-01-22T16:35:26.279Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/14/2f/967ba146e6d58cf6a652da73885f52fc68001525b4197effc174321d70b4/jmespath-1.1.0-py3-none-any.whl", hash = "sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64", size = 20419, upload-time = "2026-01-22T16:35:24.919Z" }, +] + [[package]] name = "license-expression" version = "30.4.4" @@ -2328,6 +2373,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b7/73/4de6579bac8e979fca0a77e54dec1f1e011a0d268165eb8a9bc0982a6564/ruff-0.14.3-py3-none-win_arm64.whl", hash = "sha256:26eb477ede6d399d898791d01961e16b86f02bc2486d0d1a7a9bb2379d055dc1", size = 12590017, upload-time = "2025-10-31T00:26:24.52Z" }, ] +[[package]] +name = "s3transfer" +version = "0.19.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "botocore" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/49/c5/0a5ce655109cb96b8dfad36908a4e108d15f5dc2eff8fbc3146c4312e704/s3transfer-0.19.3.tar.gz", hash = "sha256:8326acc3d056d7f7b8a37110c7d2aea41f67e83f6ae79cd3b5fbcca34c726406", size = 166087, upload-time = "2026-10-19T19:19:49.751Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e2/a4/88f9e10498759121060b8050a1554753dfc04df39bbbcc7aad9ecc8d9440/s3transfer-0.19.3-py3-none-any.whl", hash = "sha256:24eb7535804306355e31c952a90022bf5b2f9d760f9a11062c7493a217c08553", size = 90252, upload-time = "2026-10-19T19:19:48.309Z" }, +] + [[package]] name = "six" version = "1.17.0"