254 lines
10 KiB
Python
254 lines
10 KiB
Python
"""FastAPI 应用装配。
|
||
|
||
路由全部挂在 ``/api/v1`` 下,前端开发服务器通过 Vite 代理访问,生产走同域反向代理,
|
||
因此两边都不需要配 CORS 白名单(本地开发例外,白名单来自配置文件)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import threading
|
||
import time
|
||
from contextlib import asynccontextmanager
|
||
from typing import Any
|
||
|
||
from fastapi import FastAPI, Request
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
from fastapi.responses import JSONResponse
|
||
|
||
from . import dicts
|
||
from .api import approvals, audit as audit_api, auth, control, dicts as dicts_api, finance, org, plan, projects, system
|
||
from .config import settings
|
||
from .config import warnings as prod_warnings
|
||
from .db import create_all, ensure_database, ping
|
||
from .deps import DbSession
|
||
from .models import Account, Status
|
||
from .envelope import install_handlers, ok
|
||
from .seed import seed_all
|
||
from .service import audit as audit_log
|
||
from .service.calc import engine as calc_engine
|
||
from .service.calc import rules as calc_rules
|
||
|
||
logging.basicConfig(
|
||
level=getattr(logging, (settings.log.level or "INFO").upper(), logging.INFO),
|
||
format="%(asctime)s %(levelname)-5s %(name)s | %(message)s",
|
||
)
|
||
logger = logging.getLogger("pms.app")
|
||
|
||
@asynccontextmanager
|
||
async def lifespan(_app: FastAPI):
|
||
_bootstrap()
|
||
yield
|
||
|
||
|
||
app = FastAPI(
|
||
lifespan=lifespan,
|
||
title="四算项目管理系统",
|
||
version="1.0.0",
|
||
description="项目立项(概算)、项目预算与审批流程",
|
||
docs_url="/api/docs",
|
||
openapi_url="/api/openapi.json",
|
||
)
|
||
|
||
install_handlers(app)
|
||
|
||
if settings.server.cors_origins:
|
||
app.add_middleware(
|
||
CORSMiddleware,
|
||
allow_origins=settings.server.cors_origins,
|
||
allow_credentials=True,
|
||
allow_methods=["*"],
|
||
allow_headers=["*"],
|
||
)
|
||
|
||
# 写操作审计挂在最后加入(= 最外层),这样它看到的是最终状态码:过了 CORS、过了
|
||
# traceId、也过了业务异常处理,"这次到底改成没有"才记得准。详见 service/audit.py。
|
||
audit_log.install(app)
|
||
|
||
API = "/api/v1"
|
||
app.include_router(auth.router, prefix=API)
|
||
app.include_router(org.router, prefix=API)
|
||
app.include_router(system.router, prefix=API)
|
||
app.include_router(audit_api.router, prefix=API)
|
||
app.include_router(projects.router, prefix=API)
|
||
app.include_router(finance.router, prefix=API)
|
||
app.include_router(plan.router, prefix=API)
|
||
app.include_router(control.router, prefix=API)
|
||
app.include_router(approvals.router, prefix=API)
|
||
|
||
# 字典的两个入口都在 /api/v1 下:/dicts 给页面取下拉值,/system/dicts 是维护页
|
||
app.include_router(dicts_api.router, prefix=API)
|
||
app.include_router(dicts_api.admin, prefix=API)
|
||
|
||
|
||
#: 免登回调的短别名(``/sso/hub``)。Hub 上习惯把 launch_url 写成这一条,
|
||
#: 同域反代把它转给后端即可;规范地址仍是 ``/api/v1/auth/sso/callback``。
|
||
app.include_router(auth.sso_alias_router)
|
||
|
||
|
||
@app.get("/api/health")
|
||
def health() -> dict[str, Any]:
|
||
"""存活 + 就绪:给容器编排和负载均衡用。"""
|
||
database_ok = ping()
|
||
payload = {
|
||
"ok": database_ok,
|
||
"status": "ready" if database_ok else "degraded",
|
||
"env": settings.env,
|
||
"database": settings.database.name if database_ok else "unavailable",
|
||
"calcVersion": calc_engine.calc_version(),
|
||
"hub": {"enabled": settings.hub.enabled, "configured": settings.hub.configured},
|
||
}
|
||
return JSONResponse(status_code=200 if database_ok else 503, content=payload)
|
||
|
||
|
||
@app.get(f"{API}/bootstrap")
|
||
def bootstrap(request: Request, db: DbSession) -> dict[str, Any]:
|
||
"""前端启动时拉一次:运行档位、口径版本、数据字典、当前人的权限。
|
||
|
||
带了令牌就顺手把"这个人能看什么"一起返回,SPA 少一次往返、少一处加载竞态;
|
||
没带令牌也照常返回枚举与告警,登录页要用。
|
||
"""
|
||
from .api.auth import profile_payload
|
||
from .security import TokenError, decode_token
|
||
from .service import permissions
|
||
|
||
payload: dict[str, Any] = {
|
||
"env": settings.env,
|
||
"calcVersion": calc_engine.calc_version(),
|
||
"production": settings.is_production,
|
||
"warnings": prod_warnings(settings),
|
||
"hubEnabled": settings.hub.enabled,
|
||
"ssoEnabled": settings.hub.sso_configured,
|
||
# 登录页这三开关:口令框留不留、口令归不归统一身份验(决定要不要摆验证码)、
|
||
# 本地自建账号的口令还认不认(只影响提示语)。口径与 GET /auth/sso/status 一致。
|
||
"passwordLoginAllowed": settings.hub.password_login_allowed,
|
||
"hubPasswordLogin": settings.hub.hub_password_login,
|
||
"localPasswordAllowed": settings.hub.local_password_login_allowed,
|
||
"loginMode": settings.hub.mode,
|
||
"enums": dicts.build(db),
|
||
"user": None,
|
||
"permissions": [],
|
||
"roles": [],
|
||
"menus": [],
|
||
"fieldMasks": {},
|
||
}
|
||
header = request.headers.get("Authorization") or ""
|
||
token = header[7:].strip() if header.lower().startswith("bearer ") else ""
|
||
if token:
|
||
try:
|
||
account_id = int(decode_token(token, expect="access").get("sub") or 0)
|
||
except (TokenError, TypeError, ValueError):
|
||
account_id = 0
|
||
account = db.get(Account, account_id) if account_id else None
|
||
if account is not None and not account.is_deleted and Status.is_active(account.status):
|
||
context = permissions.build_context(db, account)
|
||
payload.update({
|
||
"user": profile_payload(db, account),
|
||
"permissions": ["*"] if context.is_system_admin else sorted(context.codes),
|
||
"roles": [{"id": role.id, "code": role.code, "name": role.name}
|
||
for role in context.roles],
|
||
"menus": permissions.menu_tree(db, context),
|
||
"fieldMasks": context.field_masks,
|
||
})
|
||
return ok(payload)
|
||
|
||
|
||
def _timeout_sweep_loop() -> None:
|
||
"""审批超时轮询,间隔走 ``[approval].timeout_sweep_minutes``。"""
|
||
interval = max(60, (settings.approval.timeout_sweep_minutes or 0) * 60)
|
||
if settings.approval.timeout_sweep_minutes <= 0:
|
||
return
|
||
while True:
|
||
time.sleep(interval)
|
||
try:
|
||
from .db import session_scope
|
||
from .service.approval.engine import sweep_timeouts
|
||
|
||
with session_scope() as session:
|
||
result = sweep_timeouts(session)
|
||
if result["reminded"] or result["auto_approved"]:
|
||
logger.info("审批超时处理:催办 %s 条,自动通过 %s 条",
|
||
result["reminded"], result["auto_approved"])
|
||
except Exception as exc: # 后台线程绝不能把进程带崩
|
||
logger.warning("审批超时轮询失败:%s", exc)
|
||
|
||
|
||
def _hub_sync_loop() -> None:
|
||
"""统一身份定时任务,两条节奏各走各的。
|
||
|
||
文档 §6.3 把同步定成三件事:首次全量、固定周期轮增量(30~60 秒)、每日一次全量校对。
|
||
增量和全量的代价差着两个数量级,不能共用一个间隔,所以这里拆成两个计时器共用一个
|
||
线程:增量按 ``changes_interval_seconds`` 蹭游标,全量按 ``sync_interval_minutes``
|
||
兜住"事件没发、写失败、父子关系变了"这三种增量永远补不到的情况。
|
||
"""
|
||
changes_interval = max(0, settings.hub.changes_interval_seconds or 0)
|
||
full_interval = max(0, (settings.hub.sync_interval_minutes or 0) * 60)
|
||
if not settings.hub.configured or (changes_interval <= 0 and full_interval <= 0):
|
||
return
|
||
|
||
from .db import session_scope
|
||
from .service.org_sync import local_cursor, sync_all, sync_changes
|
||
|
||
tick = min(x for x in (changes_interval or None, full_interval or None) if x) or 60
|
||
since_changes = 0
|
||
since_full = 0
|
||
while True:
|
||
time.sleep(tick)
|
||
since_changes += tick
|
||
since_full += tick
|
||
|
||
want_full = full_interval > 0 and since_full >= full_interval
|
||
# 本地还没有游标就说明从没成功全量过,先补一次全量再说增量。
|
||
if not want_full:
|
||
try:
|
||
with session_scope() as session:
|
||
want_full = local_cursor(session) <= 0
|
||
except Exception as exc: # noqa: BLE001
|
||
logger.warning("读取目录游标失败:%s", exc)
|
||
|
||
try:
|
||
if want_full:
|
||
since_full = 0
|
||
since_changes = 0
|
||
with session_scope() as session:
|
||
run = sync_all(session, trigger="scheduled")
|
||
logger.info("统一身份全量校对:%s(部门 +%s/改%s,账号 +%s/改%s)",
|
||
run.status, run.org_created, run.org_updated,
|
||
run.account_created, run.account_updated)
|
||
elif changes_interval > 0 and since_changes >= changes_interval:
|
||
since_changes = 0
|
||
with session_scope() as session:
|
||
run = sync_changes(session, trigger="scheduled")
|
||
if run.account_total or run.status != "success":
|
||
logger.info("统一身份增量同步:%s 处理 %s 条,游标 %s",
|
||
run.status, run.account_total, run.cursor_after)
|
||
except Exception as exc: # 后台线程绝不能把进程带崩
|
||
logger.warning("统一身份定时同步失败:%s", exc)
|
||
|
||
|
||
def _bootstrap() -> None:
|
||
logger.info("四算 PMS 启动:档位=%s", settings.env)
|
||
for message in prod_warnings(settings):
|
||
logger.warning("上线体检:%s", message)
|
||
|
||
if settings.database.auto_create_schema:
|
||
ensure_database()
|
||
create_all()
|
||
counts = seed_all()
|
||
logger.info("基础数据就绪:%s", counts)
|
||
|
||
from .db import session_scope
|
||
|
||
# 口径在库里,不在配置文件里:建表补完参数就把生效值读进内核,
|
||
# 免得第一个请求赶在 seed 之前跑,用的是代码默认值却盖着界面上的版本号。
|
||
with session_scope() as session:
|
||
calc_rules.reload(session)
|
||
logger.info("计算口径 %s:%s", calc_engine.calc_version(), calc_rules.describe(
|
||
[spec.attr for spec in calc_rules.RULE_SPECS if spec.attr != "version"]))
|
||
|
||
if not threading.main_thread().is_alive(): # pragma: no cover - 防御
|
||
return
|
||
threading.Thread(target=_timeout_sweep_loop, daemon=True, name="approval-timeout").start()
|
||
if settings.hub.enabled and settings.hub.configured:
|
||
threading.Thread(target=_hub_sync_loop, daemon=True, name="hub-sync").start()
|