main.py 6.24 KB
"""云端入口: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
import os
import socket
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 .core.request_log import RequestLog
from .services import edge, events, im, links, releases, settings, stores
from .services.agent import assistant
from .services.scheduler import scheduler

log = logging.getLogger("server")
STATE: dict = {}


def startup_info() -> str:
    """这个实例是谁、连哪个库、链接用哪个域名、用哪个机器人发到哪些群。多套环境并存时靠它分清是哪个实例发的消息。
    不含账号、密码、令牌。"""
    out = [f"主机 {socket.gethostname()} PID {os.getpid()}", f"APP_ENV={C.app_env}", f"库 {C.db_label()}",
           f"对外地址 {links.base_url()}({links.base_url_source()})", f"imhub {settings.get().im_api_base}",
           "后台任务 " + ("关" if STATE.get("no_background") else "开")]
    for s in stores.stores(active_only=True):
        for t in im.targets(s["id"], True):
            out.append(f"[店{s['id']}] {t['bot_name']}({im.bot_of(t)['bot_id']}{'' if t['bot_enabled'] else ',已停用'})"
                       f" → {t['name']}({t['contact_id']})")
    return ";".join(out)


@asynccontextmanager
async def lifespan(app: FastAPI):
    db.init_engine()
    await asyncio.to_thread(db.verify_schema)        # 只读检查:表结构 / 版本标记不对就拒绝启动(改库走 sql_script)
    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")
    try:
        events.emit("实例信息:" + await asyncio.to_thread(startup_info), source="system")
    except Exception as e:  # noqa: BLE001  只是留痕,不能影响启动
        log.error("实例信息没取到:%s", type(e).__name__)
    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(RequestLog)               # 写操作和出错的请求各记一行(来源 IP、结果)
    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()