Commit a6562a76 by imwangxiaozhou

feat(backend): 集成运维面板的后端托管功能

- 配置运维面板的vite构建基础路径与React Router basename为/panel,移除本地开发启动脚本
- 在生产Docker配置中添加复制运维面板静态产物的步骤
- 为FastAPI后端新增customer_groups路由,实现/panel路径的静态资源托管与SPA fallback
- 新增运维面板静态资源托管的单元测试
1 parent 192031cf
......@@ -35,6 +35,7 @@ COPY config/ ./config/
COPY skills/ ./skills/
COPY soul/ ./soul/
COPY scripts/ ./scripts/
COPY operation-panel/dist/ ./operation-panel/dist/
COPY sitecustomize.py ./
# 创建日志目录并设置权限
......
from fastapi import APIRouter
from app.api.v1.endpoints import agent_group_helper, agent_hub, agents, position_tags, skills, routing, analytics, qrcode_channel, official_site_tab, official_site_agent_display, official_site_upload, official_site_home, methodology, wecom_sync, wecom_jobs, wecom_debug
from app.api.v1.endpoints import agent_group_helper, agent_hub, agents, customer_groups, position_tags, skills, routing, analytics, qrcode_channel, official_site_tab, official_site_agent_display, official_site_upload, official_site_home, methodology, wecom_sync, wecom_jobs, wecom_debug
from app.customer_info import api as customer_info_api
api_router = APIRouter()
api_router.include_router(agent_group_helper.router, tags=["agent-group-helper"])
api_router.include_router(agents.router, tags=["agents"])
api_router.include_router(customer_groups.router, tags=["customer-groups"])
api_router.include_router(position_tags.router, tags=["position-tags"])
api_router.include_router(skills.router, tags=["skills"])
api_router.include_router(routing.router, tags=["routing"])
......
......@@ -2,9 +2,10 @@ import json
import os
from contextlib import asynccontextmanager
import logging
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from fastapi.responses import FileResponse, JSONResponse, Response
logger = logging.getLogger(__name__)
......@@ -56,6 +57,9 @@ redoc_url = f"{base_path}/redoc" if base_path else "/redoc"
openapi_url = f"{base_path}/openapi.json" if base_path else "/openapi.json"
oauth2_redirect_url = f"{base_path}/docs/oauth2-redirect" if base_path else "/docs/oauth2-redirect"
# 运维面板静态产物目录(operation-panel/dist),通过 /panel 由后端托管
PANEL_DIST_DIR = Path(__file__).resolve().parents[1] / "operation-panel" / "dist"
@asynccontextmanager
async def lifespan(app: FastAPI):
......@@ -218,6 +222,32 @@ def health_check():
return {"status": "ok"}
def _serve_panel_file(full_path: str) -> FileResponse:
"""提供运维面板静态文件:命中 dist 内真实文件则返回该文件,否则 SPA fallback 到 index.html。"""
dist_root = PANEL_DIST_DIR.resolve()
index_file = dist_root / "index.html"
if not dist_root.is_dir():
raise HTTPException(status_code=404, detail="operation-panel dist 未构建")
full_path = (full_path or "").lstrip("/")
if full_path:
candidate = (dist_root / full_path).resolve()
if candidate.is_file() and candidate.is_relative_to(dist_root):
return FileResponse(candidate)
return FileResponse(index_file)
@app.get(f"{base_path}/panel" if base_path else "/panel", include_in_schema=False)
async def panel_index():
return _serve_panel_file("index.html")
@app.get(f"{base_path}/panel/{{full_path:path}}" if base_path else "/panel/{full_path:path}", include_in_schema=False)
async def panel_spa(full_path: str):
return _serve_panel_file(full_path)
if __name__ == "__main__":
import uvicorn
......
......@@ -4,7 +4,6 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
......
......@@ -8,7 +8,7 @@ import { CustomerGroupChat } from './pages/CustomerGroupChat';
function App() {
return (
<BrowserRouter>
<BrowserRouter basename="/panel">
<Layout>
<Routes>
<Route path="/" element={<Navigate to="/customer-groups" replace />} />
......
......@@ -3,17 +3,5 @@ import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
host: '0.0.0.0',
port: 5180,
proxy: {
'/api': {
target: 'http://127.0.0.1:8082',
changeOrigin: true,
},
},
},
preview: {
host: '0.0.0.0',
},
base: '/panel/',
})
"""后端托管运维面板(/panel)静态资源与 SPA fallback 测试。"""
import pytest
from fastapi.testclient import TestClient
import app.main as main_module
@pytest.fixture
def panel_dist(tmp_path):
"""构造临时 dist 目录并注入 app.main.PANEL_DIST_DIR。"""
dist = tmp_path / "dist"
(dist / "assets").mkdir(parents=True)
(dist / "index.html").write_text("<html><body>panel index</body></html>", encoding="utf-8")
(dist / "assets" / "app.js").write_text("console.log('app')", encoding="utf-8")
original = main_module.PANEL_DIST_DIR
main_module.PANEL_DIST_DIR = dist
yield dist
main_module.PANEL_DIST_DIR = original
@pytest.fixture
def client():
from app.main import app
return TestClient(app)
def test_panel_root_returns_index(panel_dist, client):
resp = client.get("/panel")
assert resp.status_code == 200
assert "text/html" in resp.headers["content-type"]
assert "panel index" in resp.text
def test_panel_spa_fallback_returns_index(panel_dist, client):
resp = client.get("/panel/customer-groups")
assert resp.status_code == 200
assert "text/html" in resp.headers["content-type"]
assert "panel index" in resp.text
def test_panel_deep_route_fallback(panel_dist, client):
resp = client.get("/panel/customer-groups/123/chat")
assert resp.status_code == 200
assert "text/html" in resp.headers["content-type"]
assert "panel index" in resp.text
def test_panel_assets_returns_file(panel_dist, client):
resp = client.get("/panel/assets/app.js")
assert resp.status_code == 200
assert resp.text == "console.log('app')"
assert "javascript" in resp.headers["content-type"].lower()
def test_panel_missing_dist_returns_404(client, tmp_path, monkeypatch):
missing = tmp_path / "no-dist"
monkeypatch.setattr(main_module, "PANEL_DIST_DIR", missing)
resp = client.get("/panel")
assert resp.status_code == 404
def test_panel_path_traversal_not_leak(panel_dist, client):
resp = client.get("/panel/%2e%2e/app/main.py")
# 不允许返回越界文件内容(应回退 index.html 或 404)
assert "Agent Admin" not in resp.text
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!