unis-oa/backend/app/main.py

438 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""FastAPI application entry point for the UniSOA approval platform."""
from __future__ import annotations
import logging
import os
import threading
import time
from pathlib import Path
from fastapi import FastAPI, Request, status
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from .api import (
ai as ai_api, auth, authrole, config as config_api, data_sources as data_sources_api, design,
dicts as dicts_api, export, hub, integrations as integrations_api, notify_channels,
openapi as openapi_api, org, portal, quota as quota_api, runtime, support,
)
from . import config as config_module
from . import dbconfig, hubconfig
from .config import settings
from .cors import LiveCORSMiddleware
from .db import (SchemaCreationRefused, SessionLocal, advisory_lock, create_schema, ensure_database,
list_stray_schemas, ping)
from .envelope import install_exception_handlers, ok
from . import storage as storage_module
from .engine import engine as engine_module
from .service import channels, events, hub_sync, leader, openauth, outbox
from .seed import run as run_seed
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-7s %(name)s | %(message)s",
)
logger = logging.getLogger("unisoa")
app = FastAPI(
title="UniSOA 流程审批平台",
description="O2OA 流程审批模块的 Python 实现(FastAPI + SQLAlchemy + MySQL)",
version="1.0.0",
docs_url="/api/docs",
openapi_url="/api/openapi.json",
)
# 跨域来源存在配置里(config:server),所以用现读现判的中间件:
# 界面上加一个前端域名,保存完刷新页面就能跨域,不用重启后端。
app.add_middleware(LiveCORSMiddleware)
install_exception_handlers(app)
def _install_engine_error_handler() -> None:
"""引擎的 ``EngineError`` 永远是业务原因,不该变成 500。
各接口自己包 try/except 难免有漏网之鱼(催办、终止这两个就漏过),
这里统一兜一层。引擎抛错时没人调过 ``db.commit()``,会话在 ``get_db``
关闭时自动回滚,半截流转不会落库。
"""
@app.exception_handler(engine_module.EngineError)
async def _engine_error_handler(
request: Request, exc: engine_module.EngineError
) -> JSONResponse:
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content={"code": 400, "message": str(exc), "reason": "ENGINE_ERROR", "data": None},
)
_install_engine_error_handler()
@app.get("/api/v1/ping")
def ping_endpoint() -> dict:
return ok({"database": ping(), "time": time.strftime("%Y-%m-%d %H:%M:%S")})
app.include_router(auth.router, prefix="/api/v1")
# 免登回调的别名路径(/sso/hub):不带 /api/v1 前缀,必须挂在文件末尾那个 SPA
# 兜底路由之前,否则这个地址会被前端壳子接走,Hub 卡片点进来只剩一张空壳页。
app.include_router(auth.sso_alias_router)
app.include_router(org.router, prefix="/api/v1")
app.include_router(authrole.router, prefix="/api/v1")
app.include_router(design.router, prefix="/api/v1")
app.include_router(dicts_api.router, prefix="/api/v1")
app.include_router(quota_api.router, prefix="/api/v1")
app.include_router(data_sources_api.router, prefix="/api/v1")
app.include_router(integrations_api.router, prefix="/api/v1")
app.include_router(runtime.router, prefix="/api/v1")
app.include_router(support.router, prefix="/api/v1")
app.include_router(portal.router, prefix="/api/v1")
app.include_router(hub.router, prefix="/api/v1")
app.include_router(config_api.router, prefix="/api/v1")
app.include_router(export.router, prefix="/api/v1")
app.include_router(ai_api.router, prefix="/api/v1")
# 消息渠道(邮件 / 群机器人)与开放平台。对外开放接口单独挂在 /api/v1/open 下,
# 管理面走 /api/v1/design/open,两套鉴权不同,路由也分开列,界面上好找、日志里好认。
app.include_router(notify_channels.router, prefix="/api/v1")
app.include_router(openapi_api.router, prefix="/api/v1")
app.include_router(openapi_api.open_router, prefix="/api/v1")
_scheduler_stop = threading.Event()
def _on_config_change(changed: dict) -> None:
"""配置一有变化就把存储层的客户端与探活缓存丢掉。
落点参数其实也进了缓存键(``storage.fingerprint()``),这里再清一次是图个
干脆:界面上刚改完 MinIO,下一次上传一定用的是新配置的新连接。
"""
if any(name.startswith(("minio_", "local_root", "fallback_to_local")) for name in changed):
storage_module.reset_cache()
dbconfig.on_change(_on_config_change)
#: 发件箱里有待发报文时的调度周期(docs/outbound-integration-design.md §5)
OUTBOUND_TICK_SECONDS = 15
@app.middleware("http")
async def _open_call_log(request, call_next):
"""给每一次对外开放接口调用留一条痕:哪个应用、什么路径、返回什么、多久。
放在中间件而不是各接口里写一遍,是因为**失败的那一次最需要留痕**——接口抛错时
函数体内的收尾代码根本不会执行,而中间件永远能看到最终的响应状态码。
"""
path = str(request.url.path)
if not path.startswith("/api/v1/open/"):
return await call_next(request)
started = time.perf_counter()
response = await call_next(request)
app_row = getattr(request.state, "open_app", None)
db = SessionLocal()
try:
openauth.log_call(
db,
app=getattr(app_row, "code", "") or "-",
app_name=getattr(app_row, "name", "") or ("换令牌请求" if path.endswith("/open/token") else "-"),
method=request.method,
path=path.replace("/api/v1", "", 1),
status_code=int(response.status_code or 0),
code="" if int(response.status_code or 200) < 400 else f"HTTP {response.status_code}",
error="" if int(response.status_code or 200) < 400 else f"HTTP {response.status_code}",
token_hint=str(getattr(request.state, "open_token_hint", "") or ""),
ip=str(request.client.host if request.client else ""),
ms=int((time.perf_counter() - started) * 1000),
)
db.commit()
except Exception: # pragma: no cover - defensive:留痕失败绝不能把接口带崩
logger.debug("记开放接口调用留痕失败", exc_info=True)
db.rollback()
finally:
db.close()
return response
def _scheduler_tick_seconds(db=None) -> int:
"""调度线程多久醒一次:默认 60 秒,开了增量同步或有外发任务就收紧(下限 15 秒)。"""
seconds = 60
try:
cfg = hubconfig.get()
if cfg.sync_allowed and cfg.hub_sync_enabled and cfg.hub_sync_changes_enabled:
seconds = max(15, min(60, cfg.hub_sync_changes_interval_seconds))
except Exception: # pragma: no cover - 配置层出问题不该拖垮调度
logger.debug("读增量同步周期失败,按 60 秒轮询", exc_info=True)
if db is not None:
for label, probe in (("发件箱", outbox.due_now), ("消息渠道", channels.due_now),
("事件订阅", events.due_now)):
try:
if probe(db):
seconds = min(seconds, OUTBOUND_TICK_SECONDS)
except Exception: # pragma: no cover - defensive
logger.debug("看看%s有没有待发任务失败,按原周期轮询", label, exc_info=True)
db.rollback()
return seconds
#: 调度租约的时长:至少 3 轮,避免自己还没跑完一轮就被下一个副本接走
LEASE_ROUNDS = 3
#: 留痕清理一天跑一次就够
PRUNE_INTERVAL_SECONDS = 86400
def _scheduler_loop() -> None:
"""Background jobs: wake delayed activities, flag overdue todos, nightly Hub sync.
**多副本时只有拿到租约的那个进程真的跑**(``service/leader.py``)。这一层不做的话,
``uvicorn --workers 4`` 一开就是四条调度线程:延时环节被唤醒四次、组织同步被拉四次、
同一条写回报文被发两次——对上游就是两张凭证。
"""
last_prune = 0.0
while True:
db = SessionLocal()
try:
# 周期先算:这一轮做完之后要睡多久,取决于"现在有没有急着要发出去的报文"
try:
tick = _scheduler_tick_seconds(db)
except Exception: # pragma: no cover - defensive
tick = 60
try:
leader_ok = leader.acquire(db, leader.NAME_SCHEDULER, ttl_seconds=max(120.0, tick * LEASE_ROUNDS))
except Exception: # pragma: no cover - defensive
logger.exception("取调度租约失败,本轮跳过")
db.rollback()
leader_ok = False
if not leader_ok:
# 别的副本是主:安静睡过这一轮,不抢、不报错、也不打日志刷屏。
# 这里必须真的睡一会儿,否则会变成"每秒几十次抢租约"把库打满。
if _scheduler_stop.wait(tick):
return
continue
try:
engine_module.wake_delays(db)
engine_module.mark_expired(db)
except Exception: # pragma: no cover - defensive
logger.exception("scheduler run failed")
db.rollback()
try:
# 每天到点(默认凌晨 1 点)从 Hub 拉一次全量组织人员;当天已经跑过就跳过。
hub_sync.run_scheduled(db)
except Exception: # pragma: no cover - defensive
logger.exception("hub directory sync failed")
db.rollback()
try:
# 增量:按游标拉组织人员变更流水(默认 45 秒一轮),落后过多时它自己会改拉全量。
hub_sync.run_scheduled_changes(db)
except Exception: # pragma: no cover - defensive
logger.exception("hub 增量同步失败")
db.rollback()
try:
# 审批结果写回业务系统:到点的报文按退避发出去,同单严格有序,重试进死信。
# 单独一个 try:上游挂了不能连累唤醒延时任务和组织同步。
outbox.run_due(db)
except Exception: # pragma: no cover - defensive
logger.exception("写回发件箱投递失败")
db.rollback()
try:
# 消息渠道:邮件与群机器人提醒,站内信已经落库,这一路失败不影响办单。
if dbconfig.value("notify_channels_enabled", True):
channels.run_due(db)
except Exception: # pragma: no cover - defensive
logger.exception("消息渠道投递失败")
db.rollback()
try:
# 事件订阅:把流程事件推给外部系统(订阅本身在「开放平台」页面配)。
if dbconfig.value("open_events_enabled", True):
events.run_due(db)
except Exception: # pragma: no cover - defensive
logger.exception("事件推送投递失败")
db.rollback()
try:
# 开放接口调用留痕只留配置的天数,一天清一次
if time.time() - last_prune > PRUNE_INTERVAL_SECONDS:
last_prune = time.time()
removed = openauth.prune_calls(db, keep_days=int(dbconfig.value("open_call_keep_days", 90)))
if removed:
logger.info("清理开放接口调用留痕 %d 条", removed)
except Exception: # pragma: no cover - defensive
logger.exception("清理开放接口调用留痕失败")
db.rollback()
finally:
db.close()
if _scheduler_stop.wait(tick):
return
def _scheduler_enabled() -> bool:
"""后台调度线程开不开。
多个副本一起跑也没关系:真正的"只有一个进程做"由库里的租约保证(``service/leader.py``),
这个开关只是给"这个副本专门只接接口、完全不跑后台任务"这种部署留的口子。
放在环境变量里而不是配置文件,是因为"跑几个副本、谁跑后台"本来就是部署层的事,
不该出现在业务配置页上。验收脚本也用它把投递时机拿到自己手里。
"""
return str(os.environ.get("OA_SCHEDULER", "on")).strip().lower() not in ("0", "off", "no", "false")
def start_scheduler() -> None:
if not _scheduler_enabled():
logger.warning("后台调度线程已关闭(OA_SCHEDULER=%s):延时任务、到期标记、组织同步与写回投递都不会自动跑",
os.environ.get("OA_SCHEDULER"))
return
thread = threading.Thread(target=_scheduler_loop, name="unisoa-scheduler", daemon=True)
thread.start()
@app.on_event("startup")
def _startup() -> None:
# 先说清楚"这一趟用的是哪一档配置文件、档位是谁定的":连不上库的时候这句话最要紧,
# 所以放在碰数据库之前,别被下面的异常吃掉
logger.info(
"config: 环境=%s(%s),配置文件按顺序叠:%s",
settings.env,
config_module.env_source(),
" + ".join(
f"{layer['path']}[{'读到' if layer['loaded'] else '没有这一档'}]" for layer in settings.config_layers
),
)
for problem in settings.config_warnings:
logger.warning("上线体检:%s", problem)
try:
ensure_database()
# 多副本同时启动(滚动发布、docker-compose 一起拉起、``--workers 4``)时,
# 建表补列与初始化数据只让一个进程做:两边同时 ALTER 同一张表会互相撞错误号,
# 而"我的那份改了、你的被回滚了"这种半套结构比直接起不来更难查。
# 用 MySQL 命名锁而不是库里的租约表——**建表之前那张表还不存在**。
with advisory_lock("unisoa:bootstrap", timeout_seconds=120) as mine:
if not mine:
logger.warning("上线体检:另一个进程正在建表补列,120 秒内没结束;本进程照常继续"
"(初始化是幂等的,最多重复跑一遍)")
if settings.auto_create_schema:
# 补表补列哪一步没做成都要单独喊一声:整趟被一句 "database bootstrap failed"
# 兜住过一次,结果库里缺列、服务照跑,第一次登录才炸(见 app/db.py: create_schema)。
for problem in create_schema():
logger.error(
"上线体检:%s。表结构可能已经落后于代码,接口会报 Unknown column;"
"请照上一条堆栈手工补这一列/索引,或改回用 sql/schema.sql 核一遍结构。",
problem,
)
session = SessionLocal()
try:
run_seed(session)
# 运行配置住在数据库里;库里没有的项每次现读配置文件,不往库里抄
dbconfig.prepare(session)
finally:
session.close()
logger.info("database ready at %s:%s/%s", settings.db_host, settings.db_port, settings.db_name)
# 一个环境一个库。别的"名字像本系统的库"多半是验收脚本被打断留下的残留,
# 现在喊一声比半年后对着 SHOW DATABASES 猜便宜(见 app/db.py: stray_schemas)
strays = list_stray_schemas()
if strays:
logger.warning(
"上线体检:%s:%s 上还有 %d 个名字也像本系统的库:%s。"
"一个环境只用一个库——确认它们不是验收脚本被打断留下的残留;"
"确实要留就把名字写进 [database] create_allowlist,这声提醒就会闭嘴。",
settings.db_host, settings.db_port, len(strays), "、".join(strays))
stored = sum(len(group) for name, group in dbconfig.stored_by_group().items())
logger.info(
"config: 运行配置共 %d 项,界面上保存过的 %d 项存在数据库 %s 的 %s* 行里(改完即生效,无需重启);"
"其余每次现读 %s(%s,不会被写进库);环境变量固定了 %d 项",
len(dbconfig.ITEMS),
stored,
dbconfig.SETTING_TABLE,
dbconfig.DB_KEY_PREFIX,
settings.config_file,
"已读取" if settings.config_loaded else "未读到,用默认值",
len(config_module.env_overrides()),
)
if config_module.env_overrides():
logger.info(
"config: 这些环境变量暂时盖住了库里的值:%s", "、".join(config_module.env_overrides())
)
except SchemaCreationRefused as exc:
# 库名不在白名单 = 配置写错了,不是可以带着跑的软失败:接着对外接客只会让人对着
# 一堆 500 猜原因。直接把话撂在启动日志里,进程就此退出。
for line in str(exc).splitlines():
logger.error("上线体检:%s", line)
raise
except Exception:
logger.exception("database bootstrap failed")
start_scheduler()
@app.on_event("shutdown")
def _shutdown() -> None:
_scheduler_stop.set()
if _scheduler_enabled():
# 主动交还调度租约:不交的话,重启期间新副本要等一个 TTL 才敢接手,
# 这段时间延时环节和消息投递是停的
try:
session = SessionLocal()
try:
leader.release(session, leader.NAME_SCHEDULER)
finally:
session.close()
except Exception: # pragma: no cover - defensive
logger.debug("交还调度租约失败(进程正在退出,忽略)", exc_info=True)
# ------------------------- built front end hosting -------------------------
_DIST_CANDIDATES = [
Path(__file__).resolve().parent.parent.parent / "frontend" / "dist",
Path(__file__).resolve().parent.parent / "web" / "dist",
]
def _dist_dir() -> Path | None:
for candidate in _DIST_CANDIDATES:
if (candidate / "index.html").exists():
return candidate
return None
class _HashedStaticFiles(StaticFiles):
"""Vite names build assets with a content hash, so they never change in place."""
def file_response(self, *args, **kwargs) -> FileResponse:
response = super().file_response(*args, **kwargs)
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
return response
# The app shell references hashed chunks, so caching it by heuristic would keep
# browsers loading a superseded build after every deploy.
_SHELL_HEADERS = {"Cache-Control": "no-cache"}
_dist = _dist_dir()
if _dist is not None:
assets = _dist / "assets"
if assets.exists():
app.mount("/assets", _HashedStaticFiles(directory=str(assets)), name="assets")
# HEAD is served as well so probes and link checkers do not see 405
@app.api_route("/{full_path:path}", methods=["GET", "HEAD"], include_in_schema=False)
def spa(full_path: str):
if full_path.startswith(("api/", "docs", "redoc")):
return JSONResponse({"code": 404, "message": "接口不存在", "data": None}, status_code=404)
candidate = (_dist / full_path).resolve() if full_path else None
if candidate and candidate.is_file() and candidate.is_relative_to(_dist.resolve()):
return FileResponse(str(candidate), headers=_SHELL_HEADERS)
return FileResponse(str(_dist / "index.html"), headers=_SHELL_HEADERS)
else:
@app.get("/", include_in_schema=False)
def root_hint() -> dict:
return ok(
{
"name": "UniSOA 流程审批平台 API",
"docs": "/api/docs",
"hint": "前端未构建,请执行 cd frontend && pnpm build 或 pnpm dev",
}
)