-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
189 lines (162 loc) · 5.43 KB
/
Copy pathmain.py
File metadata and controls
189 lines (162 loc) · 5.43 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
import logging
from contextlib import asynccontextmanager
from typing import Any, Dict, List
from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.trustedhost import TrustedHostMiddleware
from api.auth import api_key_middleware
from api.rate_limit import rate_limit_middleware
from api.response import api_error
from api.request_context import (
get_request_id,
request_body_size_limit_middleware,
request_id_middleware,
request_logging_middleware,
security_headers_middleware,
)
from api.routes import router
from api.health import set_api_draining
from config import settings
from runtime.observability import log_structured, redact_sensitive_text
from startup_validation import validate_startup_or_raise
def validate_api_startup() -> None:
validate_startup_or_raise()
def is_production_env() -> bool:
return settings.app_env in ["prod", "production"]
@asynccontextmanager
async def lifespan(app: FastAPI):
validate_api_startup()
set_api_draining(False)
try:
yield
finally:
set_api_draining(True, reason="shutdown")
app = FastAPI(
title="多 Agent 创业分析系统",
description=(
"自研多 Agent 工作流 runtime,用于把创业想法拆解为市场、产品、技术、"
"财务、批判性审查和最终决策等多个 Agent 协作任务。系统支持异步执行、"
"结构化输出、agent-level retry、worker retry、heartbeat、recovery 和统一 API 响应合同。"
),
version="0.1.0",
lifespan=lifespan,
openapi_url=None if is_production_env() else "/openapi.json",
docs_url=None if is_production_env() else "/docs",
redoc_url=None if is_production_env() else "/redoc",
)
app.include_router(router, prefix="/api")
def split_csv_setting(value: str) -> List[str]:
return [
item.strip()
for item in value.split(",")
if item.strip()
]
cors_allowed_origins = split_csv_setting(settings.cors_allowed_origins)
if cors_allowed_origins:
app.add_middleware(
CORSMiddleware,
allow_origins=cors_allowed_origins,
allow_credentials=True,
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=[
"Authorization",
"Content-Type",
"Idempotency-Key",
"X-API-Key",
"X-Metrics-API-Key",
"X-Platform-API-Key",
"X-Request-ID",
"X-Tenant-ID",
],
)
trusted_hosts = split_csv_setting(settings.trusted_hosts)
if trusted_hosts:
app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=trusted_hosts,
)
app.middleware("http")(rate_limit_middleware)
app.middleware("http")(api_key_middleware)
app.middleware("http")(request_logging_middleware)
app.middleware("http")(request_id_middleware)
app.middleware("http")(security_headers_middleware)
app.middleware("http")(request_body_size_limit_middleware)
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc: HTTPException):
request_id = get_request_id(request)
if isinstance(exc.detail, dict) and "success" in exc.detail:
return JSONResponse(
status_code=exc.status_code,
content=exc.detail,
)
return JSONResponse(
status_code=exc.status_code,
content={
"success": False,
"data": None,
"error": {
"code": "http_error",
"message": str(exc.detail),
"details": {},
},
"request_id": request_id,
"correlation_id": None,
},
)
def sanitize_validation_errors(errors: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
sanitized_errors = []
for error in errors:
sanitized_errors.append({
"loc": list(error.get("loc", [])),
"type": error.get("type"),
"msg": error.get("msg"),
})
return sanitized_errors
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc: RequestValidationError):
return JSONResponse(
status_code=422,
content=api_error(
code="validation_error",
message="Request validation failed",
details={
"errors": sanitize_validation_errors(exc.errors()),
},
request=request,
),
)
@app.exception_handler(Exception)
async def unhandled_exception_handler(request, exc: Exception):
request_id = get_request_id(request)
log_structured(
logging,
logging.ERROR,
event="api_unhandled_exception",
service="api",
run_id="-",
job_type="http_request",
correlation_id=None,
details={
"method": request.method,
"path": request.url.path,
"request_id": request_id,
"exception_type": type(exc).__name__,
"exception": redact_sensitive_text(str(exc)),
},
)
return JSONResponse(
status_code=500,
content={
"success": False,
"data": None,
"error": {
"code": "internal_server_error",
"message": "Internal server error",
"details": {},
},
"request_id": request_id,
"correlation_id": None,
},
)