From efad0cfd5d21b8f4d5eb32332dbc08491e0f776d Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:21:11 -0300 Subject: [PATCH 01/27] docs(site): polished 0.5.0 discovery, installation and migration landing (#48) --- mkdocs.yml | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 mkdocs.yml diff --git a/mkdocs.yml b/mkdocs.yml new file mode 100644 index 00000000..8b489ce7 --- /dev/null +++ b/mkdocs.yml @@ -0,0 +1,80 @@ +site_name: fastapi-cache-stable +site_description: Drop-in FastAPI response caching with safe migration from fastapi-cache2. +repo_url: https://github.com/agustin18/fastapi-cache +repo_name: agustin18/fastapi-cache +edit_uri: edit/stable/site_docs/ +docs_dir: site_docs +site_dir: site +use_directory_urls: true + +nav: + - Overview: index.md + - Get started: + - Install from scratch: getting-started.md + - Migrate from fastapi-cache2: migration.md + - Choose a backend: backends.md + - Guides: + - Redis standalone: guides/redis.md + - InMemory: guides/inmemory.md + - Privacy and tenant safety: guides/privacy.md + - Troubleshooting: guides/troubleshooting.md + - Reference: + - Capabilities: reference/features.md + - Compatibility: reference/compatibility.md + - Version history: reference/releases.md + - Roadmap: roadmap.md + +theme: + name: material + variant: modern + language: en + font: false + icon: + logo: material/database-check-outline + repo: fontawesome/brands/github + features: + - navigation.tabs + - navigation.sections + - navigation.top + - navigation.tracking + - content.code.copy + - content.tabs.link + - search.suggest + - search.highlight + palette: + - media: "(prefers-color-scheme: light)" + scheme: default + primary: blue + accent: teal + toggle: + icon: material/brightness-7 + name: Switch to dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + primary: blue + accent: teal + toggle: + icon: material/brightness-4 + name: Switch to light mode + +plugins: + - search + +markdown_extensions: + - admonition + - attr_list + - md_in_html + - pymdownx.details + - pymdownx.superfences + - pymdownx.tabbed: + alternate_style: true + - toc: + permalink: true + +extra_css: + - assets/stylesheets/extra.css +extra: + social: + - icon: fontawesome/brands/github + link: https://github.com/agustin18/fastapi-cache +copyright: Apache-2.0 · Community-maintained, independent from upstream. From a268453d0a9e4daceb05854ca0504846fb816702 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:21:13 -0300 Subject: [PATCH 02/27] docs(site): polished 0.5.0 discovery, installation and migration landing (#48) --- site_docs/index.md | 79 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 site_docs/index.md diff --git a/site_docs/index.md b/site_docs/index.md new file mode 100644 index 00000000..b470ad30 --- /dev/null +++ b/site_docs/index.md @@ -0,0 +1,79 @@ +--- +title: FastAPI caching, without the migration headache +description: Install fastapi-cache-stable or move safely from fastapi-cache2. +--- + +
FASTAPI-CACHE-STABLE · CURRENT RELEASE 0.5.0
+ +# Response caching that respects your existing FastAPI app. + +**Start with a single decorator. Keep your existing \`fastapi_cache\` imports.** Get tested Redis compatibility, safer HTTP behavior, clear migration paths, and evidence-backed releases. + +
+[Start from scratch](getting-started.md){ .md-button .md-button--primary } +[Migrate from fastapi-cache2](migration.md){ .md-button } +
+ +
+ +- :material-rocket-launch-outline: **Build something new** + + --- + + Install a pinned package, run an InMemory example, see real HIT/MISS headers. + + [Installation & first request](getting-started.md) + +- :material-swap-horizontal: **Already using fastapi-cache2?** + + --- + + Keep most imports and decorators; review the intentional privacy changes and clean rollback. + + [Step-by-step migration](migration.md) + +- :material-database-outline: **Choose your backend** + + --- + + InMemory for a single worker, or standalone Redis to share entries across workers. + + [Compare backends](backends.md) + +- :material-shield-check-outline: **Protect private responses** + + --- + + Authenticated requests bypass by default. Header variation is explicit, not automatic tenant isolation. + + [Security boundaries](guides/privacy.md) + +
+ +## Install the published version + +\`\`\`console +python -m pip install "fastapi-cache-stable==0.5.0" uvicorn +python -m pip check +\`\`\` + +The package name is **\`fastapi-cache-stable\`**; imports remain **\`fastapi_cache\`**. Use \`fastapi-cache-stable[redis]==0.5.0\` for standalone Redis. + +!!! warning "Do not install both packages" + \`fastapi-cache2\` and \`fastapi-cache-stable\` own the same Python package files. \`pip check\` will **not** detect this collision. Uninstall the old distribution in a clean environment before migrating. + +## What ships today? + +| Included in published 0.5.0 | Future / not shipped | +|---|---| +| Default-key-compatible GET/JSON caching | Optional bounded InMemory (#54) | +| Standalone Redis and process-local InMemory | Typed cache lifecycle events (#50) | +| Safe default Authorization/Cookie bypass | Arbitrary hidden tenant/context autodetection (#53 residual) | +| Opt-in \`vary_headers\`, ETag and HTTP 304 | Single-flight and tag-based invalidation | +| Python 3.8–3.13 functional compatibility | Python 3.14 certification | + +**Security-maintained target:** server-side CPython **3.11–3.13**. Python 3.8–3.10 are legacy **functional migration** targets, not security-supported runtimes. DynamoDB and Memcached remain experimental. + +
+**Release evidence:** [0.5.0 provenance](reference/releases.md) · **Next work:** [0.6.0 roadmap](roadmap.md) · **Source:** [GitHub](https://github.com/agustin18/fastapi-cache) +
From 1aac4ade91b8f589202868bae8ba726d11e7e86c Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:21:16 -0300 Subject: [PATCH 03/27] docs(site): polished 0.5.0 discovery, installation and migration landing (#48) --- site_docs/assets/stylesheets/extra.css | 64 ++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 site_docs/assets/stylesheets/extra.css diff --git a/site_docs/assets/stylesheets/extra.css b/site_docs/assets/stylesheets/extra.css new file mode 100644 index 00000000..abeeb419 --- /dev/null +++ b/site_docs/assets/stylesheets/extra.css @@ -0,0 +1,64 @@ +:root { + --fc-accent: #0f9f92; + --fc-accent-soft: rgba(15, 159, 146, .10); + --fc-ink: #14283f; +} +.md-typeset .landing-kicker { + color: var(--fc-accent); + font-size: .73rem; + font-weight: 800; + letter-spacing: .13em; + margin: 1.9rem 0 .75rem; +} +.md-typeset h1 { + font-weight: 770; + letter-spacing: -.04em; + line-height: 1.17; +} +.md-typeset .landing-actions { + display: flex; + gap: .65rem; + flex-wrap: wrap; + margin: 1.8rem 0 2rem; +} +.md-typeset .landing-actions .md-button { + border-radius: .6rem; + padding: .7rem 1.1rem; + font-weight: 700; +} +.md-typeset .grid.cards > ul > li { + border-radius: .9rem; + border: 1px solid var(--md-default-fg-color--lightest); + box-shadow: 0 7px 26px rgba(13, 36, 60, .035); + transition: border-color .2s ease, box-shadow .2s ease, transform .2s ease; +} +.md-typeset .grid.cards > ul > li:hover { + border-color: var(--fc-accent); + box-shadow: 0 12px 30px rgba(13, 36, 60, .08); + transform: translateY(-2px); +} +.md-typeset .grid.cards .twemoji, +.md-typeset .grid.cards .emojione { + color: var(--fc-accent); +} +.md-typeset .landing-rail { + margin-top: 2.2rem; + border-left: 3px solid var(--fc-accent); + border-radius: 0 .5rem .5rem 0; + background: var(--fc-accent-soft); + padding: .85rem 1rem; + font-size: .88rem; +} +[data-md-color-scheme="slate"] { + --fc-accent: #4fdbca; + --fc-accent-soft: rgba(79, 219, 202, .09); +} +@media (prefers-reduced-motion: reduce) { + .md-typeset .grid.cards > ul > li { + transition: none; + } +} +@media (max-width: 44rem) { + .md-typeset .landing-actions { flex-direction: column; } + .md-typeset .landing-actions .md-button { text-align: center; } +} From 2102e919e5f20a7ee30febdb9471d6b289dcfb39 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:21:18 -0300 Subject: [PATCH 04/27] docs(site): polished 0.5.0 discovery, installation and migration landing (#48) --- site_docs/getting-started.md | 93 ++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 site_docs/getting-started.md diff --git a/site_docs/getting-started.md b/site_docs/getting-started.md new file mode 100644 index 00000000..0bb521ec --- /dev/null +++ b/site_docs/getting-started.md @@ -0,0 +1,93 @@ +# Install from scratch + +Get from zero to a working FastAPI cache in five minutes. The examples use **published fastapi-cache-stable 0.5.0**. + +!!! tip "Which Python?" + Use server-side **Python 3.11–3.13** for the project's security-supported test profiles. Python 3.8–3.10 work as legacy functional migration bridges; **3.14 is not supported** by 0.5.0. + +## 1. Create a virtual environment + +=== "Linux / macOS" + + \`\`\`console + python3 -m venv .venv + source .venv/bin/activate + python -m pip install "fastapi-cache-stable==0.5.0" uvicorn + python -m pip check + \`\`\` + +=== "Windows PowerShell" + + \`\`\`powershell + py -3 -m venv .venv + .\.venv\Scripts\Activate.ps1 + python -m pip install "fastapi-cache-stable==0.5.0" uvicorn + python -m pip check + \`\`\` + +!!! danger "Package collision" + If you already use \`fastapi-cache2\`, **follow the [migration steps](migration.md)**. Do not install both distributions in the same environment; they provide the same \`fastapi_cache\` module. + +## 2. Create app.py + +\`\`\`python +from contextlib import asynccontextmanager +from typing import AsyncIterator + +from fastapi import FastAPI + +from fastapi_cache import FastAPICache +from fastapi_cache.backends.inmemory import InMemoryBackend +from fastapi_cache.decorator import cache + + +@asynccontextmanager +async def lifespan(_: FastAPI) -> AsyncIterator[None]: + FastAPICache.init(InMemoryBackend(), prefix="my-app") + try: + yield + finally: + FastAPICache.reset() + + +app = FastAPI(lifespan=lifespan) + + +@app.get("/hello") +@cache(expire=60) +async def hello(): + return {"message": "Hello from the cache!"} +\`\`\` + +The order is important: \`@app.get\` belongs **above** \`@cache\`. + +## 3. Run the server + +\`\`\`console +python -m uvicorn app:app --port 8000 +\`\`\` + +In a second terminal: + +\`\`\`console +curl -i http://127.0.0.1:8000/hello +curl -i http://127.0.0.1:8000/hello +\`\`\` + +The first response has \`X-FastAPI-Cache: MISS\`; the second identical request within 60 seconds has **\`HIT\`**. Add \`If-None-Match\` using the ETag value to test a conditional 304. + +## 4. Choose where data lives + +| Situation | Use | +|---|---| +| Local development / one process | [InMemoryBackend](guides/inmemory.md) | +| Several workers / processes | [RedisBackend](guides/redis.md) | +| DynamoDB or Memcached | Experimental: read [compatibility](reference/compatibility.md) first | + +The 0.5.0 InMemory backend has **no entry-count limit**. A future, opt-in bounded mode is being reviewed under [#54](https://github.com/agustin18/fastapi-cache/issues/54). + +## 5. Before production + +Review [private-response safety](guides/privacy.md), [compatibility](reference/compatibility.md), and use the exact released package version in your application lockfile. \`FastAPICache.reset()\` resets the configuration, **not** backend data or Redis connections. + +**Next:** [Configure Redis](guides/redis.md) · [Features](reference/features.md) From 12e894fc252753606288f4a9f843ec055d023957 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:21:20 -0300 Subject: [PATCH 05/27] docs(site): polished 0.5.0 discovery, installation and migration landing (#48) --- site_docs/migration.md | 80 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 site_docs/migration.md diff --git a/site_docs/migration.md b/site_docs/migration.md new file mode 100644 index 00000000..fb223c7b --- /dev/null +++ b/site_docs/migration.md @@ -0,0 +1,80 @@ +# Migrate from fastapi-cache2 + +For common GET/JSON endpoints backed by standalone Redis or InMemory, **0.5.0 keeps the \`fastapi_cache\` import and legacy default key builder**, but it intentionally corrects unsafe caching behavior. + +
+- :material-check-circle-outline: **Likely simple** + + --- + + Anonymous GET/JSON with one lifespan initialization and the standard Redis/InMemory backend. + +- :material-alert-circle-outline: **Needs review** + + --- + + Custom auth, private responses, special coders, existing private Redis data, shared namespaces or multiple \`init()\` calls. +
+ +## Before you change anything + +- [ ] Record your installed \`fastapi-cache2\` version and Redis client version. +- [ ] Inventory all \`@cache\` endpoints that depend on tenant, user, locale, headers, permissions, cookies or middleware state. +- [ ] Record namespaces, custom key builders and coders, and every \`clear()\` call. +- [ ] Back up **application data**, identify affected cache prefixes, and decide how to remove unsafe legacy entries **selectively**. +- [ ] Verify a rollback route that does **not** restore the old authenticated-response caching behavior. + +## Install the replacement safely + +In a clean environment: + +\`\`\`console +python -m pip uninstall -y fastapi-cache2 +python -m pip install "fastapi-cache-stable[redis]==0.5.0" +python -m pip check +python -c "from importlib.metadata import version; print(version('fastapi-cache-stable'))" +\`\`\` + +Update **your application's** dependency declaration/lockfile: uninstalling locally does not stop the old distribution from coming back on a deployment. + +!!! warning "Do not co-install" + Both distributions own \`fastapi_cache\`. \`pip check\` cannot detect overwritten module files. Use separate fresh environments for comparisons or rollback tests. + +## Keep your normal imports + +\`\`\`python +from fastapi_cache import FastAPICache +from fastapi_cache.backends.redis import RedisBackend +from fastapi_cache.decorator import cache +\`\`\` + +## Intentional behavior changes + +| Area | What to check in 0.5.0 | +|---|---| +| Authentication | Authorization/Cookie requests bypass the default cache; do not opt into private caching without complete identity/permission keys | +| Keys | Default builder's ordinary GET/JSON keys stay compatible; generated/factory route handlers are isolated since 0.4.1 | +| Request/headers | Explicit \`Request\` + default builder bypasses; hidden context is **not** automatically keyed | +| Headers | 0.5.0 offers opt-in \`vary_headers\` for listed **public** header dimensions | +| \`init()\` | A second call raises unless deliberately using \`force=True\`; clean up owned clients at lifespan teardown | +| \`clear()\` | Per-key/namespace invalidation is narrower and safer; do not expect a global Redis flush | +| Response models | Default JSON decoder preserves legacy dict/list shape; typed restoration is opt-in | +| Redis | Redis-py 4.x stays available; newer versions have Python-dependent requirements | + +!!! danger "Hidden identity is not automatically safe" + Headers like \`X-API-Key\`, tenant identity in \`request.state\`, middleware or \`ContextVar\` may not affect the default key. HTTP \`Vary\` alone does not partition the internal cache. See [privacy](guides/privacy.md) and [#53 residual](https://github.com/agustin18/fastapi-cache/issues/53). + +## Smoke-test before traffic + +1. GET anonymously: **MISS → HIT**; include ETag/304. +2. Test distinct request/locale variants and confirm separate values. +3. Test \`Authorization\` and \`Cookie\`: private endpoints should not get a shared cache HIT. +4. Verify cache namespace \`clear()\`, TTL expiry and custom key builders. +5. Test an application restart / lifespan close without unexpected second-\`init()\` exceptions. +6. Observe that unrelated Redis data stays intact after selective cache cleanup. + +## Rollback: deliberately narrow + +The release's isolated legacy rollback proved **ordinary compatible entries**, not that reverting to \`fastapi-cache2==0.2.2\` is safe for private traffic. The older package lacks the newer default authenticated-cache bypass. If you must roll back, disable unsafe private caching and rotate affected namespaces first, then reinstall the pinned previous distribution in a **fresh environment**. + +**More detail:** [Full migration contract](https://github.com/agustin18/fastapi-cache/blob/stable/MIGRATION.md) · [Release-tested wheel/sdist evidence](reference/releases.md) From 861bb95459b65ef6b414ed93aa0982928e1dc687 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:22:01 -0300 Subject: [PATCH 06/27] docs(site): backend choice, Redis, InMemory, privacy and troubleshooting (#48) --- site_docs/backends.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 site_docs/backends.md diff --git a/site_docs/backends.md b/site_docs/backends.md new file mode 100644 index 00000000..a7a15eae --- /dev/null +++ b/site_docs/backends.md @@ -0,0 +1,35 @@ +# Choose your backend + +Pick based on where your FastAPI workers run. The backend affects operational behavior; it does **not** decide which user or tenant is entitled to see a cached result. + +| | InMemory | Redis standalone | +|---|---|---| +| Setup | No external service | Running Redis server required | +| Shared across processes? | No | Yes | +| Persistent across worker restart? | No | Redis configuration-dependent | +| Production multiworker use | No shared cache | Recommended path | +| Published 0.5.0 capacity bound | No | Configure Redis eviction separately | +| Cache expiry | TTL / optional no-expiry | Redis TTL | +| Scoped namespace clearing | Yes | Yes for supported standalone mode | +| Recommended for | Dev, tests, single worker | Servers with multiple workers | + +
+- :material-laptop: **Simple app** + + --- + + [Use InMemory](guides/inmemory.md) to begin without external dependencies. + +- :material-server-network: **More than one worker** + + --- + + [Use Redis](guides/redis.md) when workers must share cached entries. +
+ +!!! warning "Unsupported is not the same as experimental" + Redis Cluster **namespace-wide clearing** is unsupported; TLS, Sentinel, failover and managed transport environments are not certified. Memcached/DynamoDB remain **experimental** and have narrower invalidation/TTL guarantees. See [compatibility](reference/compatibility.md). + +### Before caching any response + +Read [privacy and tenant safety](guides/privacy.md). Neither backend automatically discovers hidden identity, permission scopes or response-varying middleware inputs. From 84f25c1ae408791ccba45cf5fbbfa5094a2a9ca2 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:22:03 -0300 Subject: [PATCH 07/27] docs(site): backend choice, Redis, InMemory, privacy and troubleshooting (#48) --- site_docs/guides/inmemory.md | 37 ++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 site_docs/guides/inmemory.md diff --git a/site_docs/guides/inmemory.md b/site_docs/guides/inmemory.md new file mode 100644 index 00000000..c2767f19 --- /dev/null +++ b/site_docs/guides/inmemory.md @@ -0,0 +1,37 @@ +# InMemoryBackend + +The fastest way to try the decorator is an in-process cache. **No Redis server required.** + +## When to use it + +- Local development, tests and a single-worker service. +- Cache lifetime is tied to the Python process. +- Each `InMemoryBackend()` instance stores its own entries. A second Uvicorn worker does not see the first worker's values. + +```python +from fastapi_cache import FastAPICache +from fastapi_cache.backends.inmemory import InMemoryBackend + +FastAPICache.init(InMemoryBackend(), prefix="my-app") +``` + +Initialize this once during the application's lifespan and call `FastAPICache.reset()` during teardown. See the [full working app](../getting-started.md). + +## TTL and invalidation + +```python +await FastAPICache.clear(namespace="public") +``` + +The namespace is scoped under your configured prefix, not a command to clear every backend key. `expire=None` preserves entries until explicit clear or process exit; finite TTL entries are discarded on access after expiration. + +## Capacity limitations in published 0.5.0 + +!!! warning "Unbounded dictionary" + Published 0.5.0 has **no `max_entries` constructor argument**. Expired entries are removed lazily, which means a stream of never-revisited unique keys can grow memory. For high-cardinality traffic, use Redis and configure capacity appropriately. + +[Issue #54](https://github.com/agustin18/fastapi-cache/issues/54) is the separately reviewed proposal for an opt-in capacity limit. Do not pass `max_entries` to your published 0.5.0 application until a newer release explicitly ships it. + +## Privacy + +The storage location does not resolve identity: follow the same [tenant and header-variation review](privacy.md) that you would apply to Redis. From 97e848ae91de2c53932b678baa2fed41e1565d3b Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:22:05 -0300 Subject: [PATCH 08/27] docs(site): backend choice, Redis, InMemory, privacy and troubleshooting (#48) --- site_docs/guides/redis.md | 74 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 site_docs/guides/redis.md diff --git a/site_docs/guides/redis.md b/site_docs/guides/redis.md new file mode 100644 index 00000000..b3391b9c --- /dev/null +++ b/site_docs/guides/redis.md @@ -0,0 +1,74 @@ +# RedisBackend · standalone Redis + +Use standalone Redis when separate FastAPI workers need to share cache entries. The Redis extra is optional: basic InMemory installs do not require it. + +## Install with explicit version pins + +```console +python -m pip install "fastapi-cache-stable[redis]==0.5.0" "redis==4.6.0" uvicorn +python -m pip check +``` + +Redis-py 4.6.0 is an intentionally conservative migration example, **not** the newest supported client for all interpreters. + +## Run an example + +```python +from contextlib import asynccontextmanager +from typing import AsyncIterator + +from fastapi import FastAPI +from redis import asyncio as redis + +from fastapi_cache import FastAPICache +from fastapi_cache.backends.redis import RedisBackend +from fastapi_cache.decorator import cache + + +@asynccontextmanager +async def lifespan(_: FastAPI) -> AsyncIterator[None]: + client = redis.from_url("redis://localhost:6379/0", decode_responses=False) + FastAPICache.init(RedisBackend(client), prefix="my-fastapi-app") + try: + yield + finally: + FastAPICache.reset() + await client.close() # redis-py 4.6; newer clients support aclose() + + +app = FastAPI(lifespan=lifespan) + + +@app.get("/catalog") +@cache(expire=120, namespace="catalog") +async def catalog(): + return {"products": ["book", "lamp"]} +``` + +```console +python -m uvicorn app:app --port 8000 +curl -i http://127.0.0.1:8000/catalog +curl -i http://127.0.0.1:8000/catalog +``` + +## Binary values and client compatibility + +Keep **`decode_responses=False`**. JSON or PickleCoder values are stored as bytes; automatic text decoding can corrupt binary entries. + +| Server-side CPython | redis-py versions allowed in 0.5.0 metadata | +|---|---| +| 3.8 (legacy) | `>=4.2.0rc1,<6.2` | +| 3.9 (legacy) | `>=4.2.0rc1,<7.1` | +| 3.10–3.13 | `>=4.2.0rc1,<8.2` | + +Redis server versions and redis-py **client** versions are not interchangeable. The supported profile includes standalone Redis, tested RESP2/RESP3 with relevant clients and verified Redis implementations; **Redis Cluster namespace clear** is unsupported. + +## Operate safely + +- Set a unique prefix per app/environment and review any shared namespace before deleting entries. +- Do not use `FLUSHDB` to migrate cache entries. +- Define Redis memory and eviction policy independently; the library does not manage total Redis server capacity. +- Protect credentials/connection strings; never include secrets in keys or logging. +- Read [privacy limitations](privacy.md) before caching personalized data. + +**References:** [compatibility matrix](../reference/compatibility.md) · [migration](../migration.md). From 6479574301c0f83dcb895c350a5031dd059ffc01 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:22:08 -0300 Subject: [PATCH 09/27] docs(site): backend choice, Redis, InMemory, privacy and troubleshooting (#48) --- site_docs/guides/privacy.md | 55 +++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 site_docs/guides/privacy.md diff --git a/site_docs/guides/privacy.md b/site_docs/guides/privacy.md new file mode 100644 index 00000000..df94f702 --- /dev/null +++ b/site_docs/guides/privacy.md @@ -0,0 +1,55 @@ +# Privacy and tenant safety + +Caching can return the wrong representation if the key does not include **every input that influences the response**. This is not limited to the usual URL, query string or JSON body. + +## Safe defaults in published 0.5.0 + +- Requests with **`Authorization`** or **`Cookie`** bypass caching by default. +- An endpoint that explicitly declares `Request` and uses the default key builder bypasses, rather than guessing whether hidden request state affects its response. +- Error/private/no-store responses have additional cache-bypass safeguards; review custom coders and returned `Response` behavior. +- Opt-in `vary_headers` partitions **only the request header fields you explicitly list**. It also emits HTTP `Vary` on MISS/HIT/304. + +!!! danger "Custom authentication is not detected automatically" + `X-API-Key`, `X-Auth-Token` or a tenant ID in middleware/context variables can control a response without appearing in the default cache key. Syntactically accepting an HTTP header name is **not** the same as authenticating it. + +## Public locale example + +This route reads a public `Accept-Language` dimension in a dependency. It is safe only if no other hidden dimension affects its response. + +```python +from contextvars import ContextVar +from fastapi import Depends, Request + +locale = ContextVar("public_locale", default="en") + + +async def choose_locale(request: Request) -> None: + locale.set(request.headers.get("Accept-Language", "en")) + + +@app.get("/public-greeting", dependencies=[Depends(choose_locale)]) +@cache(expire=60, namespace="public-greeting-v1", + vary_headers=("Accept-Language",)) +async def greeting(): + return {"language": locale.get()} +``` + +`app` and `cache` are defined in the application example. `Request` is on the dependency, not the decorated endpoint. The app is responsible for limiting/normalizing allowed language values. + +## Never rely on these shortcuts + +| Shortcut | Why it fails | +|---|---| +| Send an HTTP `Vary` header alone | It does not partition the library's own internal store | +| Vary only by locale but also read tenant state | Different tenants can collide | +| Exclude `current_user` from a key | May replay private data across users | +| Vary by `X-API-Key` without validation | Does not prove user identity or permissions | +| Hash request headers | Digest is not authentication, encryption or rate limiting | + +## Protect against cardinality attacks + +A client can send many distinct values and multiply entries. Validate and canonicalize externally supplied values, enforce limits and request rate controls, keep TTLs bounded and use backend capacity controls. The future [bounded InMemory proposal](https://github.com/agustin18/fastapi-cache/issues/54) is not in 0.5.0. + +For private/tenant-sensitive caching, prefer an application-reviewed custom key builder incorporating **validated identity, permissions and all response dimensions**, or bypass caching. + +**Full contract:** [SECURITY.md](https://github.com/agustin18/fastapi-cache/blob/stable/SECURITY.md) · [#53 residual investigation](https://github.com/agustin18/fastapi-cache/issues/53). From 91ac284a23d08bb028b93187497363d8ed515a02 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:22:10 -0300 Subject: [PATCH 10/27] docs(site): backend choice, Redis, InMemory, privacy and troubleshooting (#48) --- site_docs/guides/troubleshooting.md | 31 +++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 site_docs/guides/troubleshooting.md diff --git a/site_docs/guides/troubleshooting.md b/site_docs/guides/troubleshooting.md new file mode 100644 index 00000000..2456ae7e --- /dev/null +++ b/site_docs/guides/troubleshooting.md @@ -0,0 +1,31 @@ +# Troubleshooting + +??? question "I see MISS on every request" + Check whether `FastAPICache.init()` runs once per lifespan, TTL is positive, the request carries `Authorization` or `Cookie`, or your endpoint explicitly declares `Request` with the default builder. Each InMemory instance and each worker has its own store. Dynamic parameters with unstable `repr()` can create a new key on every call. + +??? question "My Redis cache returns decoding errors" + Use `decode_responses=False`, verify the installed Redis client version against the [Python matrix](../reference/compatibility.md) and review any older serialized data or `PickleCoder` trust boundary. + +??? question "I installed the fork but imports behave strangely" + Ensure **exactly one** distribution owns the `fastapi_cache` module: + + ```console + python -m pip show fastapi-cache2 fastapi-cache-stable + python -m pip check + ``` + + A clean environment and an updated application lockfile are essential. `pip check` cannot detect the shared import collision. + +??? question "My second application startup raises RuntimeError" + The cache is process-global. Initialize once per lifespan, dispose of clients you own and use `FastAPICache.reset()` at teardown. Avoid `force=True` unless you explicitly intend to replace configuration. + +??? question "My response has the wrong tenant or language" + Treat this as a potential **data isolation issue**, not a performance glitch. Disable caching on the affected endpoint, rotate its namespace after reviewing access, inspect all hidden response dimensions and compare with [privacy guidance](privacy.md). `vary_headers` is never a generic tenant isolation policy. + +??? question "Can I clear an entire Redis Cluster?" + Redis Cluster namespace-wide `clear` is unsupported. Do not assume that standalone Redis prefix scanning applies to Cluster, Sentinel, TLS or managed failover. + +??? question "Can I use Python 3.14 or older EOL versions?" + 0.5.0 declares `>=3.8,<3.14`. Python 3.8–3.10 receive functional legacy tests only; modern security-maintained target is server-side 3.11–3.13. Python 3.14 is being evaluated under [#51](https://github.com/agustin18/fastapi-cache/issues/51). + +For a reproducible problem, open an [issue](https://github.com/agustin18/fastapi-cache/issues) with Python/FastAPI/Redis version, a minimal endpoint, expected versus actual HIT/MISS, and whether credentials or request state influence the output. **Never paste real tokens or user data.** From bfc6c79d63d4c83b4a7ef14ef22136406f05d37b Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:22:33 -0300 Subject: [PATCH 11/27] docs(site): published capability matrix, support, release evidence and next roadmap (#48) --- site_docs/reference/features.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 site_docs/reference/features.md diff --git a/site_docs/reference/features.md b/site_docs/reference/features.md new file mode 100644 index 00000000..e06b018c --- /dev/null +++ b/site_docs/reference/features.md @@ -0,0 +1,31 @@ +# What ships in 0.5.0? + +This page describes features in the **published 0.5.0 wheel and sdist**. PRs and roadmap proposals are not installed features. + +## Capabilities + +| Capability | Status | Notes | +|---|---|---| +| `fastapi_cache` drop-in import | :material-check-circle: Shipped | Import unchanged from `fastapi-cache2` | +| GET/JSON response caching | :material-check-circle: Shipped | Legacy ordinary default keys preserved | +| Per-process InMemory | :material-check-circle: Shipped | Per-instance and **unbounded** in 0.5.0 | +| Standalone Redis | :material-check-circle: Shipped | Redis-py 4.x legacy path, conditional modern versions | +| TTL and namespace/key clearing | :material-check-circle: Shipped | No global Redis `FLUSHDB` | +| ETag / conditional 304 | :material-check-circle: Shipped | HTTP response metadata on tested paths | +| Authorization/Cookie bypass | :material-check-circle: Shipped | Default behavior, not generic custom-auth detection | +| `vary_headers` | :material-check-circle: Shipped | Explicit public header variations, no tenant autodetection | +| Typed JSON restoration | :material-check-circle: Opt-in | `TypedJsonCoder`, Pydantic v2 profiles | +| InMemory capacity / LRU | :material-clock-outline: In review | [#54](https://github.com/agustin18/fastapi-cache/issues/54), **not in 0.5.0** | +| Cache event callbacks | :material-clock-outline: Proposed | [#50](https://github.com/agustin18/fastapi-cache/issues/50) | +| Argument exclusion | :material-clock-outline: Proposed | [#49](https://github.com/agustin18/fastapi-cache/issues/49), privacy design required | +| Single-flight / distributed locking | :material-flask-outline: Research | Cancellation, lease and stampede design needed | +| Tags / pattern invalidation | :material-flask-outline: Research | Cross-backend index races and TTL | +| Redis Cluster namespace clear | :material-close-circle-outline: Unsupported | Do not confuse with standalone prefix clearing | +| DynamoDB / Memcached | :material-alert-outline: Experimental | Different TTL/invalidation contracts | + +## Release traceability + +0.5.0 was tagged at commit `40c86d551b760315f3c6e99f383d6868c6294870`. See [exact artifact provenance](releases.md) for SHA-256, checks and maintenance boundaries. + +!!! info "No implicit feature flags" + The presence of a feature on `stable` after the release does **not** imply it exists in the immutable 0.5.0 package. Always check [PyPI](https://pypi.org/project/fastapi-cache-stable/0.5.0/) and the installed version. From 183e48ccbfb62dfdec83c51ec2b8b080d8fa066c Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:22:35 -0300 Subject: [PATCH 12/27] docs(site): published capability matrix, support, release evidence and next roadmap (#48) --- site_docs/reference/compatibility.md | 36 ++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 site_docs/reference/compatibility.md diff --git a/site_docs/reference/compatibility.md b/site_docs/reference/compatibility.md new file mode 100644 index 00000000..a7beec6f --- /dev/null +++ b/site_docs/reference/compatibility.md @@ -0,0 +1,36 @@ +# Compatibility & support + +## Distribution and Python + +| Item | Published 0.5.0 | +|---|---| +| Package on PyPI | [`fastapi-cache-stable==0.5.0`](https://pypi.org/project/fastapi-cache-stable/0.5.0/) | +| Python import | `fastapi_cache` | +| Requires-Python | `>=3.8,<3.14` | +| Security-maintained server-side target | CPython 3.11–3.13 | +| Legacy functional migration bridge | CPython 3.8–3.10 | +| Python 3.14 | Unsupported; no metadata claim | +| FastAPI / Pydantic | Tested across pinned legacy and modern CI profiles | + +!!! note "Functional compatibility is not a security support promise" + Python 3.8–3.10 and several historical framework versions are EOL. `pip check` verifies dependency metadata, not runtime safety or your tenant isolation. + +## Redis client requirements + +| CPython | redis-py `[redis]` constraint | +|---|---| +| 3.8 | `>=4.2.0rc1,<6.2` | +| 3.9 | `>=4.2.0rc1,<7.1` | +| 3.10–3.13 | `>=4.2.0rc1,<8.2` | + +`decode_responses=False` is required for binary payloads. Redis standalone is the primary supported deployment. Redis Cluster namespace clearing is unsupported; TLS, Sentinel, failover, managed transports are not fully certified. Memcached/DynamoDB remain experimental. + +## Migrating safely + +Anonymous GET/JSON and the default key builder have published golden migration tests. Safer auth/Request handling and selective clear can intentionally change observed behavior. + +- [From scratch](../getting-started.md) +- [Migrate existing applications](../migration.md) +- [Security/tenant context](../guides/privacy.md) +- [Full compatibility contract](https://github.com/agustin18/fastapi-cache/blob/stable/COMPATIBILITY.md) +- [Support policy](https://github.com/agustin18/fastapi-cache/blob/stable/SUPPORT.md) From 04c636efe591d9a63a6209dc2e3fce872ca5875a Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:22:38 -0300 Subject: [PATCH 13/27] docs(site): published capability matrix, support, release evidence and next roadmap (#48) --- site_docs/reference/releases.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 site_docs/reference/releases.md diff --git a/site_docs/reference/releases.md b/site_docs/reference/releases.md new file mode 100644 index 00000000..9c9e3fba --- /dev/null +++ b/site_docs/reference/releases.md @@ -0,0 +1,27 @@ +# Published releases and evidence + +Release tags are immutable reference points. The repository's `stable` branch may contain later documentation or unreleased work. + +| Release | Status | Highlights | +|---|---|---| +| [0.5.0](https://pypi.org/project/fastapi-cache-stable/0.5.0/) | Published 2026-11-21 | Opt-in `vary_headers`, strict artifact migration and security gates | +| [0.4.1](https://pypi.org/project/fastapi-cache-stable/0.4.1/) | Published 2026-11-20 | Generated/factory-route cache key isolation | +| [0.4.0](https://pypi.org/project/fastapi-cache-stable/0.4.0/) | Published 2026-11-20 | Redis-py 4–8 conditional compatibility | +| [0.3.1](https://pypi.org/project/fastapi-cache-stable/0.3.1/) | Historical | Explicit-Request/default-builder cache bypass | +| [0.3.0](https://pypi.org/project/fastapi-cache-stable/0.3.0/) | Historical | Initial stable migration line | + +## 0.5.0 provenance + +| Artifact | SHA-256 | +|---|---| +| Wheel | `7f30d074e222aaf4471d13105e1282b97d2968549bc4b727b941837272b10449` | +| Sdist | `e5dfe2fb5a16cb790e98bfb5e57377d835adc55579b0fdf1cb1d0afbf610ba0b` | + +The annotated `v0.5.0` tag points to commit `40c86d551b760315f3c6e99f383d6868c6294870`. Final release CI included 13/13 exact wheel/sdist migration/rollback jobs, 7/7 installed security profiles and a fresh authenticated Dependabot delta with 21 unchanged historical alerts. These findings are **bounded acceptance**, not claims that all vulnerabilities or consumer configurations are risk-free. + +- [Release status, hashes and workflow links](https://github.com/agustin18/fastapi-cache/blob/stable/docs/releases/RELEASE_STATUS_0.5.0.md) +- [Maintainer's signed scope decision](https://github.com/agustin18/fastapi-cache/issues/66#issuecomment-7055377740) +- [GitHub Release](https://github.com/agustin18/fastapi-cache/releases/tag/v0.5.0) +- [CHANGELOG](https://github.com/agustin18/fastapi-cache/blob/stable/CHANGELOG.md) + +The release is **not** a certification of arbitrary authenticated applications, Redis Cluster, TLS/Sentinel or private-response rollback. From 2cd6ed19e70e61a9cd714469ade09666e9516139 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:22:40 -0300 Subject: [PATCH 14/27] docs(site): published capability matrix, support, release evidence and next roadmap (#48) --- site_docs/roadmap.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 site_docs/roadmap.md diff --git a/site_docs/roadmap.md b/site_docs/roadmap.md new file mode 100644 index 00000000..c52f1993 --- /dev/null +++ b/site_docs/roadmap.md @@ -0,0 +1,25 @@ +# Roadmap: what is next? + +**0.5.0 is published.** Proposed 0.6.0 features remain unshipped until separately reviewed and released. This page is an approachable overview, not a release authorization. + +## Priorities for 0.6.0 + +| Priority | Issue | What users gain | Boundary | +|---|---|---|---| +| P0 when reproducible | [#53 — hidden identity/tenant inputs](https://github.com/agustin18/fastapi-cache/issues/53) | Correct private-response behavior | No promise of generic autodetection | +| P1 / active PR | [#54 — bounded InMemory](https://github.com/agustin18/fastapi-cache/issues/54) | Optional LRU capacity for a single process | No memory-byte or multiworker guarantee | +| P1 / proposed | [#50 — typed events](https://github.com/agustin18/fastapi-cache/issues/50) | Observe HIT/MISS/BYPASS/error safely | Opt-in; no mandatory telemetry | +| Research | Single-flight | Avoid duplicated same-key computations | Needs cancellation/race tests | +| Design first | [#49 — parameter exclusion](https://github.com/agustin18/fastapi-cache/issues/49) | Stable keys for irrelevant dependencies | No implicit removal of user/tenant/locale | +| Maintenance | [#45 DynamoDB](https://github.com/agustin18/fastapi-cache/issues/45), [#55 FIPS](https://github.com/agustin18/fastapi-cache/issues/55) | Real defect fixes | Isolated from new minor features | +| Research / docs | [#51 Python 3.14](https://github.com/agustin18/fastapi-cache/issues/51), [#48 docs](https://github.com/agustin18/fastapi-cache/issues/48) | New runtime qualification, easier adoption | No untested support claims | + +## Why these priorities? + +Our strongest promise is **a safe, low-friction migration from `fastapi-cache2`** with familiar keys and imports. We prioritize bounded memory, diagnostics and demonstrated correctness issues ahead of copying a broad caching strategy API. + +Cashews, aiocache, dogpile.cache, FastAPI-CacheX, Yolley/fastapi-cache and Redis FastAPI SDK are useful references. The [technical feature map](https://github.com/agustin18/fastapi-cache/blob/stable/ROADMAP.md#competitor-feature-map-docs-snapshot-2026-11-21) is qualitative; it is **not** an independently measured performance ranking. + +**Not planned for 0.6.0 without a separate design:** general tag invalidation, distributed locks, rate limiting, circuit breaking, a second public API. + +The full [GitHub roadmap](https://github.com/agustin18/fastapi-cache/blob/stable/ROADMAP.md) includes research, historical PRs and release evidence. [Browse issues](https://github.com/agustin18/fastapi-cache/issues). From a208c91c588886876a4a9333bf15482cc36e661e Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:23:11 -0300 Subject: [PATCH 15/27] docs(site): render Markdown code blocks and inline code without escaping (#48) --- site_docs/index.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/site_docs/index.md b/site_docs/index.md index b470ad30..b2cf6f9e 100644 --- a/site_docs/index.md +++ b/site_docs/index.md @@ -7,7 +7,7 @@ description: Install fastapi-cache-stable or move safely from fastapi-cache2. # Response caching that respects your existing FastAPI app. -**Start with a single decorator. Keep your existing \`fastapi_cache\` imports.** Get tested Redis compatibility, safer HTTP behavior, clear migration paths, and evidence-backed releases. +**Start with a single decorator. Keep your existing `fastapi_cache` imports.** Get tested Redis compatibility, safer HTTP behavior, clear migration paths, and evidence-backed releases.
[Start from scratch](getting-started.md){ .md-button .md-button--primary } @@ -52,15 +52,15 @@ description: Install fastapi-cache-stable or move safely from fastapi-cache2. ## Install the published version -\`\`\`console +```console python -m pip install "fastapi-cache-stable==0.5.0" uvicorn python -m pip check -\`\`\` +``` -The package name is **\`fastapi-cache-stable\`**; imports remain **\`fastapi_cache\`**. Use \`fastapi-cache-stable[redis]==0.5.0\` for standalone Redis. +The package name is **`fastapi-cache-stable`**; imports remain **`fastapi_cache`**. Use `fastapi-cache-stable[redis]==0.5.0` for standalone Redis. !!! warning "Do not install both packages" - \`fastapi-cache2\` and \`fastapi-cache-stable\` own the same Python package files. \`pip check\` will **not** detect this collision. Uninstall the old distribution in a clean environment before migrating. + `fastapi-cache2` and `fastapi-cache-stable` own the same Python package files. `pip check` will **not** detect this collision. Uninstall the old distribution in a clean environment before migrating. ## What ships today? @@ -69,7 +69,7 @@ The package name is **\`fastapi-cache-stable\`**; imports remain **\`fastapi_cac | Default-key-compatible GET/JSON caching | Optional bounded InMemory (#54) | | Standalone Redis and process-local InMemory | Typed cache lifecycle events (#50) | | Safe default Authorization/Cookie bypass | Arbitrary hidden tenant/context autodetection (#53 residual) | -| Opt-in \`vary_headers\`, ETag and HTTP 304 | Single-flight and tag-based invalidation | +| Opt-in `vary_headers`, ETag and HTTP 304 | Single-flight and tag-based invalidation | | Python 3.8–3.13 functional compatibility | Python 3.14 certification | **Security-maintained target:** server-side CPython **3.11–3.13**. Python 3.8–3.10 are legacy **functional migration** targets, not security-supported runtimes. DynamoDB and Memcached remain experimental. From a23a4ef4ed8cc264ab7bb6864ae3e5702349986b Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:23:14 -0300 Subject: [PATCH 16/27] docs(site): render Markdown code blocks and inline code without escaping (#48) --- site_docs/getting-started.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/site_docs/getting-started.md b/site_docs/getting-started.md index 0bb521ec..170537a3 100644 --- a/site_docs/getting-started.md +++ b/site_docs/getting-started.md @@ -9,28 +9,28 @@ Get from zero to a working FastAPI cache in five minutes. The examples use **pub === "Linux / macOS" - \`\`\`console + ```console python3 -m venv .venv source .venv/bin/activate python -m pip install "fastapi-cache-stable==0.5.0" uvicorn python -m pip check - \`\`\` + ``` === "Windows PowerShell" - \`\`\`powershell + ```powershell py -3 -m venv .venv .\.venv\Scripts\Activate.ps1 python -m pip install "fastapi-cache-stable==0.5.0" uvicorn python -m pip check - \`\`\` + ``` !!! danger "Package collision" - If you already use \`fastapi-cache2\`, **follow the [migration steps](migration.md)**. Do not install both distributions in the same environment; they provide the same \`fastapi_cache\` module. + If you already use `fastapi-cache2`, **follow the [migration steps](migration.md)**. Do not install both distributions in the same environment; they provide the same `fastapi_cache` module. ## 2. Create app.py -\`\`\`python +```python from contextlib import asynccontextmanager from typing import AsyncIterator @@ -57,24 +57,24 @@ app = FastAPI(lifespan=lifespan) @cache(expire=60) async def hello(): return {"message": "Hello from the cache!"} -\`\`\` +``` -The order is important: \`@app.get\` belongs **above** \`@cache\`. +The order is important: `@app.get` belongs **above** `@cache`. ## 3. Run the server -\`\`\`console +```console python -m uvicorn app:app --port 8000 -\`\`\` +``` In a second terminal: -\`\`\`console +```console curl -i http://127.0.0.1:8000/hello curl -i http://127.0.0.1:8000/hello -\`\`\` +``` -The first response has \`X-FastAPI-Cache: MISS\`; the second identical request within 60 seconds has **\`HIT\`**. Add \`If-None-Match\` using the ETag value to test a conditional 304. +The first response has `X-FastAPI-Cache: MISS`; the second identical request within 60 seconds has **`HIT`**. Add `If-None-Match` using the ETag value to test a conditional 304. ## 4. Choose where data lives @@ -88,6 +88,6 @@ The 0.5.0 InMemory backend has **no entry-count limit**. A future, opt-in bounde ## 5. Before production -Review [private-response safety](guides/privacy.md), [compatibility](reference/compatibility.md), and use the exact released package version in your application lockfile. \`FastAPICache.reset()\` resets the configuration, **not** backend data or Redis connections. +Review [private-response safety](guides/privacy.md), [compatibility](reference/compatibility.md), and use the exact released package version in your application lockfile. `FastAPICache.reset()` resets the configuration, **not** backend data or Redis connections. **Next:** [Configure Redis](guides/redis.md) · [Features](reference/features.md) From 94e004e2b3d80c5d30bc3079066b7980ec685f6d Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:23:16 -0300 Subject: [PATCH 17/27] docs(site): render Markdown code blocks and inline code without escaping (#48) --- site_docs/migration.md | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/site_docs/migration.md b/site_docs/migration.md index fb223c7b..ecdb9a81 100644 --- a/site_docs/migration.md +++ b/site_docs/migration.md @@ -1,6 +1,6 @@ # Migrate from fastapi-cache2 -For common GET/JSON endpoints backed by standalone Redis or InMemory, **0.5.0 keeps the \`fastapi_cache\` import and legacy default key builder**, but it intentionally corrects unsafe caching behavior. +For common GET/JSON endpoints backed by standalone Redis or InMemory, **0.5.0 keeps the `fastapi_cache` import and legacy default key builder**, but it intentionally corrects unsafe caching behavior.
- :material-check-circle-outline: **Likely simple** @@ -13,14 +13,14 @@ For common GET/JSON endpoints backed by standalone Redis or InMemory, **0.5.0 ke --- - Custom auth, private responses, special coders, existing private Redis data, shared namespaces or multiple \`init()\` calls. + Custom auth, private responses, special coders, existing private Redis data, shared namespaces or multiple `init()` calls.
## Before you change anything -- [ ] Record your installed \`fastapi-cache2\` version and Redis client version. -- [ ] Inventory all \`@cache\` endpoints that depend on tenant, user, locale, headers, permissions, cookies or middleware state. -- [ ] Record namespaces, custom key builders and coders, and every \`clear()\` call. +- [ ] Record your installed `fastapi-cache2` version and Redis client version. +- [ ] Inventory all `@cache` endpoints that depend on tenant, user, locale, headers, permissions, cookies or middleware state. +- [ ] Record namespaces, custom key builders and coders, and every `clear()` call. - [ ] Back up **application data**, identify affected cache prefixes, and decide how to remove unsafe legacy entries **selectively**. - [ ] Verify a rollback route that does **not** restore the old authenticated-response caching behavior. @@ -28,25 +28,25 @@ For common GET/JSON endpoints backed by standalone Redis or InMemory, **0.5.0 ke In a clean environment: -\`\`\`console +```console python -m pip uninstall -y fastapi-cache2 python -m pip install "fastapi-cache-stable[redis]==0.5.0" python -m pip check python -c "from importlib.metadata import version; print(version('fastapi-cache-stable'))" -\`\`\` +``` Update **your application's** dependency declaration/lockfile: uninstalling locally does not stop the old distribution from coming back on a deployment. !!! warning "Do not co-install" - Both distributions own \`fastapi_cache\`. \`pip check\` cannot detect overwritten module files. Use separate fresh environments for comparisons or rollback tests. + Both distributions own `fastapi_cache`. `pip check` cannot detect overwritten module files. Use separate fresh environments for comparisons or rollback tests. ## Keep your normal imports -\`\`\`python +```python from fastapi_cache import FastAPICache from fastapi_cache.backends.redis import RedisBackend from fastapi_cache.decorator import cache -\`\`\` +``` ## Intentional behavior changes @@ -54,27 +54,27 @@ from fastapi_cache.decorator import cache |---|---| | Authentication | Authorization/Cookie requests bypass the default cache; do not opt into private caching without complete identity/permission keys | | Keys | Default builder's ordinary GET/JSON keys stay compatible; generated/factory route handlers are isolated since 0.4.1 | -| Request/headers | Explicit \`Request\` + default builder bypasses; hidden context is **not** automatically keyed | -| Headers | 0.5.0 offers opt-in \`vary_headers\` for listed **public** header dimensions | -| \`init()\` | A second call raises unless deliberately using \`force=True\`; clean up owned clients at lifespan teardown | -| \`clear()\` | Per-key/namespace invalidation is narrower and safer; do not expect a global Redis flush | +| Request/headers | Explicit `Request` + default builder bypasses; hidden context is **not** automatically keyed | +| Headers | 0.5.0 offers opt-in `vary_headers` for listed **public** header dimensions | +| `init()` | A second call raises unless deliberately using `force=True`; clean up owned clients at lifespan teardown | +| `clear()` | Per-key/namespace invalidation is narrower and safer; do not expect a global Redis flush | | Response models | Default JSON decoder preserves legacy dict/list shape; typed restoration is opt-in | | Redis | Redis-py 4.x stays available; newer versions have Python-dependent requirements | !!! danger "Hidden identity is not automatically safe" - Headers like \`X-API-Key\`, tenant identity in \`request.state\`, middleware or \`ContextVar\` may not affect the default key. HTTP \`Vary\` alone does not partition the internal cache. See [privacy](guides/privacy.md) and [#53 residual](https://github.com/agustin18/fastapi-cache/issues/53). + Headers like `X-API-Key`, tenant identity in `request.state`, middleware or `ContextVar` may not affect the default key. HTTP `Vary` alone does not partition the internal cache. See [privacy](guides/privacy.md) and [#53 residual](https://github.com/agustin18/fastapi-cache/issues/53). ## Smoke-test before traffic 1. GET anonymously: **MISS → HIT**; include ETag/304. 2. Test distinct request/locale variants and confirm separate values. -3. Test \`Authorization\` and \`Cookie\`: private endpoints should not get a shared cache HIT. -4. Verify cache namespace \`clear()\`, TTL expiry and custom key builders. -5. Test an application restart / lifespan close without unexpected second-\`init()\` exceptions. +3. Test `Authorization` and `Cookie`: private endpoints should not get a shared cache HIT. +4. Verify cache namespace `clear()`, TTL expiry and custom key builders. +5. Test an application restart / lifespan close without unexpected second-`init()` exceptions. 6. Observe that unrelated Redis data stays intact after selective cache cleanup. ## Rollback: deliberately narrow -The release's isolated legacy rollback proved **ordinary compatible entries**, not that reverting to \`fastapi-cache2==0.2.2\` is safe for private traffic. The older package lacks the newer default authenticated-cache bypass. If you must roll back, disable unsafe private caching and rotate affected namespaces first, then reinstall the pinned previous distribution in a **fresh environment**. +The release's isolated legacy rollback proved **ordinary compatible entries**, not that reverting to `fastapi-cache2==0.2.2` is safe for private traffic. The older package lacks the newer default authenticated-cache bypass. If you must roll back, disable unsafe private caching and rotate affected namespaces first, then reinstall the pinned previous distribution in a **fresh environment**. **More detail:** [Full migration contract](https://github.com/agustin18/fastapi-cache/blob/stable/MIGRATION.md) · [Release-tested wheel/sdist evidence](reference/releases.md) From c7b6eb17c6a1b5c999547edf099eddb6058e0bb4 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:23:55 -0300 Subject: [PATCH 18/27] docs(site): add reproducible Zensical build with read-only PR preview (#48) --- docs/DOCS_SITE.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 docs/DOCS_SITE.md diff --git a/docs/DOCS_SITE.md b/docs/DOCS_SITE.md new file mode 100644 index 00000000..34faac00 --- /dev/null +++ b/docs/DOCS_SITE.md @@ -0,0 +1,39 @@ +# Documentation site development + +The authoritative published package remains **fastapi-cache-stable 0.5.0**. The sources in site_docs/ are a searchable companion to MIGRATION.md, SECURITY.md, COMPATIBILITY.md, SUPPORT.md and the release archive. + +## Preview locally + +Use a separate docs virtual environment on Python 3.11+: + +~~~console +python -m venv .venv-docs +. .venv-docs/bin/activate +python -m pip install "zensical==0.1.3" +zensical serve +~~~ + +Open http://127.0.0.1:8000/. Build the static pages: + +~~~console +zensical build +~~~ + +The generated site/ directory is not committed. The documentation tool is **not a runtime dependency** of the library. + +## PR previews + +The read-only Documentation site GitHub Actions workflow builds the site and uploads static output as a short-lived artifact. It does not publish GitHub Pages, mutate PyPI or create a deployment. A public website and true multi-version hosting require separate maintainer approval. + +Historical releases already remain navigable at [docs/releases](releases/README.md); source on stable is not immutable documentation for older wheels. + +## Authoring contract + +- Primary guides describe published behavior. Features from unmerged PRs must be visibly labeled proposed. +- Show the distribution name fastapi-cache-stable, the import fastapi_cache and Python legacy/security support boundaries accurately. +- Migration walkthroughs cover uninstalling fastapi-cache2, application lockfiles, tenant safety, targeted namespace cleanup and bounded rollback. +- Snippets declare dependencies and are runnable on the named Python/server profiles. +- Mobile navigation, readable color schemes, accessible links/contrast and reduced-motion preferences are design requirements. +- Compare release dates/hashes against [RELEASE_STATUS_0.5.0.md](releases/RELEASE_STATUS_0.5.0.md), not source version on stable. + +The site uses [Zensical](https://zensical.org/) for search, responsive navigation and a modern theme. \ No newline at end of file From 121ca7508fc7de2eaab65ab40003c94eda827057 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:23:57 -0300 Subject: [PATCH 19/27] docs(site): add reproducible Zensical build with read-only PR preview (#48) --- .github/workflows/docs-site.yml | 76 +++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 .github/workflows/docs-site.yml diff --git a/.github/workflows/docs-site.yml b/.github/workflows/docs-site.yml new file mode 100644 index 00000000..e304f237 --- /dev/null +++ b/.github/workflows/docs-site.yml @@ -0,0 +1,76 @@ +name: Documentation site + +on: + pull_request: + branches: [stable] + paths: + - "site_docs/**" + - "mkdocs.yml" + - ".github/workflows/docs-site.yml" + - "docs/QUICKSTART.md" + - "docs/DOCS_SITE.md" + - "README.md" + - "ROADMAP.md" + push: + branches: [stable] + paths: + - "site_docs/**" + - "mkdocs.yml" + - ".github/workflows/docs-site.yml" + - "docs/QUICKSTART.md" + - "docs/DOCS_SITE.md" + - "README.md" + - "ROADMAP.md" + workflow_dispatch: + +permissions: + contents: read + +jobs: + site: + name: Build, verify and preview documentation + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 + with: + python-version: "3.12" + - name: Install pinned docs tooling (not a runtime dependency) + run: | + python -m pip install --upgrade pip + python -m pip install "zensical==0.1.3" + - name: Build static site + run: zensical build + - name: Check real pages and published-version promises + run: | + python - <<'PY' + from pathlib import Path + pages = { + "home": Path("site/index.html"), + "start": Path("site/getting-started/index.html"), + "migration": Path("site/migration/index.html"), + "features": Path("site/reference/features/index.html"), + "privacy": Path("site/guides/privacy/index.html"), + } + for name, page in pages.items(): + if not page.is_file(): + raise AssertionError((name, page)) + data = page.read_text(encoding="utf-8") + assert " Date: Fri, 20 Nov 2026 23:23:59 -0300 Subject: [PATCH 20/27] docs(site): add reproducible Zensical build with read-only PR preview (#48) --- changelog.d/48.doc.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/48.doc.md diff --git a/changelog.d/48.doc.md b/changelog.d/48.doc.md new file mode 100644 index 00000000..3f81e350 --- /dev/null +++ b/changelog.d/48.doc.md @@ -0,0 +1 @@ +Create a searchable, responsive docs site with separate beginner installation and safe fastapi-cache2 migration, explicit 0.5.0 security/capability boundaries, release evidence, and read-only CI previews. Update the published 0.5.0 quickstart and separate the completed 0.5.0 release from 0.6.0 planning. From 42861d21199f1e9f8ebcf9f6e6a8a8c9aafa228f Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:24:11 -0300 Subject: [PATCH 21/27] docs(quickstart): use published 0.5.0 and distinguish shipped Vary from future capacity (#48) --- docs/QUICKSTART.md | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.md index 7a4035d1..2a61ac78 100644 --- a/docs/QUICKSTART.md +++ b/docs/QUICKSTART.md @@ -1,7 +1,7 @@ -# Quickstart — fastapi-cache-stable 0.4.1 +# Quickstart — fastapi-cache-stable 0.5.0 Five-minute example of response caching with -[`fastapi-cache-stable`](https://pypi.org/project/fastapi-cache-stable/0.4.1/). +[`fastapi-cache-stable`](https://pypi.org/project/fastapi-cache-stable/0.5.0/). The Python import remains `fastapi_cache`. ## Install @@ -12,7 +12,7 @@ environment. Create a clean virtual environment: ```sh python -m venv .venv . .venv/bin/activate -python -m pip install "fastapi-cache-stable==0.4.1" "uvicorn" +python -m pip install "fastapi-cache-stable==0.5.0" "uvicorn" python -m pip check ``` @@ -63,7 +63,7 @@ next identical request within the TTL should show `HIT`. The decorator order matters: `@app.get` is **above** `@cache`. **InMemory is per Python process**, not shared between workers; it -has no size cap in 0.4.x. Use Redis standalone when workers must +has no size cap in 0.5.0. Use Redis standalone when workers must share cached values. ## Redis standalone @@ -71,15 +71,31 @@ share cached values. First install the tested Redis client line: ```sh -python -m pip install "fastapi-cache-stable[redis]==0.4.1" +python -m pip install "fastapi-cache-stable[redis]==0.5.0" ``` Use [the complete Redis lifespan example](../README.md#quick-start) -and a **test Redis instance**. The 0.4.x compatibility matrix covers +and a **test Redis instance**. The 0.5.0 compatibility matrix covers Python-conditional redis-py 4.6–8.1 clients and Redis servers 6.2/7.0/7.4/8.0; see [COMPATIBILITY.md](../COMPATIBILITY.md) and the [Redis research evidence](../audit/redis/REDIS_CLIENT_MATRIX_RESEARCH.md). +## Header variations in 0.5.0 + +Public responses that vary on a known header can opt in with +`@cache(expire=60, vary_headers=("Accept-Language",))`. Declare +**every** representation-defining dimension and validate untrusted +header values to avoid cache flooding. An HTTP `Vary` header by +itself does not partition the library's internal store. The feature +is not automatic tenant isolation, and it does not make hidden +authentication or role state safe. See +[the privacy guide](../site_docs/guides/privacy.md) and +[#53](https://github.com/agustin18/fastapi-cache/issues/53). + +Published 0.5.0 InMemory is **unbounded per process**. The separate +[#54 proposal](https://github.com/agustin18/fastapi-cache/issues/54) +adds optional capacity only in a future release if reviewed and shipped. + ## Privacy and migration rules - Authenticated `Authorization` or `Cookie` requests **bypass** the @@ -92,7 +108,7 @@ see [COMPATIBILITY.md](../COMPATIBILITY.md) and the `Vary`, locale, tenant or custom-auth headers. Use a suitable custom key builder, or bypass caching until variation is proven safe. See [the header/Vary investigation](https://github.com/agustin18/fastapi-cache/issues/53). - **0.3.1 and 0.4.1** bypass cache reads and writes when an endpoint + **0.3.1, 0.4.1 and 0.5.0** bypass cache reads and writes when an endpoint explicitly declares `Request` and uses the default builder; endpoints with a custom, identity-aware key builder still cache. This does not make hidden middleware/context variables safe for routes that do not declare @@ -110,6 +126,7 @@ see [COMPATIBILITY.md](../COMPATIBILITY.md) and the ## Continue +- [New searchable documentation source](../site_docs/index.md) (web publishing is separate) - [Migration and rollback](../MIGRATION.md) - [Precise compatibility matrix](../COMPATIBILITY.md) - [Security limitations](../SECURITY.md) From 627fca9852b94f44076e6a7c3f0652a18c42adb0 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:24:29 -0300 Subject: [PATCH 22/27] docs(discoverability): clarify start-vs-migrate and separate 0.6.0 tracker from published release (#48) --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index 0bd6e52c..b75324e7 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,20 @@ See [compatibility & risk matrix](https://github.com/agustin18/fastapi-cache/blo [security policy](https://github.com/agustin18/fastapi-cache/blob/stable/SECURITY.md) and [legacy vulnerability explanation](https://github.com/agustin18/fastapi-cache/blob/stable/audit/security/LEGACY_SUPPORT_AND_RISKS.md). + +## Choose your path + +| I'm… | Start here | What you'll learn | +|---|---|---| +| **Starting from zero** | [Install in 5 minutes](docs/QUICKSTART.md) · [Visual guide source](site_docs/getting-started.md) | Pinned package, InMemory, first HIT/MISS, Redis | +| **Already on fastapi-cache2** | [Migration walkthrough](site_docs/migration.md) · [Full migration contract](MIGRATION.md) | Remove the old distribution, validate privacy, migrate namespaces, rollback | +| **Comparing features/backends** | [Feature matrix](site_docs/reference/features.md) · [Backend choice](site_docs/backends.md) | What's actually in 0.5.0 and what remains proposed | +| **Checking security** | [Tenant and request safety](site_docs/guides/privacy.md) · [Security policy](SECURITY.md) | Default auth bypass, custom headers, cache-key isolation | +| **Looking ahead** | [Next release plan](site_docs/roadmap.md) · [#86 tracker](https://github.com/agustin18/fastapi-cache/issues/86) | 0.6.0 candidates, not publication promises | + +**Published:** [fastapi-cache-stable 0.5.0](https://pypi.org/project/fastapi-cache-stable/0.5.0/). The new searchable site is in [site_docs/](site_docs/index.md) and has a **CI build preview**; it is not claimed to be hosted publicly until a separate deployment is approved. + + ## Introduction `fastapi-cache` is a tool to cache FastAPI endpoint and function results, with From 1b24edc1717298f9095e4f869d7a39a647765bd4 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:24:32 -0300 Subject: [PATCH 23/27] docs(discoverability): clarify start-vs-migrate and separate 0.6.0 tracker from published release (#48) --- ROADMAP.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index e668b5c6..8d5837fd 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -21,6 +21,25 @@ The primary product advantage remains conservative migration from `fastapi-cache2==0.2.2`, preserved `fastapi_cache` imports, predictable cache keys and safe default HTTP/private-response behavior. + +## 0.6.0 — planning, not a release commitment + +The active [0.6.0 tracker #86](https://github.com/agustin18/fastapi-cache/issues/86) +supersedes the **completed** [0.5.0 train #70](https://github.com/agustin18/fastapi-cache/issues/70). +The proposed first feature PR is [#85](https://github.com/agustin18/fastapi-cache/pull/85) +for opt-in bounded InMemory (#54). It is **unmerged** and not available +in the immutable published 0.5.0 wheel. A separate documentation PR +updates the [five-minute quickstart](docs/QUICKSTART.md) and adds +a [navigable site](site_docs/index.md) with CI preview; public hosting +and true versioned deployment remain independent approvals. + +0.6.0 should stay focused on optional bounded InMemory and privacy-safe +observability (#50). Single-flight is **research**, and argument filtering +(#49) requires a separate safety contract before any implementation. +Proven #53 privacy defects outrank the feature roadmap. Never inherit +0.5.0's release-specific security acceptance for a different SHA. + + ## Version strategy - **0.5.x:** current published line. Keep the published Python From 0857e5f6e51770654d860c1d13e3dea095611d8d Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:44:45 -0300 Subject: [PATCH 24/27] test(docs): validate every built HTML link and fragment offline (#48) --- scripts/check_docs_links.py | 108 ++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 scripts/check_docs_links.py diff --git a/scripts/check_docs_links.py b/scripts/check_docs_links.py new file mode 100644 index 00000000..ec4554af --- /dev/null +++ b/scripts/check_docs_links.py @@ -0,0 +1,108 @@ +"""Offline link integrity check for every page in the built documentation site. + +Validates built-site-relative links and HTML fragment targets without making +network calls. External links are deliberately out of scope (network-dependent). +""" + +import argparse +import posixpath +from html.parser import HTMLParser +from pathlib import Path +from urllib.parse import unquote, urlsplit + + +class LinkParser(HTMLParser): + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.ids = set() + self.links = [] + + def handle_starttag(self, tag, attrs) -> None: + self._collect(attrs) + + def handle_startendtag(self, tag, attrs) -> None: + self._collect(attrs) + + def _collect(self, attrs) -> None: + for name, value in attrs: + if value is None: + continue + if name in {"id", "name"}: + self.ids.add(value) + elif name == "href": + self.links.append(value) + + +def _target(source: Path, href: str, site: Path): + parts = urlsplit(href) + if parts.scheme or parts.netloc or href.startswith("//"): + return None + path = unquote(parts.path) + rel = source.relative_to(site).as_posix() + if path.startswith("/"): + target_path = path.lstrip("/") + elif path: + target_path = posixpath.join(posixpath.dirname(rel), path) + else: + target_path = rel + normalized = posixpath.normpath(target_path) + if normalized == ".." or normalized.startswith("../"): + return ("INVALID", parts.fragment) + location = site / normalized + if path.endswith("/") or not location.suffix: + location = location / "index.html" + elif location.is_dir(): + location = location / "index.html" + return (location, unquote(parts.fragment)) + + +def check_site(site: Path) -> tuple: + site = site.resolve() + pages = sorted(site.rglob("*.html")) + if not pages: + return (0, 0, ["No HTML pages found in " + str(site)]) + parsed = {} + for source in pages: + doc = LinkParser() + doc.feed(source.read_text(encoding="utf-8")) + parsed[source.resolve()] = doc + + problems = [] + checked = 0 + for source, doc in parsed.items(): + for href in doc.links: + if not href.strip(): + continue + result = _target(source, href, site) + if result is None: + continue + checked += 1 + target, fragment = result + if target == "INVALID": + problems.append(f"{source.relative_to(site)}: escapes site: {href}") + continue + if not target.is_file(): + problems.append(f"{source.relative_to(site)}: missing {href} -> {target}") + continue + if fragment and target.suffix.lower() == ".html": + if target not in parsed: + problems.append(f"{source.relative_to(site)}: HTML not parsed {href}") + elif fragment not in parsed[target].ids: + problems.append(f"{source.relative_to(site)}: missing fragment {href}") + return (len(pages), checked, problems) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--site-dir", type=Path, default=Path("site")) + args = parser.parse_args() + pages, links, errors = check_site(args.site_dir) + print(f"Documentation: {pages} pages, {links} local links verified") + if errors: + for error in errors: + print("ERROR: " + error) + raise SystemExit(f"{len(errors)} documentation link errors") + + +if __name__ == "__main__": + main() From e6de3ff3f592c3a19ca0a47e5675dc2289e4ccc7 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:44:48 -0300 Subject: [PATCH 25/27] test(docs): validate every built HTML link and fragment offline (#48) --- tests/test_docs_link_checker.py | 58 +++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 tests/test_docs_link_checker.py diff --git a/tests/test_docs_link_checker.py b/tests/test_docs_link_checker.py new file mode 100644 index 00000000..0c0146b3 --- /dev/null +++ b/tests/test_docs_link_checker.py @@ -0,0 +1,58 @@ +"""Fail-closed checks for built-site relative links and page fragments.""" + +from pathlib import Path + +from scripts.check_docs_links import check_site + + +def _page(root: Path, path: str, html: str) -> None: + target = root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(html, encoding="utf-8") + + +def test_links_check_every_html_and_anchors(tmp_path: Path) -> None: + _page( + tmp_path, + "index.html", + 'StartAnchor' + 'External', + ) + _page(tmp_path, "start/index.html", '

Ready

') + pages, links, errors = check_site(tmp_path) + assert pages == 2 + assert links == 2 + assert errors == [] + + +def test_links_detect_broken_relative_file_and_fragment(tmp_path: Path) -> None: + _page( + tmp_path, + "index.html", + 'MissingTypo', + ) + _page(tmp_path, "start/index.html", '

Ready

') + _, _, errors = check_site(tmp_path) + assert len(errors) == 2 + assert "missing/" in errors[0] + assert "missing fragment" in errors[1] + + +def test_links_block_escape_and_allow_static_assets(tmp_path: Path) -> None: + _page( + tmp_path, + "nested/index.html", + 'Escape' + 'Asset', + ) + (tmp_path / "assets").mkdir() + (tmp_path / "assets/site.css").write_text("body {}") + _, _, errors = check_site(tmp_path) + assert len(errors) == 1 + assert "escapes site" in errors[0] + + +def test_missing_site_fails(tmp_path: Path) -> None: + pages, _, errors = check_site(tmp_path) + assert pages == 0 + assert "No HTML pages" in errors[0] From b85e1ad95227c4157ebe15ec4f9d9675c961c9cd Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:45:11 -0300 Subject: [PATCH 26/27] ci(docs): fail closed on broken links across all generated site pages (#48) --- .github/workflows/docs-site.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/docs-site.yml b/.github/workflows/docs-site.yml index e304f237..d14e1805 100644 --- a/.github/workflows/docs-site.yml +++ b/.github/workflows/docs-site.yml @@ -66,6 +66,8 @@ jobs: assert "fastapi-cache-stable==0.5.0" in quickstart assert "fastapi-cache-stable==0.4.1" not in quickstart PY + - name: Validate every built HTML link, target file and page fragment + run: python scripts/check_docs_links.py --site-dir site - name: Upload preview without publishing a website if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 From f3fb5797e14c407a7353daf7f6d68802ca87740d Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 20 Nov 2026 23:48:12 -0300 Subject: [PATCH 27/27] fix(docs): annotate link parser collections for strict mypy gate (#48) --- scripts/check_docs_links.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/check_docs_links.py b/scripts/check_docs_links.py index ec4554af..87876b26 100644 --- a/scripts/check_docs_links.py +++ b/scripts/check_docs_links.py @@ -8,14 +8,15 @@ import posixpath from html.parser import HTMLParser from pathlib import Path +from typing import List, Set from urllib.parse import unquote, urlsplit class LinkParser(HTMLParser): def __init__(self) -> None: super().__init__(convert_charrefs=True) - self.ids = set() - self.links = [] + self.ids: Set[str] = set() + self.links: List[str] = [] def handle_starttag(self, tag, attrs) -> None: self._collect(attrs)