feat: sincronizar scaffold completo del shape web-backend/python
Sincroniza el scaffold canónico desde templates/web-backend-python/ del repo IDP. Reemplaza el placeholder mínimo previo (.gitea/workflows/ci.yaml, README.md, .gitignore, catalog-info.yaml) por el scaffold completo documentado en ADR-053 §3: - code/ — FastAPI app con /health (db check), /metrics, /demo estático, middleware correlation_id, settings Pydantic, db.py con SQLAlchemy - code/alembic/ — migración inicial vacía + env.py usando MIGRATION_DATABASE_URL - code/tests/ — pytest + httpx TestClient (test_health, test_demo) - helm/APP_NAME/ — chart con Deployment, Service, IngressRoute Traefik, NetworkPolicy, ServiceMonitor, Job alembic-upgrade como hook pre-upgrade,pre-install (backoffLimit: 0) - coralware-shape.yaml — manifiesto v1alpha1 del contrato del shape - claim-mariadb.yaml — AddonClaim declarativo (uso futuro ADR-052) - catalog-info.yaml — entidad Backstage actualizada - .gitea/workflows/APP_NAME-build.yaml — invoca reusable workflow ADR-038 + job helm-deploy con KUBECONFIG_TENANT_B64 Placeholders __APP_NAME__, __TIER__, __TENANT_ID__, __TENANT_ID_NODASHES__ serán sustituidos server-side por repo-provisioner cuando materialice el template para un tenant (pendiente — ADR-053 §11.5). El openspec/ del golden path NO se sincroniza al repo Gitea (gobernanza interna de Coralware). Refs: ADR-052, ADR-053, poc-nexobms.md (PoC NexoBMS Demetrio).
This commit is contained in:
115
code/app/main.py
Normal file
115
code/app/main.py
Normal file
@@ -0,0 +1,115 @@
|
||||
"""
|
||||
Aplicación FastAPI — entry point.
|
||||
|
||||
Endpoints obligatorios del shape web-backend/python (ver coralware-shape.yaml):
|
||||
- /health → liveness + readiness
|
||||
- /docs → Swagger UI (auth opcional)
|
||||
- /demo → frontend estático servido desde STATIC_DEMO_PATH
|
||||
- /metrics → Prometheus
|
||||
|
||||
Endpoints de dominio: agregar en app/routers/ y registrar en _register_routers().
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
from fastapi import Depends, FastAPI, HTTPException, Request, status
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from prometheus_client import CONTENT_TYPE_LATEST, generate_latest
|
||||
|
||||
from app.db import db_alive
|
||||
from app.settings import settings
|
||||
|
||||
logging.basicConfig(
|
||||
level=getattr(logging, settings.LOG_LEVEL, logging.INFO),
|
||||
format="%(asctime)s [%(levelname)s] [cid=%(correlation_id)s] %(message)s",
|
||||
datefmt="%Y-%m-%dT%H:%M:%SZ",
|
||||
)
|
||||
|
||||
|
||||
class CorrelationIdFilter(logging.Filter):
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
if not hasattr(record, "correlation_id"):
|
||||
record.correlation_id = "-"
|
||||
return True
|
||||
|
||||
|
||||
logging.getLogger().addFilter(CorrelationIdFilter())
|
||||
log = logging.getLogger("__APP_NAME__")
|
||||
|
||||
|
||||
def _require_auth_dep() -> None:
|
||||
"""
|
||||
Dependency placeholder para /docs cuando OPENAPI_REQUIRE_AUTH=true.
|
||||
Implementación real: validar JWT contra KEYCLOAK_ISSUER (ADR-029 R-004).
|
||||
"""
|
||||
if not settings.OPENAPI_REQUIRE_AUTH:
|
||||
return
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Auth requerido — implementar validación JWT contra Keycloak",
|
||||
)
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
app = FastAPI(
|
||||
title="__APP_NAME__",
|
||||
version="0.1.0",
|
||||
dependencies=[Depends(_require_auth_dep)] if settings.OPENAPI_REQUIRE_AUTH else [],
|
||||
)
|
||||
|
||||
@app.middleware("http")
|
||||
async def correlation_id_middleware(request: Request, call_next):
|
||||
cid = request.headers.get(settings.CORRELATION_ID_HEADER) or _generate_cid()
|
||||
request.state.correlation_id = cid
|
||||
response = await call_next(request)
|
||||
response.headers[settings.CORRELATION_ID_HEADER] = cid
|
||||
return response
|
||||
|
||||
@app.get("/health", tags=["platform"])
|
||||
async def health() -> JSONResponse:
|
||||
db_status = "up" if db_alive() else "down"
|
||||
code = 200 if db_status == "up" else 503
|
||||
return JSONResponse(
|
||||
status_code=code,
|
||||
content={"status": "ok" if code == 200 else "degraded", "db": db_status},
|
||||
)
|
||||
|
||||
@app.get("/metrics", tags=["platform"])
|
||||
async def metrics() -> Response:
|
||||
return Response(content=generate_latest(), media_type=CONTENT_TYPE_LATEST)
|
||||
|
||||
if os.path.isdir(settings.STATIC_DEMO_PATH):
|
||||
app.mount(
|
||||
"/demo",
|
||||
StaticFiles(directory=settings.STATIC_DEMO_PATH, html=True),
|
||||
name="demo",
|
||||
)
|
||||
else:
|
||||
log.warning(
|
||||
"STATIC_DEMO_PATH=%s no existe — endpoint /demo no será servido",
|
||||
settings.STATIC_DEMO_PATH,
|
||||
)
|
||||
|
||||
_register_routers(app)
|
||||
return app
|
||||
|
||||
|
||||
def _generate_cid() -> str:
|
||||
"""Genera correlation_id si el cliente no envió uno."""
|
||||
import time
|
||||
import uuid
|
||||
|
||||
return f"__APP_NAME__-{int(time.time() * 1000)}-{uuid.uuid4().hex[:8]}"
|
||||
|
||||
|
||||
def _register_routers(app: FastAPI) -> None:
|
||||
"""
|
||||
Registra los routers de dominio.
|
||||
Agrega aquí los include_router(...) conforme tu app crezca.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
app = create_app()
|
||||
Reference in New Issue
Block a user