Files
dtf-system/app/app.py
Cauê Faleiros 445d686f43 fix: a redeploy's short database outage no longer takes the API down
Sentry DTF-API-2..7 (redeploy of 5a7fc0f, 13/11): the name db did not
resolve for about 12 s; the new API exited at startup and the worker and
audit() logged the error every second. The API now waits up to 90 s with
a backoff, the worker reports an outage once and backs off to 15 s, the
audit persistence error is logged at most once a minute, and api, site
and kanban update start-first so the old container serves meanwhile.

Built by Bobina.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-13 15:25:29 -03:00

75 lines
3.0 KiB
Python

"""The DTF Portal/API service: assembly only.
Configuration and shared helpers are in local.runtime; every route lives in a
router under local.api. This module creates the application, applies the
cross-cutting middleware, and includes them.
"""
import asyncio
import logging
import time
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from starlette.middleware.trustedhost import TrustedHostMiddleware
from . import observability
from .core import db
from .core.auth import audit, client_ip
from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage
from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, stamps, uploads, users
observability.init('api')
RETRY_SECONDS = (1, 2, 4, 8, 15)
STARTUP_BUDGET_SECONDS = 90
@asynccontextmanager
async def lifespan(app):
# A redeploy briefly removes the database name; wait it out, warning once
# per attempt (a warning, not an error: Sentry only takes errors).
deadline = time.monotonic() + STARTUP_BUDGET_SECONDS
attempt = 0
while True:
try:
with db.connect() as c:
c.execute('SELECT 1 FROM dtf_local.operator_sessions LIMIT 1')
storage.health()
break
except Exception:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise
delay = min(RETRY_SECONDS[min(attempt, len(RETRY_SECONDS) - 1)], remaining)
logging.warning('Database not reachable yet, retrying in %d s', max(1, round(delay)))
await asyncio.sleep(delay)
attempt += 1
yield
app = FastAPI(title='DTF Portal/API', lifespan=lifespan, docs_url=None, redoc_url=None)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=ALLOWED_HOSTS)
@app.middleware('http')
async def safe_headers(request, call_next):
if request.method not in ('GET','HEAD','OPTIONS'):
origin = request.headers.get('origin')
if request.headers.get('sec-fetch-site') == 'cross-site' or (origin and origin not in ALLOWED_ORIGINS):
audit('cross_origin_rejected', ip=client_ip(request))
return JSONResponse({'detail':'Cross-origin request rejected'}, status_code=403)
response = await call_next(request)
if response.status_code in (401,403,429) or response.status_code>=500:
audit('http_security_event', method=request.method, status=response.status_code, ip=client_ip(request))
# Nothing is cached unless a route says so (the Kanban's artwork pictures).
response.headers.setdefault('Cache-Control', 'no-store')
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['Referrer-Policy'] = 'no-referrer'
return response
# Order is not significant: no two routers declare the same path.
for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, site_admin, reviews, machine_log, stamps):
app.include_router(module.router)