Cut the edge over from nginx and certbot to Caddy
Test and deploy / test (push) Successful in 3m30s
Test and deploy / deploy (push) Has been cancelled

Caddy takes nginx's place in compose: ports 80/443, the fixed address
172.28.255.251 that cloudflared pins the public names to, the network
aliases, the healthcheck and the autoheal label. nginx and certbot are
removed from compose; Caddy already holds its own certificates in
./caddy/data, obtained while it ran beside nginx. `traffic` now tails
logs/caddy/payloads.log, and the dev override switches Caddy to its dev
sites instead of putting nginx in DEV_MODE.

Docs and comments that described nginx's behaviour now describe Caddy's:
CLAUDE.md, DEPLOYMENT.md (topology, boot paths, TLS, rate limits, runbook
with a rollback, rough edges), the READMEs, .env.example and the comments
in the backend, Python service, Vue source and infra files. nginx/ and
certbot/ stay in the repo as the rollback until this has settled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-17 23:28:28 +00:00
co-authored by Claude Opus 5.5
parent e09b90afaa
commit daa2a465fb
54 changed files with 547 additions and 655 deletions
+2 -2
View File
@@ -11,7 +11,7 @@
# immediately instead of sitting in a buffer — both are standard for
# containerised Python and the second one matters for debugging.
#
# ROOT_PATH=/py: nginx proxies /py/ and STRIPS the prefix, so the app's routes
# ROOT_PATH=/py: Caddy proxies /py/ and STRIPS the prefix, so the app's routes
# are written relative to /. --root-path tells FastAPI it is nonetheless
# mounted under a prefix, so the OpenAPI schema and Swagger UI emit correct
# /py/... URLs. Without it, /py/docs loads but cannot call anything.
@@ -21,7 +21,7 @@
# Both have defaults here so the image runs standalone; docker compose normally
# supplies them.
#
# EXPOSE 8000 is documentation only — the port is not published; nginx reaches
# EXPOSE 8000 is documentation only — the port is not published; Caddy reaches
# it over app-network.
# =============================================================================
FROM python:3.12-slim
+15 -12
View File
@@ -26,7 +26,7 @@ driven from a plain script.
## Endpoints
Paths below are as the service sees them; from a browser prefix everything with
`/py` (see *Behind nginx*).
`/py` (see *Behind Caddy*).
| Method | Path | What it does |
| --- | --- | --- |
@@ -72,9 +72,9 @@ can't be shared), and identical requests are cached for 10 minutes.
Routes under `/internal/` (today only the rowing reader) are the only ones in
this service that are **not public**. Each spends a paid Claude call and has no
auth of its own — the admin check happens in the Go backend, which calls the container
directly (`http://python:8000/...`). Two things keep them internal: nginx
directly (`http://python:8000/...`). Two things keep them internal: Caddy
answers `/py/internal/` with a 404, and the route itself 404s any request
carrying the `X-Real-IP` / `X-Forwarded-For` headers nginx adds to everything
carrying the `X-Real-IP` / `X-Forwarded-For` headers Caddy adds to everything
it proxies (the Go backend sends neither).
Their plumbing is in two places, shared by any route added later:
@@ -127,7 +127,7 @@ they see this service's error rather than their own.
in `main.py`'s docstring and bump the FastAPI `version`.
3. **Tests** `tests/test_<thing>.py`, copied from `test_rowing.py`: fake the
client with `monkeypatch.setattr(thing, "_client", ...)`.
4. **Docs**: the endpoint table and a section here. Nothing to do in nginx —
4. **Docs**: the endpoint table and a section here. Nothing to do in Caddy —
it already 404s everything under `/py/internal/`.
If third-party text goes into the prompt (a web page, an email), say in the
@@ -149,19 +149,22 @@ Errors: 502 with a fixed `detail` (`failed to process image`, `empty response
from image processor`, `failed to parse image data`) that the Go handler
relays to the admin; 503 if `CLAUDE_API_KEY` is unset.
## Behind nginx
## Behind Caddy
`nginx/nginx.conf.template` proxies `/py/` to this container and **strips the
`caddy/routes.caddy` proxies `/py/` to this container and **strips the
prefix**, so routes here are written relative to `/`. `--root-path /py` (set on
the uvicorn command line via `ROOT_PATH`) is what keeps the generated docs and
OpenAPI URLs correct behind that rewrite.
The hotel routes get their own nginx location with `proxy_buffering off` and a
300s read timeout, because otherwise nginx would hold the whole NDJSON stream
until it finished. The app also sends `X-Accel-Buffering: no` as a belt-and-
braces version of the same thing. The internal deadlines in `travelodge.py`
(200s for a search, 240s for a scan) exist to finish *before* that 300s cut, and
return partial results with `summary.truncated = true` instead of dying.
The hotel routes get their own Caddy route with `flush_interval -1` and their
own rate limit, so each NDJSON line reaches the browser as it is written. The
app also sends `X-Accel-Buffering: no`, which Caddy ignores but an nginx-style
proxy would need. The internal deadlines in `travelodge.py` (200s for a search,
240s for a scan) were set to finish before nginx's old 300s cut; Caddy sets no
upstream timeout, but they still bound a run and return partial results with
`summary.truncated = true` instead of dying. Through the tunnel, Cloudflare
gives up on an origin that sends nothing for 100s, which the streaming routes
avoid by writing progress lines.
Env vars (from `docker-compose.yml`): `PYTHON_PORT`, `ROOT_PATH`, the optional
`TFL_APP_KEY` (see below), and `CLAUDE_API_KEY` and `CLAUDE_MODEL` for the internal Claude route. Dev mode mounts `python/app` and runs
+19 -14
View File
@@ -1,6 +1,6 @@
"""Small Python API service.
Nginx proxies https://www.<DOMAIN>/py/... to this container and strips the
Caddy proxies https://www.<DOMAIN>/py/... to this container and strips the
/py prefix, so routes here are defined relative to "/". FastAPI's root_path
(set via --root-path on the uvicorn command line) keeps the generated docs
at /py/docs working behind the proxy.
@@ -14,7 +14,7 @@ Endpoints
POST /hotels/search/stream same search, streamed as NDJSON
POST /hotels/scan/stream cheapest-night-in-a-range scan, NDJSON
POST /internal/rowing/read read a rowing display photo with Claude
(Go backend only - not reachable through nginx)
(Go backend only - not reachable through Caddy)
All the hotel work lives in `travelodge`; this module is the HTTP skin around
it - request validation, a response cache, the one-search-at-a-time guard, and
@@ -62,7 +62,7 @@ class Greeting(BaseModel):
@app.get("/", response_model=Greeting, summary="Service index")
def index() -> Greeting:
"""Point a curious caller at the docs (which live at /py/docs via nginx)."""
"""Point a curious caller at the docs (which live at /py/docs via Caddy)."""
return Greeting(message="Python API is running. See /py/docs for the schema.")
@@ -558,10 +558,13 @@ def _ndjson(events) -> StreamingResponse:
line, with no event-type framing to strip. `exclude_none=True` keeps the
lines small, so absent keys must be treated as null by the reader.
X-Accel-Buffering: no is essential - without it nginx buffers the whole
response and the user sees nothing until the search finishes, defeating the
point of streaming. Cache-Control: no-cache stops any intermediary storing
a partial stream.
X-Accel-Buffering: no tells an nginx-style proxy not to buffer the
response; without it the user would see nothing until the search finished,
defeating the point of streaming. Caddy, the edge now, ignores the header
and passes a chunked response on as it is written (its /py/hotels route
also sets flush_interval -1), so the header is insurance for whatever
proxy might sit here next. Cache-Control: no-cache stops any intermediary
storing a partial stream.
"""
return StreamingResponse(
(ev.model_dump_json(exclude_none=True) + "\n" for ev in events),
@@ -651,7 +654,7 @@ def hotel_scan_stream(req: HotelScanRequest) -> StreamingResponse:
# Internal: the routes the Go backend calls
# --------------------------------------------------------------------------- #
def _internal_only(request: Request) -> None:
"""Refuse a request that arrived through nginx.
"""Refuse a request that arrived through the edge proxy (Caddy).
Every other route in this service is public, but the internal ones spend
a paid Claude call per request and have no auth of their own - the admin
@@ -659,10 +662,12 @@ def _internal_only(request: Request) -> None:
directly over app-network. Two layers keep the outside world off it,
because either alone is one config edit away from being lost:
1. nginx answers /py/internal/ with a 404 (both templates).
2. nginx stamps X-Real-IP and X-Forwarded-For on everything it proxies
here, and a client cannot make it omit them; the Go backend sends
neither. So their presence means the request came from outside.
1. Caddy answers /py/internal/ with a 404 (caddy/routes.caddy, dev and
production alike).
2. Caddy stamps X-Real-IP and X-Forwarded-For on everything it proxies
here (the `proxy` snippet), and a client cannot make it omit them;
the Go backend sends neither. So their presence means the request
came from outside.
404 rather than 403, so the route is indistinguishable from one that does
not exist.
@@ -732,7 +737,7 @@ class RowingReadRequest(BaseModel):
response_model=rowing.RowingReading,
summary="Read time and distance off a rowing machine display",
description=(
"Internal to the Go backend's admin-only `POST /api/rowing`; not reachable through nginx. "
"Internal to the Go backend's admin-only `POST /api/rowing`; not reachable through Caddy. "
"Sends the image to Claude and returns the three numbers it read. No plausibility checking "
"happens here - the caller owns the sanity bounds."
),
@@ -743,7 +748,7 @@ def rowing_read(req: RowingReadRequest) -> rowing.RowingReading:
A plain `def`, so FastAPI runs it in the threadpool and the blocking Claude
call does not stall the event loop the hotel streams are served from.
Responds 404 (came through nginx), 503 (no API key) or 502 (Claude failed
Responds 404 (came through Caddy), 503 (no API key) or 502 (Claude failed
or returned something unparseable) by way of `_internal_claude_route`. The
502 detail is one of rowing.read_display's fixed messages, which the Go
handler passes on to the admin verbatim.
+6 -3
View File
@@ -55,7 +55,9 @@ Time budgets
Every network path takes an optional `deadline` (a time.monotonic() value).
Passing it down instead of using a wall-clock timeout lets a long run degrade
gracefully: work already done is returned with summary["truncated"] = True
instead of the whole request dying at the nginx 300s proxy timeout.
instead of the whole request being cut off by a proxy timeout. (nginx cut at
300s; Caddy sets no upstream timeout, but the budgets below still bound a
run, and Cloudflare gives up on an origin that sends nothing for 100s.)
"""
import logging
@@ -102,8 +104,9 @@ ORIGINS = {
# Rough Greater London bounding box for custom "lat,lon" origins.
LONDON_BOX = (51.25, 51.75, -0.55, 0.35) # min lat, max lat, min lon, max lon
# Wall-clock budget for one run_search call. Nginx cuts the connection at
# 300s, so stop pricing transport well before that and return what we have.
# Wall-clock budget for one run_search call. Set when nginx cut the connection
# at 300s: stop pricing transport well before that and return what we have.
# Caddy has no such cut, but the budget still keeps a run bounded.
SEARCH_DEADLINE_S = 200
# A date-range scan fetches one Travelodge search per candidate night, then
+3 -3
View File
@@ -3,7 +3,7 @@
The Vue frontend splits the response on newlines and JSON-parses each line, so
the contract under test is: one complete JSON object per line, the documented
event names, the right payload key per event kind, `exclude_none` dropping
absent keys, and the framing headers that stop nginx buffering the stream.
absent keys, and the framing headers that stop a buffering proxy holding the stream.
No scraping and no network happens here: `_run_events` takes the upstream
generator as a callable, so a fake generator stands in for travelodge and the
@@ -134,8 +134,8 @@ def test_ndjson_omits_none_fields():
def test_ndjson_headers_defeat_proxy_buffering():
response = main._ndjson(iter([]))
assert response.media_type == "application/x-ndjson"
# Without X-Accel-Buffering nginx holds the whole response and the stream
# is pointless.
# Without X-Accel-Buffering an nginx-style proxy holds the whole response
# and the stream is pointless. (Caddy streams it regardless.)
assert response.headers["x-accel-buffering"] == "no"
assert response.headers["cache-control"] == "no-cache"
+2 -2
View File
@@ -125,8 +125,8 @@ def test_route_returns_reading(fake_claude, http):
@pytest.mark.parametrize("header", ["X-Real-IP", "X-Forwarded-For"])
def test_route_refuses_requests_proxied_by_nginx(fake_claude, http, header):
"""nginx sets these on everything it forwards; the Go backend sets neither."""
def test_route_refuses_requests_proxied_by_the_edge(fake_claude, http, header):
"""Caddy sets these on everything it forwards; the Go backend sets neither."""
res = http.post("/internal/rowing/read", json=BODY, headers={header: "203.0.113.9"})
assert res.status_code == 404
assert fake_claude.calls == []