main.py 7.52 KB
# -*- coding: utf-8 -*-
"""
文件名: main.py
职责: 项目启动入口,初始化 FastAPI 应用,挂载路由和静态资源。
注意: 不要删除这个注释。
"""

import os
import time

# 强制设置时区为东八区(Docker/服务器兜底)
os.environ.setdefault("TZ", "Asia/Shanghai")
try:
    time.tzset()
except AttributeError:
    pass  # Windows 不支持 tzset,Docker Linux 环境生效

import uvicorn
import asyncio
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from contextlib import asynccontextmanager
from sqlalchemy.orm import Session

from app.core.scheduler import SchedulerManager
from app.core.config import settings
from app.api.auth import router as auth_router
from app.api.endpoints import router as api_router
from app.core.logging_config import setup_logging
from app.db.session import get_db, SessionLocal, engine
from app.services.auth_service import AuthService
from app.models.user import Base as AuthBase

# 初始化日志
setup_logging()

# 基础目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))


def _init_auth_tables_sync():
    """同步创建认证相关表( lifespan 中异步调用)"""
    AuthBase.metadata.create_all(bind=engine)


def _init_default_users_sync():
    """同步初始化默认账号( lifespan 中异步调用)"""
    db = SessionLocal()
    try:
        AuthService.init_default_users(db)
    finally:
        db.close()


@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时执行
    print("[*] Starting Data Analyze WebUI...")
    # 创建认证表(若不存在)并初始化默认账号
    await asyncio.to_thread(_init_auth_tables_sync)
    await asyncio.to_thread(_init_default_users_sync)
    # 创建策略效果分析结果表
    try:
        from app.services.strategy_service import StrategyService
        await asyncio.to_thread(StrategyService.ensure_result_table)
    except Exception as e:
        print(f"[!] Failed to create strategy result table: {e}")
    # 清理启动前卡住的 running 状态 ETL 历史记录(仅清理超过 2 小时未完成的任务)
    # 避免 reload 模式下将正在正常执行的 scheduler 任务误标记为 failed
    try:
        from sqlalchemy import text
        from app.db.session import SessionLocal
        db = SessionLocal()
        try:
            result = db.execute(text(
                "UPDATE _etl_history SET status = 'failed', "
                "end_time = NOW(), result_info = 'Server restarted, task interrupted' "
                "WHERE status = 'running' AND start_time < DATE_SUB(NOW(), INTERVAL 2 HOUR)"
            ))
            db.commit()
            stuck_count = getattr(result, 'rowcount', 0)
            if stuck_count:
                print(f"[*] Cleaned up {stuck_count} stuck ETL history record(s) (running -> failed)")
        finally:
            db.close()
    except Exception as e:
        print(f"[!] Failed to clean up stuck ETL history: {e}")
    # 启动定时任务调度器
    await SchedulerManager.start()
    yield
    # 关闭时执行
    print("[*] Stopping Data Analyze WebUI...")
    try:
        await asyncio.wait_for(SchedulerManager.stop(), timeout=5.0)
    except asyncio.TimeoutError:
        print("[!] Scheduler stop timed out, forcing exit.")
    except Exception as e:
        print(f"[!] Error during stop: {e}")


app = FastAPI(
    title="问界门店运营数据分析平台",
    description="支持 ODS/DWS/DWM/DWA 各层数据同步任务及分析模版展示",
    version="1.0.0",
    lifespan=lifespan,
    root_path=settings.ROOT_PATH or "",
)

# 挂载静态文件
app.mount("/static", StaticFiles(directory=os.path.join(BASE_DIR, "app/static")), name="./static")

# 配置模板引擎
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "app/templates"))


# ========== 认证依赖 ==========

async def get_current_user_for_page(request: Request, db: Session = Depends(get_db)):
    """页面路由使用的当前用户校验"""
    token = request.cookies.get("access_token")
    user = AuthService.get_current_user_from_token(db, token)
    if not user:
        raise HTTPException(status_code=401, detail="未登录")
    return user


async def get_current_user_for_api(request: Request, db: Session = Depends(get_db)):
    """API 路由使用的当前用户校验"""
    token = request.cookies.get("access_token")
    user = AuthService.get_current_user_from_token(db, token)
    if not user:
        raise HTTPException(status_code=401, detail="未登录或登录已过期")
    return user


# 注册公开认证路由
app.include_router(auth_router, prefix="/api")

# 注册受保护 API 路由
app.include_router(api_router, prefix="/api", dependencies=[Depends(get_current_user_for_api)])


# 页面路由映射:路径 → 模板文件名
PAGE_ROUTES = {
    "/": "index.html",
    "/ods": "ods.html",
    "/dw": "dw.html",
    "/analysis": "analysis.html",
    "/harmony": "harmony.html",
    "/harmony/sub-brand": "harmony_sub_brand.html",
    "/strategy": "strategy.html",
    "/strategy/detail": "strategy_detail.html",
    "/strategy/info": "strategy_info.html",
}


def _page_handler(template_name: str, require_auth: bool = True):
    """闭包工厂:为指定模板生成页面处理函数"""
    async def handler(request: Request, db: Session = Depends(get_db)):
        if require_auth:
            token = request.cookies.get("access_token")
            user = AuthService.get_current_user_from_token(db, token)
            if not user:
                # 未登录重定向到登录页
                return RedirectResponse(url="./login", status_code=302)
        return templates.TemplateResponse(request=request, name=template_name, context={})
    return handler


# 登录页(公开)
app.get("/login")(_page_handler("login.html", require_auth=False))

# 受保护业务页面
for path, tpl in PAGE_ROUTES.items():
    app.get(path)(_page_handler(tpl, require_auth=True))


@app.get("/api/health")
async def health():
    """健康检查接口(公开)"""
    return {"status": "ok", "message": "Welcome to Data Analyze WebUI API"}


if __name__ == "__main__":
    import signal
    import threading

    # Ctrl+C 后若优雅关闭卡住,超时后强制结束本进程(逻辑仅在此入口生效)
    FORCE_EXIT_SECONDS = 3
    _force_exit_state = {"armed": False}
    _force_exit_lock = threading.Lock()

    def _arm_force_exit():
        with _force_exit_lock:
            if _force_exit_state["armed"]:
                return
            _force_exit_state["armed"] = True

        def _force_kill():
            time.sleep(FORCE_EXIT_SECONDS)
            print(f"[!] {FORCE_EXIT_SECONDS}s 内未能正常退出,强制结束进程。")
            os._exit(1)

        threading.Thread(target=_force_kill, daemon=True, name="force-exit").start()

    def _on_exit_signal(signum, _frame):
        label = "Ctrl+C" if signum == signal.SIGINT else f"signal {signum}"
        print(f"[*] 收到退出信号 ({label}),正在关闭服务...")
        _arm_force_exit()
        raise KeyboardInterrupt

    signal.signal(signal.SIGINT, _on_exit_signal)
    if hasattr(signal, "SIGTERM"):
        signal.signal(signal.SIGTERM, _on_exit_signal)

    # 端口指定 9500,root_path 适配子路径部署(如 /daw)
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=9500,
        reload=settings.APP_DEBUG,
        root_path=settings.ROOT_PATH or "",
        timeout_graceful_shutdown=FORCE_EXIT_SECONDS,
    )