-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.py
More file actions
138 lines (116 loc) · 3.93 KB
/
main.py
File metadata and controls
138 lines (116 loc) · 3.93 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
"""
FlexiRoaster FastAPI Application.
Main entry point for the REST API server.
"""
from datetime import datetime
import uvicorn
from fastapi import Depends, FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, Response
from backend.api.middleware.rate_limit_middleware import RateLimitMiddleware
from backend.api.routes import airflow, executions, metrics, pipelines
from backend.api.routes.auth import router as auth_router
from backend.api.security import require_roles
from backend.config import settings
from backend.services.secrets import secret_manager
from backend.observability import observability_metrics
from backend.observability.logging import configure_logstash_logging
# Create FastAPI app
app = FastAPI(
title=settings.APP_NAME,
version=settings.APP_VERSION,
description="Production-grade pipeline automation backend with AI-powered insights",
docs_url=f"{settings.API_PREFIX}/docs",
redoc_url=f"{settings.API_PREFIX}/redoc",
openapi_url=f"{settings.API_PREFIX}/openapi.json",
)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Rate limiting middleware
app.add_middleware(RateLimitMiddleware, requests_per_minute=settings.RATE_LIMIT_PER_MINUTE)
# Request/Response logging middleware
if settings.LOG_REQUESTS:
from backend.api.middleware.logging_middleware import RequestLoggingMiddleware
app.add_middleware(RequestLoggingMiddleware)
# Optional centralized log shipping
configure_logstash_logging()
@app.on_event("startup")
async def load_runtime_secrets() -> None:
"""Load secrets from configured provider when available."""
jwt_secret = secret_manager.get("JWT_SECRET_KEY")
if jwt_secret:
settings.JWT_SECRET_KEY = jwt_secret
# Exception handlers
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
"""Global exception handler"""
return JSONResponse(
status_code=500,
content={
"error": "Internal server error",
"detail": str(exc),
"timestamp": datetime.now().isoformat(),
},
)
# Health check endpoint
@app.get("/health", tags=["health"])
async def health_check():
"""Health check endpoint"""
return {
"status": "healthy",
"app": settings.APP_NAME,
"version": settings.APP_VERSION,
"timestamp": datetime.now().isoformat(),
}
@app.get("/metrics", include_in_schema=False)
async def prometheus_metrics():
"""Prometheus scrape endpoint for infrastructure monitoring."""
payload, content_type = observability_metrics.prometheus_payload()
return Response(content=payload, media_type=content_type)
# Root endpoint
@app.get("/", tags=["root"])
async def root():
"""Root endpoint with API information"""
return {
"app": settings.APP_NAME,
"version": settings.APP_VERSION,
"docs": f"{settings.API_PREFIX}/docs",
"health": "/health",
}
# Include routers
app.include_router(auth_router, prefix=settings.API_PREFIX)
app.include_router(
pipelines.router,
prefix=settings.API_PREFIX,
dependencies=[Depends(require_roles("admin", "operator", "viewer"))],
)
app.include_router(
executions.router,
prefix=settings.API_PREFIX,
dependencies=[Depends(require_roles("admin", "operator", "viewer"))],
)
app.include_router(
metrics.router,
prefix=settings.API_PREFIX,
dependencies=[Depends(require_roles("admin", "operator", "viewer"))],
)
app.include_router(
airflow.router,
prefix=settings.API_PREFIX,
dependencies=[Depends(require_roles("admin", "operator"))],
)
# Run server
if __name__ == "__main__":
uvicorn.run(
"backend.main:app",
host=settings.HOST,
port=settings.PORT,
reload=settings.DEBUG,
log_level=settings.LOG_LEVEL.lower(),
)