main.py
4.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
"""云端入口:python -m app.main(在 server/ 目录下)。
启动顺序:日志 → 连库 + 迁移 → 首次初始化 → 运行事件写库线程 → 各功能启动钩子 → 调度器 → 企微收消息线程。
路由:/api/auth、/api/me、/api/system|client|wecom|assistant(后台,需登录)、/api/<功能>/*(如 /api/restock)、
/api/edge/v1/*(取数端,设备令牌)、/api/public/*(免登录)、/healthz;其余路径托管前端 SPA。
"""
from __future__ import annotations
import asyncio
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from . import __version__, bootstrap, features
from .api import assistant as assistant_api
from .api import auth, client, edge_api, public, system, wecom
from .core import db
from .core import logging as corelog
from .core.config import C, env
from .core.download_meter import DownloadMeter
from .services import edge, events, im, releases
from .services.agent import assistant
from .services.scheduler import scheduler
log = logging.getLogger("server")
STATE: dict = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
db.init_engine()
await asyncio.to_thread(db.migrate)
bootstrap.run()
events.start()
edge.mark_started()
await asyncio.to_thread(releases.register_bundled)
for f in features.FEATURES.values():
await f.on_startup()
if not STATE.get("no_background"):
scheduler.start()
poller = im.Poller(assistant.handle, asyncio.get_running_loop())
poller.start()
STATE["poller"] = poller
events.emit(f"云端已启动 v{__version__}({C.env_label})", "ok", source="system")
yield
if STATE.get("poller"):
STATE["poller"].stop()
await scheduler.stop()
events.stop()
def create_app(background: bool = True) -> FastAPI:
corelog.setup()
STATE["no_background"] = not background
features.load_all()
app = FastAPI(title="库存补货助手", version=__version__, lifespan=lifespan)
app.add_middleware(DownloadMeter) # 证据文件(日志包 / 诊断包 / 截图)下载计量,排查「下载失败」用
for r in (public.router, auth.router, system.router, client.router, wecom.router, assistant_api.router,
edge_api.router):
app.include_router(r)
for f in features.FEATURES.values():
for r in (f.router(), f.public_router()):
if r is not None:
app.include_router(r)
@app.exception_handler(ValueError)
async def _value_error(request: Request, exc: ValueError):
return JSONResponse({"detail": str(exc)}, status_code=400)
@app.exception_handler(Exception)
async def _server_error(request: Request, exc: Exception):
"""未捕获异常(500)→ 告警 system.http_500,同一接口未恢复期间按重复提醒间隔再提醒;堆栈照常进云端日志。"""
route = request.scope.get("route")
path = getattr(route, "path", None) or request.url.path
try:
from .services import alerts
await alerts.open_alert(None, "system.http_500", f"api:{request.method} {path}", "error",
f"接口内部错误:{request.method} {path}",
f"{type(exc).__name__}: {exc}"[:1000] + "\n详细堆栈见云端日志。")
except Exception: # noqa: BLE001 告警本身失败不影响返回
log.exception("接口内部错误告警没发出去")
return JSONResponse({"detail": "服务器内部错误,已通知管理员"}, status_code=500)
dist = C.web_dist
if dist.exists() and (dist / "index.html").exists():
if (dist / "assets").exists():
app.mount("/assets", StaticFiles(directory=dist / "assets"), name="assets")
@app.get("/{path:path}", include_in_schema=False)
def spa(path: str):
if path.startswith("api/"):
raise HTTPException(404, "接口不存在")
f = dist / path
if path and f.is_file() and dist in f.resolve().parents:
return FileResponse(f)
# index.html 不缓存:升级后浏览器立刻拿到新版本(assets/ 下的文件名带内容哈希,可以长期缓存)
return FileResponse(dist / "index.html", headers={"Cache-Control": "no-cache"})
return app
def main() -> None:
import uvicorn
# CLOUD_BACKGROUND=false:不跑调度器和企微收消息(本机多开一个实例看页面用,避免和正式实例重复调度)
background = (env("CLOUD_BACKGROUND") or "true").lower() != "false"
uvicorn.run(create_app(background), host=C.host, port=C.port, log_config=None, proxy_headers=True,
forwarded_allow_ips="*")
if __name__ == "__main__":
main()