609 lines
31 KiB
Python
609 lines
31 KiB
Python
"""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 starlette.datastructures import MutableHeaders
|
||
|
||
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,
|
||
embeds as embeds_api, openapi as openapi_api, org, portal, quota as quota_api, runtime, support,
|
||
)
|
||
from . import config as config_module
|
||
from . import dbconfig, hubconfig
|
||
from . import cache as cache_module
|
||
from .compress import GzipResponseMiddleware, GzipStaticFiles
|
||
from .config import settings
|
||
from .cors import LiveCORSMiddleware
|
||
from .db import (SchemaCreationRefused, SessionLocal, advisory_lock, connection_budget_note,
|
||
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, embed, embed_session, events, external_check, 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)
|
||
# 接口 JSON 的 gzip。装在 CORS 后面(后装的在外层),预检与跨域头都先由 CORS 答完,
|
||
# 这一层只负责"一口写完的可压缩响应",流式的附件、预览、分段下载一概不碰。
|
||
app.add_middleware(GzipResponseMiddleware)
|
||
|
||
|
||
class SecurityHeadersMiddleware:
|
||
"""只干一件事:往响应头里写 CSP,管住"谁能被 OA 嵌进来"和"谁能把 OA 嵌进去"。
|
||
|
||
写成裸 ASGI 中间件而不是 ``@app.middleware("http")``:后者是 BaseHTTPMiddleware,
|
||
会把响应体过一遍内存,附件那种流式下载与分段预览没必要为几个响应头受这一刀。
|
||
|
||
两条头各管一头:
|
||
|
||
* ``frame-src``——表单里那一格要嵌外部系统的页面(``type=embed``,见
|
||
``docs/embed-page-field-design.md``)。白名单来自外部数据源注册表里启用中的那些来源,
|
||
外加配置项 ``[embed] frame_extra``。**必须留着 ``'self'`` 与 ``blob:``**:
|
||
附件预览是把 ``URL.createObjectURL`` 出来的 blob 地址塞进 iframe 的
|
||
(``components/common/FilePreviewDialog.vue``),漏了它 PDF 预览整块打不开。
|
||
* ``frame-ancestors 'none'``——本系统自己任何时候都不该被别人嵌。
|
||
|
||
只装在最后(后装的在外层),所以 gzip 与 CORS 都已经处理完,这一层不会盖掉谁的头。
|
||
"""
|
||
|
||
def __init__(self, app) -> None:
|
||
self.app = app
|
||
|
||
async def __call__(self, scope, receive, send) -> None:
|
||
if scope.get("type") != "http" or not settings.embed_csp:
|
||
await self.app(scope, receive, send)
|
||
return
|
||
try:
|
||
# 不在这条路上开数据库会话:缓存热着的时候连查询都没有(每个响应都要这个值)
|
||
frame_src = embed.frame_src_cached()
|
||
except Exception: # noqa: BLE001 - 读不到注册表也要有一条兜底的 CSP,别因此打不开页面
|
||
logger.warning("CSP: 读可嵌入来源清单失败,退回 'self' blob:", exc_info=True)
|
||
frame_src = "'self' blob:"
|
||
|
||
async def _send(message) -> None:
|
||
if message.get("type") == "http.response.start":
|
||
headers = MutableHeaders(scope=message)
|
||
headers.append("Content-Security-Policy", f"frame-src {frame_src}; frame-ancestors 'none'")
|
||
await send(message)
|
||
|
||
await self.app(scope, receive, _send)
|
||
|
||
|
||
app.add_middleware(SecurityHeadersMiddleware)
|
||
|
||
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")
|
||
# 表单里那一格外部页面:要地址、发免登短码、给对方验票(挂在 data-sources 旁边,
|
||
# 因为注册表就是同一张表,配置入口也在同一个页面)
|
||
app.include_router(embeds_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()
|
||
#: "醒一下"那一下的信号:退出线程和"发件箱刚落了新报文"都靠它把调度线程从等待里叫起来。
|
||
#: 退出与唤醒共用一个事件,是因为 ``Event.wait`` 只能等一个——谁叫的都起来看一眼,
|
||
#: 再看 ``_scheduler_stop`` 决定是退出还是接着跑这一轮。
|
||
_scheduler_stir = threading.Event()
|
||
|
||
|
||
def _wake_scheduler() -> None:
|
||
"""告诉调度线程"现在就有活":写回报文入队的那一刻用它,别等下一个轮询周期。"""
|
||
_scheduler_stir.set()
|
||
|
||
|
||
def _scheduler_sleep(seconds: float) -> bool:
|
||
"""调度线程的睡:到点自然醒,或者被 ``_wake_scheduler`` / 退出信号提前叫醒。
|
||
|
||
返回 True 表示该退出线程了。叫醒只改变"什么时候醒",不改变醒来之后跑什么,
|
||
所以多叫几次最多多跑一轮空转,不会把任务跑两遍(各段自己有租约与状态判断)。
|
||
"""
|
||
remaining = max(0.0, float(seconds))
|
||
woke = remaining > 0 and _scheduler_stir.wait(remaining)
|
||
if woke:
|
||
_scheduler_stir.clear() # 睡到了点还是被叫醒,接下来都一样:跑一轮,再看该不该退
|
||
return _scheduler_stop.is_set()
|
||
|
||
|
||
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()
|
||
if any(name.startswith("redis_") for name in changed):
|
||
# Redis 的连接参数变了:换客户端、把"连不上先冷却 15 秒"那一档也一起清掉,
|
||
# 免得刚填对的地址还要等半分钟才生效;顺带把失效广播的订阅线程拉起来。
|
||
cache_module.reset()
|
||
cache_module.start_bus()
|
||
|
||
|
||
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), ("外部核验对账", external_check.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_sleep(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:
|
||
# 外部核验(票据初审那类)的兜底对账:回调没来、也没人点提交时,到点的批次
|
||
# 由这里按批次号问回来。回调联调期间也别关掉它——这是整条链路唯一
|
||
# "没人管也不会烂在那儿"的保证。
|
||
external_check.reconcile(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:
|
||
# 嵌进来的那一页被放弃了(人没保存就返回)而前端那一句没报上来——会话过期
|
||
# 之后由这里补发一次"删掉你们那张草稿"。放在发件箱之后:同一类外呼,
|
||
# 挂了也别连累别的投递。
|
||
embed_session.sweep_abandons(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()
|
||
# 跑完这一轮睡回去。这一觉能被"刚入队了报文"提前叫醒:写完回不再等下一个周期,
|
||
# 实测同一次提交入队的报文从"最多等 60 秒"变成当场就发(轮询退回兜底)。
|
||
if _scheduler_sleep(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
|
||
# 报文一入队就把这一条线程叫起来(同进程直接置事件,跨副本走 TOPIC_OUTBOUND 广播):
|
||
# 写回的即时性靠这个,15/60 秒那一档轮询退回"叫不醒也要发出去"的兜底。
|
||
outbox.wake(_wake_scheduler)
|
||
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)
|
||
# 上一趟进程被 kill / 容器重启会留下一条「进行中」的同步记录,谁都不会
|
||
# 再去收尾,于是同步历史一直转圈、「立即同步」一直按不动。启动时清一次
|
||
# (判据是"超过半小时且没人持锁",别的副本真在跑时不会误伤)。
|
||
hub_sync.reap_stale_runs(session, message="后端重启:上一趟同步没能收尾,已标记为终止")
|
||
finally:
|
||
session.close()
|
||
logger.info("database ready at %s:%s/%s", settings.db_host, settings.db_port, settings.db_name)
|
||
# 连接数这笔账:进程数(OA_WORKERS)× 每进程池子上限 别大过 MySQL 的 max_connections,
|
||
# 超了是排队不是变慢,而排队最难查(账怎么算见 app.db.connection_budget_note)
|
||
note = connection_budget_note()
|
||
if note:
|
||
logger.warning("上线体检:%s", note)
|
||
if int(settings.workers or 1) > 1:
|
||
logger.info("HTTP 进程数 %s:后台任务照旧只有一个进程在做,靠 oa_worker_lease "
|
||
"那把租约挑出来(见 docs/multi-worker-deployment.md)", settings.workers)
|
||
# 一个环境一个库。别的"名字像本系统的库"多半是验收脚本被打断留下的残留,
|
||
# 现在喊一声比半年后对着 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")
|
||
_report_shared_state()
|
||
start_scheduler()
|
||
|
||
|
||
def _report_shared_state() -> None:
|
||
"""启动时说清 Redis 这一层今天参与不参与:多副本部署最容易踩的就是"以为接上了"。
|
||
|
||
没配是正常状态(单进程部署本来就不需要),只 INFO 一句;配了却连不上是 WARNING,
|
||
因为那时限流额度会按副本数放大、缓存各副本一份,跟部署者的预期不一致。
|
||
"""
|
||
reachable, note = cache_module.ping()
|
||
if not cache_module.configured():
|
||
logger.info("共享缓存:%s(多副本部署才需要,见 config.<环境名>.toml 的 [redis] 段)", note)
|
||
return
|
||
if reachable:
|
||
logger.info("共享缓存:%s;%s", note, "失效广播订阅线程已启动" if cache_module.start_bus() else "失效广播已关闭")
|
||
else:
|
||
# 命令那一侧自己会在冷却之后重试,订阅线程却不能等:过去这一支只喊一句 WARNING 就走,
|
||
# 于是"后端先起、Redis 晚几秒才起来"这种最常见的重启顺序,会把失效广播永久落下——
|
||
# 缓存跟着 Redis 恢复,本副本却再也收不到别的副本的失效通知,直到有人手动 reload 一次。
|
||
# 订阅线程本来就是"订不上就一直试"(间隔 1 秒起、最多退到 15 秒),这里只管拉起来就行。
|
||
retrying = cache_module.start_bus()
|
||
logger.warning("共享缓存:配了 Redis 但不可用(%s)。这段时间按单进程口径跑:"
|
||
"各副本自己缓存、限流查库计数、配置失效最多等一个快照周期;%s"
|
||
"想现在就把这一层拉回来,用 POST /api/v1/system/redis/reload",
|
||
note, "订阅线程已拉起,Redis 一回来就自己接上;" if retrying else
|
||
"失效广播按配置是关的;")
|
||
|
||
|
||
@app.on_event("shutdown")
|
||
def _shutdown() -> None:
|
||
_scheduler_stop.set()
|
||
_scheduler_stir.set() # 叫醒正在睡的那一觉,别等它自己到点
|
||
cache_module.stop_bus()
|
||
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 _route_methods_for_get(path: str) -> str:
|
||
"""这个路径上有没有**只吃别的动词**的接口:有就把动词回给对方看,没有就回空串。
|
||
|
||
Starlette 的路由表里先撞上了这条 SPA 兜底(它注册的是 GET/HEAD),所以方法不匹配
|
||
轮不到它报 405,只能自己回来翻一遍表。翻不到就算没说——兜底该保守,不猜接口名。
|
||
"""
|
||
from starlette.routing import Match
|
||
|
||
scope = {"type": "http", "method": "GET", "path": path, "headers": [],
|
||
"query_string": b"", "root_path": ""}
|
||
allowed: set[str] = set()
|
||
for route in app.routes:
|
||
try:
|
||
match, _ = route.matches(scope)
|
||
except Exception: # noqa: BLE001 - 只为多问一句动词,任何路由算不了就跳过
|
||
continue
|
||
if match == Match.PARTIAL:
|
||
allowed |= {str(item) for item in (getattr(route, "methods", None) or set())
|
||
if str(item).upper() not in ("HEAD", "OPTIONS")}
|
||
return "、".join(sorted(allowed))
|
||
|
||
|
||
def _dist_dir() -> Path | None:
|
||
for candidate in _DIST_CANDIDATES:
|
||
if (candidate / "index.html").exists():
|
||
return candidate
|
||
return None
|
||
|
||
|
||
class _HashedStaticFiles(GzipStaticFiles):
|
||
"""Vite names build assets with a content hash, so they never change in place.
|
||
|
||
压过的那一份按内容指纹记在内存里(见 :mod:`app.compress`):哈希命名的文件内容
|
||
永远不变,所以压一次能用满整个进程生命周期,不必每次请求重烧一遍 CPU。
|
||
"""
|
||
|
||
|
||
# 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")):
|
||
# 地址在、动词不对:这条接口只吃 POST,而浏览器地址栏只会 GET。把这两种情况
|
||
# 混成一句"接口不存在",对接方就会以为接口没部署,来回扯一轮——说清差的是动词
|
||
methods = _route_methods_for_get("/" + full_path)
|
||
if methods:
|
||
return JSONResponse({
|
||
"code": 405, "reason": "METHOD_NOT_ALLOWED", "data": None,
|
||
"message": f"这个地址上没有 GET 接口,它只接受 {methods}:"
|
||
"浏览器地址栏发的是 GET,请改用 curl / Postman 调",
|
||
}, status_code=405)
|
||
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",
|
||
}
|
||
)
|