diff --git a/backend/Dockerfile b/backend/Dockerfile index 550b309..d98b641 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -37,6 +37,6 @@ USER fableuser EXPOSE 8000 HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ - CMD curl --fail --silent "http://127.0.0.1:${PORT:-8000}/api/v1/health" || exit 1 + CMD curl --fail --silent "http://127.0.0.1:${PORT:-8000}/api/v1/live" || exit 1 CMD ["sh", "-c", "exec uvicorn main:app --host 0.0.0.0 --port ${PORT:-8000}"] diff --git a/backend/api/v1/endpoints/health.py b/backend/api/v1/endpoints/health.py index 15fab0f..70ce4b3 100644 --- a/backend/api/v1/endpoints/health.py +++ b/backend/api/v1/endpoints/health.py @@ -7,6 +7,13 @@ logger = logging.getLogger(__name__) router = APIRouter() + +@router.get("/live") +def liveness_check(): + """Report process availability without waking or querying the database.""" + return {"status": "alive"} + + @router.get("/health", response_model=HealthResponse) def health_check(): conn = None diff --git a/backend/core/rate_limit.py b/backend/core/rate_limit.py index 59fed6e..7456e0a 100644 --- a/backend/core/rate_limit.py +++ b/backend/core/rate_limit.py @@ -318,6 +318,7 @@ def __init__( if isinstance(self.rate_limiter, SharedTokenBucketRateLimiter): self.rate_limiter.add_reset_hook(self.read_rate_limiter.reset) self.exempt_paths = { + "/api/v1/live", "/api/v1/health", "/docs", "/redoc", diff --git a/backend/test_health_http.py b/backend/test_health_http.py new file mode 100644 index 0000000..4f33390 --- /dev/null +++ b/backend/test_health_http.py @@ -0,0 +1,25 @@ +import os + +import pytest +from fastapi.testclient import TestClient + +os.environ.setdefault("FABLE_ENV", "test") +os.environ.setdefault("FABLE_RATE_LIMIT_ENABLED", "false") + +from api.v1.endpoints import health +from main import app + + +client = TestClient(app) + + +def test_liveness_check_does_not_query_database(monkeypatch): + def fail_if_database_is_used(): + pytest.fail("liveness check must not open a database connection") + + monkeypatch.setattr(health, "get_db", fail_if_database_is_used) + + response = client.get("/api/v1/live") + + assert response.status_code == 200 + assert response.json() == {"status": "alive"} diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index e24770e..03bc013 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -98,7 +98,7 @@ GitHub Actions runs backend tests, builds the Docker image, builds the iOS app, ## Monitoring and incident response -The image health check calls `/api/v1/health` every 30 seconds after a 20-second startup grace period. That endpoint reports API and database health; it does not confirm provider availability, SMTP delivery, backup freshness, or end-to-end iOS behavior. Check the deployed HTTPS health URL from outside the host and configure the hosting platform to alert on sustained health-check failures, repeated container restarts, and elevated 5xx responses. For OCI, use an HTTPS Health Checks monitor and a Monitoring alarm for the public API, plus the included host freshness timer for local encrypted backup age. +The image and Render health checks call `/api/v1/live`; this verifies the API process without opening a database connection. `/api/v1/health` performs an on-demand database connectivity check. Neither endpoint verifies provider availability, SMTP delivery, backup freshness, or end-to-end iOS behavior. For a low-cost external monitor, point UptimeRobot to `/api/v1/live`; use `/api/v1/health` manually when diagnosing Neon connectivity. For OCI, use an HTTPS Health Checks monitor and a Monitoring alarm for the public API, plus the included host freshness timer for local encrypted backup age. Unexpected 500 responses include an `X-Request-ID` response header. Match that ID with the server log entry, which records the method, path, exception type, and stack frames without logging the exception message or request body. Include the request ID when reporting a server error; do not include passwords, bearer tokens, reset codes, or other credentials in support messages. diff --git a/docs/RENDER_NEON_DEPLOYMENT.md b/docs/RENDER_NEON_DEPLOYMENT.md index da9a052..bb6041c 100644 --- a/docs/RENDER_NEON_DEPLOYMENT.md +++ b/docs/RENDER_NEON_DEPLOYMENT.md @@ -1,6 +1,6 @@ # Deploy Fable with Render and Neon -This deployment keeps SQLite as the local default and uses Neon PostgreSQL when `FABLE_DATABASE_BACKEND=postgres` is set. `render.yaml` defines a free Render Docker web service, uses the Render-provided port, and checks `/api/v1/health`. Neon holds persistent application data; Render's free web service filesystem is temporary and is used only for a disposable Gutenberg catalog cache. +This deployment keeps SQLite as the local default and uses Neon PostgreSQL when `FABLE_DATABASE_BACKEND=postgres` is set. `render.yaml` defines a free Render Docker web service, uses the Render-provided port, and checks `/api/v1/live`, which confirms the API process responds without querying Neon. Neon holds persistent application data; Render's free web service filesystem is temporary and is used only for a disposable Gutenberg catalog cache. `/api/v1/health` remains available for an on-demand database connectivity check. ## Free-tier limits @@ -8,6 +8,7 @@ This deployment keeps SQLite as the local default and uses Neon PostgreSQL when - Neon Free currently includes 100 compute hours and 1 GB of Postgres storage per project. Compute scales to zero after five idle minutes. If monthly limits are exhausted, Neon suspends compute until the next billing period. - Select **Free** plans in both dashboards. Do not add a payment method or upgrade a resource if a strict $0 ceiling is required. If a free quota is reached, expect service suspension rather than continued availability. - A new Neon project starts with an empty Fable schema. Existing local SQLite accounts, shelves, and authored stories are not copied automatically. The public catalog is fetched from its upstream providers. +- UptimeRobot's Free plan checks every five minutes. A monitor of `/api/v1/live` keeps Render from idling while leaving Neon free to scale to zero. Keeping one Render service awake continuously uses about 720 instance-hours per 30-day month; Render's 750 free instance-hours are shared across the workspace, so other active free services can exhaust the remaining allowance. If no payment method is on file, exceeding the free instance-hour allowance suspends free services rather than charging for extra hours. ## Create the Neon database @@ -25,6 +26,14 @@ This deployment keeps SQLite as the local default and uses Neon PostgreSQL when 6. Open `https://.onrender.com/api/v1/health`. It should report `healthy` and `database: connected`. 7. Configure the iOS Release setting `FABLE_API_BASE_URL` as `https://.onrender.com/api/v1`. +## Monitor Fable with UptimeRobot + +1. Use UptimeRobot's Free plan and add an **HTTP(s)** monitor named `Fable API`. +2. Set its URL to `https://fable-api-cbo8.onrender.com/api/v1/live` and keep the free five-minute interval. +3. Enable email notifications for your account contact and confirm the monitor reports **Up**. + +Use `/api/v1/live` for the frequent monitor. It checks that the API process can answer requests but deliberately does not connect to Neon. The `/api/v1/health` endpoint checks Neon; polling it every five minutes could keep Neon compute active and consume its free monthly compute allowance. Query it manually when you want to verify the database connection. + Render connects the public service through its proxy. The Blueprint trusts forwarded client IP headers from that proxy so per-client rate limits use the real client address. Do not expose the container directly outside Render. ## Optional settings and known limits diff --git a/render.yaml b/render.yaml index ad1aaa5..cf9ce57 100644 --- a/render.yaml +++ b/render.yaml @@ -6,7 +6,7 @@ services: region: singapore dockerfilePath: ./backend/Dockerfile dockerContext: . - healthCheckPath: /api/v1/health + healthCheckPath: /api/v1/live envVars: - key: FABLE_ENV value: production