generated from shayancoin/aieng-template-mvp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
255 lines (210 loc) · 8.97 KB
/
main.py
File metadata and controls
255 lines (210 loc) · 8.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
"""Main module for the FastAPI application."""
import logging
from contextlib import asynccontextmanager
from contextlib import nullcontext
from time import perf_counter
from typing import Dict, Optional
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, RedirectResponse
from opentelemetry import trace
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.trace import Status, StatusCode
from prometheus_fastapi_instrumentator import Instrumentator
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.base import BaseHTTPMiddleware
from api.config import Settings as _Settings, get_settings
from api.db import Base, engine
from api.instrumentation_boot import setup_instrumentation
from api.metrics import (
observe_http_request,
record_http_request,
suppress_prometheus_http_metrics,
)
from api.orders import router as orders_router
from api.routes import router as api_router
from api.exports import router as exports_router
from api.routes_catalog import router as catalog_router
from api.routes_catalog import router_mesh as catalog_mesh_router
from api.routes_designs import router as design_router
from api.routes_materials import router as materials_router
from api.routes_modules import router as modules_router
from api.routes_observability import router as observability_router
from api.routes_orders import router as orders_router
from api.routes_quote import router as pricing_router
logger = logging.getLogger(__name__)
try:
from api.routes_sync import router as sync_router
except Exception as exc: # pragma: no cover - optional dependency guard
logger.warning("Disabling Hygraph sync routes: %s", exc)
sync_router = None
from prometheus_client import CONTENT_TYPE_LATEST, generate_latest
# Initialize settings
settings = get_settings()
# Create the FastAPI app
app = FastAPI(
title="MVP API",
description="API for MVP application",
version="0.1.0",
)
# Register Prometheus instrumentation so HTTP metrics are emitted for alerts/dashboards
Instrumentator().instrument(app).expose(app, include_in_schema=False, endpoint="/metrics")
# Ensure tables exist in SQLite (dev/test); migrations still handle Postgres
if _Settings().database_url.startswith("sqlite"):
@app.on_event("startup")
async def _ensure_sqlite_tables() -> None:
Base.metadata.create_all(bind=engine)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def _resolve_route_label(request: Request) -> str:
"""
Resolve the best available route label for an incoming request.
Parameters:
request (Request): The incoming FastAPI request.
Returns:
route_label (str): The route's path template if present (e.g., "/items/{id}"), otherwise the request URL path, otherwise "unknown".
"""
route = request.scope.get("route")
if route and hasattr(route, "path") and route.path:
return route.path
return request.url.path or "unknown"
class PrometheusInstrumentationMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next): # type: ignore[override]
if request.url.path == "/metrics":
return await call_next(request)
start = perf_counter()
try:
response = await call_next(request)
except Exception:
duration = perf_counter() - start
observe_http_request(
service="backend",
route=_resolve_route_label(request),
method=request.method,
status="500",
duration_seconds=duration,
)
raise
duration = perf_counter() - start
observe_http_request(
service="backend",
route=_resolve_route_label(request),
method=request.method,
status=str(response.status_code),
duration_seconds=duration,
)
return response
app.add_middleware(PrometheusInstrumentationMiddleware)
# Include API router
app.include_router(api_router)
app.include_router(orders_router)
app.include_router(catalog_router)
app.include_router(catalog_mesh_router)
app.include_router(materials_router)
app.include_router(modules_router)
app.include_router(pricing_router)
app.include_router(exports_router)
app.include_router(design_router)
if sync_router is not None:
app.include_router(sync_router)
app.include_router(observability_router)
app.include_router(orders_router)
_http_tracer = trace.get_tracer("paform.api.http")
@app.api_route(
"/api/price/{remaining:path}",
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"],
include_in_schema=False,
)
async def redirect_legacy_price_paths(remaining: str, request: Request) -> Response:
"""Permanent redirect from legacy `/api/price/*` endpoints to `/api/v1/price/*`."""
trimmed = remaining.strip("/")
target_path = "/api/v1/price" if not trimmed else f"/api/v1/price/{trimmed}"
target_url = request.url.replace(path=target_path)
return RedirectResponse(str(target_url), status_code=308)
@app.middleware("http")
async def telemetry_middleware(request: Request, call_next):
"""
Intercepts incoming HTTP requests to create or join an OpenTelemetry span, record HTTP attributes and errors, and emit a Prometheus observation for the request duration.
The middleware uses an existing current span if present; otherwise it starts a new span named "HTTP {METHOD}". It sets span attributes (`http.method`, `deployment.environment`, `http.status_code`, and `http.route`), records exceptions and marks the span as errored for response status codes >= 500 or on raised exceptions, and always records the request duration (in milliseconds) via record_http_request.
Parameters:
request (Request): The incoming FastAPI request.
call_next (Callable): The next ASGI app/callable to invoke and obtain a Response.
Returns:
Response: The response produced by downstream handlers, or a fallback Response constructed with the captured status code if no response was produced.
"""
method = request.method.upper()
path_template = request.url.path
start = perf_counter()
current_span = trace.get_current_span()
if current_span.get_span_context().is_valid:
span_context = nullcontext(current_span)
else:
span_context = _http_tracer.start_as_current_span(f"HTTP {method}")
status_code = 500
response: Optional[Response] = None
with span_context as span:
span.set_attribute("http.method", method)
span.set_attribute("deployment.environment", settings.environment)
try:
response = await call_next(request)
status_code = response.status_code
span.set_attribute("http.status_code", status_code)
if status_code >= 500:
span.set_status(Status(StatusCode.ERROR))
except Exception as exc: # noqa: BLE001
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR))
raise
finally:
matched_route = request.scope.get("route")
path_template = getattr(matched_route, "path", path_template)
span.set_attribute("http.route", path_template)
duration_ms = (perf_counter() - start) * 1000
with suppress_prometheus_http_metrics():
record_http_request(method, path_template, status_code, duration_ms)
return response if response is not None else Response(status_code=status_code)
@app.exception_handler(RequestValidationError)
async def handle_validation_error(request: Request, exc: RequestValidationError) -> JSONResponse:
# Unified error envelope for malformed JSON / validation errors
return JSONResponse(
status_code=422,
content={
"ok": False,
"error": {
"code": "BAD_REQUEST",
"message": "invalid request",
"details": exc.errors(),
},
},
)
@app.get("/")
async def root() -> Dict[str, str]:
"""Root endpoint of the API.
Returns
-------
Dict[str, str]
A welcome message for the API.
"""
return {"message": "Welcome to the MVP API"}
@app.get("/healthcheck")
async def healthcheck() -> Dict[str, str]:
"""
Report the API health status.
Returns:
dict: A dictionary with a single key "status" set to "healthy".
"""
return {"status": "healthy"}
@app.get("/metrics")
async def metrics() -> Dict[str, str]:
"""
Compatibility endpoint for legacy Prometheus scrapes.
Returns:
dict: A dictionary with key "detail" containing an informational message that metrics are exported via OpenTelemetry OTLP and no local payload is available.
"""
return Response(content=generate_latest(), media_type=CONTENT_TYPE_LATEST)