"""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 import psycopg from fastapi import FastAPI, Request 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) # The seconds a restart takes the database away (Sentry DTF-API-9): the # request is answered "try again" instead of a 500, and only a warning is # logged (Sentry takes errors). The page retries by itself or on reload. RESTARTING = 'O servidor está reiniciando. Tente de novo em alguns segundos.' @app.exception_handler(psycopg.OperationalError) async def database_unavailable(request: Request, exc): logging.warning('Database unavailable for %s %s: %s', request.method, request.url.path, exc) return JSONResponse({'detail': RESTARTING}, status_code=503, headers={'Retry-After': '5'}) @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)