Files
planet/backend/app/main.py
T
linkong 5fc698d738
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release / images (push) Canceled after 0s
release / client_release (push) Canceled after 0s
release: bump version to 0.78.0
2026-11-23 22:40:11 +08:00

266 lines
9.2 KiB
Python

import asyncio
from contextlib import asynccontextmanager
from pathlib import Path
from uuid import uuid4
from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
from starlette.middleware.base import BaseHTTPMiddleware
from app.api.main import api_router
from app.api.v1 import websocket
from app.core.config import settings, validate_production_security
from app.core.logging import configure_logging, get_logger
from app.core.request_context import set_request_id
from app.core.security import _AsyncRedisClient, get_current_user
from app.core.websocket.broadcaster import broadcaster
from app.core.websocket.manager import manager
from app.db.session import async_session_factory, init_db
from app.models.user import User
from app.services.data_jobs import start_data_job_worker, stop_data_job_worker
from app.services.earth_db_change_listener import (
start_earth_db_change_listener,
stop_earth_db_change_listener,
)
from app.services.earth_news_worker import (
start_earth_news_target_worker,
stop_earth_news_target_worker,
)
from app.services.scheduler import (
acquire_scheduler_leader_lock,
cleanup_stale_running_tasks,
release_scheduler_leader_lock,
start_scheduler,
stop_scheduler,
sync_scheduler_with_datasources,
)
configure_logging()
logger = get_logger(__name__, service="main")
class WebSocketCORSMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
if request.url.path.startswith("/ws") and request.method == "GET":
response = await call_next(request)
allow_origins = settings.CORS_ORIGINS or []
origin = request.headers.get("origin")
if "*" in allow_origins:
response.headers["Access-Control-Allow-Origin"] = "*"
elif origin and origin in allow_origins:
response.headers["Access-Control-Allow-Origin"] = origin
response.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "*"
return response
return await call_next(request)
class RequestContextMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
request_id = request.headers.get("X-Request-ID") or uuid4().hex
set_request_id(request_id)
try:
response = await call_next(request)
finally:
set_request_id(None)
response.headers["X-Request-ID"] = request_id
return response
@asynccontextmanager
async def lifespan(app: FastAPI):
validate_production_security(settings)
await init_db()
pubsub_started = False
leader_lock_acquired = False
scheduler_started = False
workers_started = False
broadcaster_started = False
listener_started = False
try:
await manager.start_pubsub()
pubsub_started = True
if settings.should_run_scheduler:
if await acquire_scheduler_leader_lock():
leader_lock_acquired = True
await cleanup_stale_running_tasks()
start_scheduler()
scheduler_started = True
await sync_scheduler_with_datasources()
else:
logger.warning_event(
"Scheduler leader lock held by another instance; skipping scheduler startup",
event="scheduler.leader_lock.skipped",
context={"role": settings.normalized_role},
)
if settings.should_run_workers:
start_data_job_worker()
start_earth_news_target_worker()
workers_started = True
broadcaster.start()
broadcaster_started = True
start_earth_db_change_listener()
listener_started = True
yield
finally:
if listener_started:
try:
await stop_earth_db_change_listener()
except Exception as exc:
logger.warning_event(
"Failed stopping earth db change listener during shutdown",
event="app.shutdown.listener_error",
context={"error": str(exc)},
)
if broadcaster_started:
try:
broadcaster.stop()
except Exception as exc:
logger.warning_event(
"Failed stopping broadcaster during shutdown",
event="app.shutdown.broadcaster_error",
context={"error": str(exc)},
)
if workers_started:
try:
await stop_earth_news_target_worker()
except Exception as exc:
logger.warning_event(
"Failed stopping earth news worker during shutdown",
event="app.shutdown.earth_news_error",
context={"error": str(exc)},
)
try:
await stop_data_job_worker()
except Exception as exc:
logger.warning_event(
"Failed stopping data job worker during shutdown",
event="app.shutdown.data_job_error",
context={"error": str(exc)},
)
if scheduler_started:
try:
stop_scheduler()
except Exception as exc:
logger.warning_event(
"Failed stopping scheduler during shutdown",
event="app.shutdown.scheduler_error",
context={"error": str(exc)},
)
if leader_lock_acquired:
try:
await release_scheduler_leader_lock()
except Exception as exc:
logger.warning_event(
"Failed releasing scheduler leader lock during shutdown",
event="app.shutdown.leader_lock_error",
context={"error": str(exc)},
)
if pubsub_started:
try:
await manager.stop_pubsub()
except Exception as exc:
logger.warning_event(
"Failed stopping pubsub during shutdown",
event="app.shutdown.pubsub_error",
context={"error": str(exc)},
)
app = FastAPI(
title=settings.PROJECT_NAME,
version=settings.VERSION,
description="智能星球计划 - 态势感知系统\n\n## 功能模块\n\n- **用户认证**: JWT-based authentication\n- **数据源管理**: 多源数据采集器管理\n- **任务调度**: 定时任务调度与监控\n- **实时更新**: WebSocket实时数据推送\n- **告警系统**: 多级告警管理\n\n## 数据层级\n\n- **L1**: 核心数据 (TOP500, Epoch AI GPU)\n- **L2**: 扩展数据 (HuggingFace, PeeringDB, 海缆)\n- **L3**: 分析数据\n- **L4**: 决策支持",
lifespan=lifespan,
docs_url=None,
redoc_url="/docs",
openapi_url="/openapi.json",
)
configured_origins = list(settings.CORS_ORIGINS or [])
app.add_middleware(
CORSMiddleware,
allow_origins=configured_origins,
allow_credentials="*" not in configured_origins and bool(configured_origins),
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(RequestContextMiddleware)
app.add_middleware(WebSocketCORSMiddleware)
app.include_router(api_router, prefix="/api/v1")
app.include_router(websocket.router)
EARTH_BRAND_ASSET_DIR = Path(__file__).resolve().parents[2] / "data" / "earth-brand"
EARTH_BRAND_ASSET_DIR.mkdir(parents=True, exist_ok=True)
app.mount(
"/earth-brand-assets",
StaticFiles(directory=str(EARTH_BRAND_ASSET_DIR)),
name="earth-brand-assets",
)
@app.get("/health")
async def health_check():
return {"status": "healthy", "version": settings.VERSION}
@app.get("/health/live")
async def health_live():
return {"status": "alive", "version": settings.VERSION, "role": settings.normalized_role}
@app.get("/health/ready")
async def health_ready():
checks = {"database": "error", "redis": "error"}
try:
async with async_session_factory() as db:
await asyncio.wait_for(db.execute(text("SELECT 1")), timeout=2.0)
checks["database"] = "ok"
except Exception:
checks["database"] = "error"
try:
client = _AsyncRedisClient.get_client()
pong = await asyncio.wait_for(client.ping(), timeout=2.0)
checks["redis"] = "ok" if pong else "error"
except Exception:
checks["redis"] = "error"
all_ok = all(value == "ok" for value in checks.values())
payload = {
"status": "ready" if all_ok else "degraded",
"version": settings.VERSION,
"role": settings.normalized_role,
"checks": checks,
}
if not all_ok:
return JSONResponse(status_code=503, content=payload)
return payload
@app.get("/")
async def root():
return {
"name": settings.PROJECT_NAME,
"version": settings.VERSION,
"docs": "/docs",
"redoc": "/redoc",
}
@app.get("/api/v1/scheduler/jobs")
async def get_scheduler_jobs(_current_user: User = Depends(get_current_user)):
from app.services.scheduler import get_scheduler_jobs
return {"jobs": get_scheduler_jobs()}