refactor: 开发启动器仅运行 Metrix 主体
This commit is contained in:
@@ -170,7 +170,7 @@ python tools/migrate_database.py schema-rollback --url "sqlite:///../runtime/met
|
||||
|
||||
## 8. 测试和检查
|
||||
|
||||
先按根 `README.md` 准备根 `.venv` 与各插件自己的环境;不要另建 `server/.venv`。`python dev.py --check` 检查主平台及可选 CapacityReport 依赖;默认四进程端口为 `8000/5173/9081/5174`,`--without-capacity-report` 仅启动主平台。启动器不安装依赖,修改代码后同步 README 和 MemRelay 对应条目。
|
||||
当前只开发和测试 Metrix 主体(`server/`、`web/`),暂停读取、修改、测试和启动 `plugins/` 内的项目。按根 `README.md` 准备根 `.venv` 与 `web` 依赖,不另建 `server/.venv`,不要求初始化子模块。`python dev.py` 只启动主体 API `8000` 与 Web `5173`,`--check` 只预检主体依赖;启动器不安装依赖。修改实现后同步 README 和 MemRelay 对应条目。
|
||||
|
||||
新增或修改功能后,在根目录 PowerShell 执行:
|
||||
|
||||
@@ -187,7 +187,7 @@ npm.cmd --prefix web run test:regression:install # 首次安装 Chromium
|
||||
npm.cmd --prefix web run test:regression
|
||||
```
|
||||
|
||||
`npm.cmd --prefix web run verify` 可一次完成 smoke、类型检查/构建和浏览器回归。pytest 输出在 `Temp/tests/pytest`,Playwright 输出在 `Temp/tests/playwright`,浏览器缓存为 `Temp/cache/ms-playwright`;临时文件和下载缓存只放项目 `Temp/` 或 PI scratch。测试使用临时 SQLite 和模拟外部依赖,不读取业务 `runtime/install.json`。插件单测在各自目录用其 `.venv` 执行 `python -m unittest discover -s tests -v`;真实数据库集成测试必须使用隔离数据库。
|
||||
`npm.cmd --prefix web run verify` 可一次完成主体 smoke、类型检查/构建和浏览器回归。pytest 输出在 `Temp/tests/pytest`,Playwright 输出在 `Temp/tests/playwright`,浏览器缓存为 `Temp/cache/ms-playwright`;临时文件和下载缓存只放项目 `Temp/` 或 PI scratch。测试使用临时 SQLite 和模拟外部依赖,不读取业务 `runtime/install.json`。插件不纳入当前验证范围;真实数据库集成验证必须使用隔离数据库。
|
||||
|
||||
## 9. 容器管理开发边界
|
||||
|
||||
|
||||
@@ -37,6 +37,8 @@ runtime/ 本地运行时目录,默认不提交
|
||||
- [`DEVELOPMENT_GUIDE.md`](DEVELOPMENT_GUIDE.md):新增模块、页面、权限、迁移和交互规范。
|
||||
- MemRelay:项目记忆、决策和进度的唯一维护入口;修改实现后同步更新对应条目,历史部署记录不代表当前线上状态。
|
||||
|
||||
当前开发聚焦 Metrix 主体(`server/` 与 `web/`)。`plugins/` 暂时保留,但不参与日常环境准备、启动、测试和维护;开发主平台无需初始化 Git 子模块。
|
||||
|
||||
## 环境要求
|
||||
|
||||
- Python 3.11 或兼容版本
|
||||
@@ -50,37 +52,26 @@ runtime/ 本地运行时目录,默认不提交
|
||||
主平台 FastAPI 固定为已验证的 `0.136.3`;新版 `include_router()` 行为变化会影响旧 OpenAPI 操作名迁移,升级前需通过相应回归测试。
|
||||
|
||||
```powershell
|
||||
git submodule update --init --recursive
|
||||
python -m venv .venv
|
||||
.\.venv\Scripts\python.exe -m pip install -r server/requirements.txt
|
||||
npm.cmd --prefix web ci
|
||||
|
||||
# 可选 CapacityReport;默认联合启动需要准备它自己的环境
|
||||
python -m venv plugins/CapacityReport/.venv
|
||||
.\plugins\CapacityReport\.venv\Scripts\python.exe -m pip install -r plugins/CapacityReport/requirements.txt
|
||||
npm.cmd --prefix plugins/CapacityReport/frontend ci
|
||||
|
||||
# InterferenceETL 独立运行与单测环境,不由 dev.py 常驻启动
|
||||
python -m venv plugins/InterferenceETL/.venv
|
||||
.\plugins\InterferenceETL\.venv\Scripts\python.exe -m pip install -r plugins/InterferenceETL/requirements.txt
|
||||
python dev.py --check
|
||||
```
|
||||
|
||||
Linux/macOS 将 `Scripts/python.exe` 换成 `bin/python`。如果 `.venv` 的基础解释器已删除,应删除该失效环境后重新创建,不能仅以 `python.exe` 文件存在判断可用。已有 `uv` 时可用 `uv venv --python 3.13 .venv` 创建环境、`uv pip install --python .venv/Scripts/python.exe -r server/requirements.txt` 安装依赖(需要 `python -m pip` 时同时安装 `pip`);插件环境同理。不要在 `server/` 再维护重复虚拟环境。
|
||||
Linux/macOS 将 `Scripts/python.exe` 换成 `bin/python`。如果 `.venv` 的基础解释器已删除,应删除该失效环境后重新创建,不能仅以 `python.exe` 文件存在判断可用。已有 `uv` 时可用 `uv venv --python 3.13 .venv` 创建环境、`uv pip install --python .venv/Scripts/python.exe -r server/requirements.txt` 安装依赖(需要 `python -m pip` 时同时安装 `pip`)。不要在 `server/` 再维护重复虚拟环境。
|
||||
|
||||
开发模式:
|
||||
|
||||
```powershell
|
||||
python dev.py # Metrix + 可选 CapacityReport
|
||||
python dev.py --without-capacity-report # 仅 Metrix
|
||||
python dev.py --check # 只检查依赖,不启动服务、不安装依赖
|
||||
python dev.py # 启动 Metrix 主体
|
||||
python dev.py --check # 只检查主体依赖,不启动服务、不安装依赖
|
||||
```
|
||||
|
||||
默认最多启动四个进程:Metrix API `127.0.0.1:8000`、Web `127.0.0.1:5173`,CapacityReport API `127.0.0.1:9081`、Web `127.0.0.1:5174`。日志前缀分别为 `[backend]`、`[web]`、`[capa-api]`、`[capa-web]`;后端自动重载,前端 HMR。CapacityReport 不存在或依赖缺失时跳过并提示,不影响 Metrix。主平台启动失败会退出;启动阶段及运行阶段按 `Ctrl+C` 都会清理已启动的子进程。前端端口被占用时明确失败,不自动换端口。
|
||||
只启动两个进程:Metrix API `127.0.0.1:8000`、Web `127.0.0.1:5173`,日志前缀分别为 `[backend]`、`[web]`;后端自动重载,前端 HMR。任一进程启动失败或退出时关闭已启动的服务;启动阶段及运行阶段按 `Ctrl+C` 都会清理子进程。前端端口被占用时明确失败,不自动换端口。
|
||||
|
||||
`dev.py` 只启动已准备的环境,不在启动途中创建环境或联网安装依赖。修改 `METRIX_HOST` / `METRIX_PORT` 时会同步设置前端代理;分开启动时可设置 `VITE_API_TARGET`(默认 `http://127.0.0.1:8000`)。后端可在 `server/` 用根环境的 Python 执行 `main.py`,前端在 `web/` 执行 `npm run dev`。开发访问 `http://127.0.0.1:5173/install` 初始化;测试必须用独立临时目录和数据库,勿复用业务 `runtime/`。
|
||||
|
||||
自定义后端端口不得为主前端端口 `5173`;与 CapacityReport 的 `9081/5174` 冲突时会提示并跳过插件服务。
|
||||
自定义后端端口不得为主前端端口 `5173`;其余端口需确保未被其他服务占用。
|
||||
|
||||
单端口部署(前后端同一端口):
|
||||
|
||||
@@ -239,14 +230,11 @@ server/app/modules/<module>/
|
||||
.\.venv\Scripts\python.exe -m pytest
|
||||
```
|
||||
|
||||
子模块测试分别在各自目录执行 `.venv\Scripts\python.exe -m unittest discover -s tests -v`。CapacityReport 的真实 MySQL 用例仅在配置 `CAPACITYREPORT_TEST_MYSQL_HOST` 后启用,使用隔离测试数据库。
|
||||
|
||||
前端:
|
||||
|
||||
```powershell
|
||||
npm.cmd --prefix web run test:regression:install
|
||||
npm.cmd --prefix web run verify
|
||||
npm.cmd --prefix plugins/CapacityReport/frontend run build
|
||||
```
|
||||
|
||||
`verify` 依次执行模块 smoke、类型检查与生产构建、Playwright 回归。pytest 临时目录为 `Temp/tests/pytest`,Playwright 输出为 `Temp/tests/playwright`,浏览器安装与运行共用 `Temp/cache/ms-playwright`(可用 `PLAYWRIGHT_BROWSERS_PATH` 覆盖)。这些目录均不提交;请勿把测试产物放入业务 `runtime/`。
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
"""Run Metrix and the optional CapacityReport services in one terminal.
|
||||
"""Run the Metrix backend and frontend in one terminal.
|
||||
|
||||
python dev.py # Metrix :8000/:5173 + CapacityReport :9081/:5174
|
||||
python dev.py --without-capacity-report # Metrix only
|
||||
python dev.py --check # check environments without starting services
|
||||
python dev.py # Metrix API :8000 + web :5173
|
||||
python dev.py --check # check the main environment without starting services
|
||||
|
||||
Prepare the Python environments and locked npm dependencies as documented in README.md.
|
||||
Prepare the root Python environment and web dependencies as documented in README.md.
|
||||
This launcher never installs dependencies. Ctrl+C stops every process it started.
|
||||
"""
|
||||
|
||||
@@ -27,10 +26,6 @@ IS_WINDOWS = os.name == "nt"
|
||||
PYTHON_RELATIVE = Path("Scripts/python.exe" if IS_WINDOWS else "bin/python")
|
||||
VENV_PYTHON = ROOT / ".venv" / PYTHON_RELATIVE
|
||||
BACKEND_HOST = os.environ.get("METRIX_HOST", "127.0.0.1")
|
||||
CAPA_DIR = ROOT / "plugins" / "CapacityReport"
|
||||
CAPA_VENV_PYTHON = CAPA_DIR / ".venv" / PYTHON_RELATIVE
|
||||
CAPA_BACKEND_PORT = 9081
|
||||
CAPA_WEB_PORT = 5174
|
||||
|
||||
_processes: list[tuple[str, subprocess.Popen]] = []
|
||||
_stopping = threading.Event()
|
||||
@@ -130,7 +125,7 @@ def _stop_all() -> None:
|
||||
log(name, f"could not confirm process stopped: {type(exc).__name__}")
|
||||
|
||||
|
||||
def _wait_for_http(proc_name: str, url: str, timeout: float = 60.0, accepted_statuses: tuple[int, ...] = (200,)) -> bool:
|
||||
def _wait_for_http(proc_name: str, url: str, timeout: float = 60.0) -> bool:
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if _stopping.is_set():
|
||||
@@ -139,35 +134,14 @@ def _wait_for_http(proc_name: str, url: str, timeout: float = 60.0, accepted_sta
|
||||
return False
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=2) as response:
|
||||
if response.status in accepted_statuses:
|
||||
if response.status == 200:
|
||||
return True
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code in accepted_statuses:
|
||||
return True
|
||||
time.sleep(0.4)
|
||||
except (urllib.error.URLError, OSError):
|
||||
time.sleep(0.4)
|
||||
return False
|
||||
|
||||
|
||||
def _start_capacity_report(node: str) -> None:
|
||||
_spawn(
|
||||
"capa-api",
|
||||
[str(CAPA_VENV_PYTHON), "-m", "uvicorn", "app.main:app", "--reload", "--host", "127.0.0.1", "--port", str(CAPA_BACKEND_PORT)],
|
||||
CAPA_DIR,
|
||||
)
|
||||
log("capa-api", f"starting -> http://127.0.0.1:{CAPA_BACKEND_PORT} (auto-reload)")
|
||||
# 未登录配置请求返回 401 即可证明应用就绪,避免健康接口的数据库检查拖慢启动。
|
||||
if not _wait_for_http("capa-api", f"http://127.0.0.1:{CAPA_BACKEND_PORT}/api/config", timeout=90.0, accepted_statuses=(401,)):
|
||||
log("capa-web", "backend unavailable; skipping CapacityReport frontend")
|
||||
return
|
||||
directory = CAPA_DIR / "frontend"
|
||||
vite = directory / "node_modules/vite/bin/vite.js"
|
||||
_spawn("capa-web", [node, str(vite), "--host", "127.0.0.1", "--port", str(CAPA_WEB_PORT), "--strictPort"], directory)
|
||||
log("capa-web", f"starting -> http://127.0.0.1:{CAPA_WEB_PORT} (hot reload)")
|
||||
|
||||
|
||||
def _run_services(node: str, backend_port: int, include_capacity: bool) -> int:
|
||||
def _run_services(node: str, backend_port: int) -> int:
|
||||
connect_host = "127.0.0.1" if BACKEND_HOST == "0.0.0.0" else BACKEND_HOST
|
||||
backend_url = f"http://{connect_host}:{backend_port}"
|
||||
try:
|
||||
@@ -181,24 +155,13 @@ def _run_services(node: str, backend_port: int, include_capacity: bool) -> int:
|
||||
web_env = {**os.environ, "VITE_API_TARGET": backend_url}
|
||||
_spawn("web", [node, str(web_dir / "node_modules/vite/bin/vite.js"), "--host", "127.0.0.1", "--port", "5173", "--strictPort"], web_dir, web_env)
|
||||
log("web", "starting -> http://127.0.0.1:5173 (hot reload)")
|
||||
if include_capacity:
|
||||
try:
|
||||
_start_capacity_report(node)
|
||||
except OSError as exc:
|
||||
log("capa-api", f"could not start optional services: {type(exc).__name__}; Metrix keeps running")
|
||||
log("dev", "press Ctrl+C to stop all services")
|
||||
critical = {"backend", "web"}
|
||||
reported: set[str] = set()
|
||||
while not _stopping.is_set():
|
||||
for name, process in _processes:
|
||||
code = process.poll()
|
||||
if code is None or name in reported:
|
||||
continue
|
||||
reported.add(name)
|
||||
if name in critical:
|
||||
if code is not None:
|
||||
log(name, f"exited with code {code}; shutting down all services")
|
||||
return code or 1
|
||||
log(name, f"exited with code {code}; other services keep running")
|
||||
time.sleep(0.5)
|
||||
except KeyboardInterrupt:
|
||||
log("dev", "received Ctrl+C")
|
||||
@@ -212,7 +175,6 @@ def _run_services(node: str, backend_port: int, include_capacity: bool) -> int:
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--without-capacity-report", action="store_true", help="start/check only Metrix")
|
||||
parser.add_argument("--check", action="store_true", help="check dependencies without starting services")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
@@ -231,21 +193,11 @@ def main(argv: list[str] | None = None) -> int:
|
||||
if not ready:
|
||||
log("dev", "Prepare environments using the Quick Start in README.md; then run python dev.py --check")
|
||||
return 1
|
||||
include_capacity = not args.without_capacity_report and (CAPA_DIR / "app/main.py").is_file()
|
||||
if include_capacity and backend_port in {CAPA_BACKEND_PORT, CAPA_WEB_PORT}:
|
||||
log("dev", "METRIX_PORT conflicts with CapacityReport; skipping optional services")
|
||||
include_capacity = False
|
||||
if include_capacity:
|
||||
capacity_ready = _python_ready("capa-api", CAPA_VENV_PYTHON, ("uvicorn", "fastapi", "pandas", "openpyxl", "pymysql", "requests", "paramiko", "chardet"))
|
||||
capacity_ready = _frontend_ready("capa-web", CAPA_DIR / "frontend", node) and capacity_ready
|
||||
if not capacity_ready:
|
||||
log("dev", "CapacityReport unavailable; prepare its environments using README.md; Metrix remains available")
|
||||
include_capacity = False
|
||||
if args.check:
|
||||
log("dev", f"Metrix ready; CapacityReport {'ready' if include_capacity else 'skipped'}; no services started")
|
||||
log("dev", "Metrix backend and frontend ready; no services started")
|
||||
return 0
|
||||
assert node is not None
|
||||
return _run_services(node, backend_port, include_capacity)
|
||||
return _run_services(node, backend_port)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -32,7 +32,7 @@ def test_startup_failure_stops_already_started_process(launcher, monkeypatch, tm
|
||||
|
||||
monkeypatch.setattr(launcher, "_wait_for_http", fail)
|
||||
try:
|
||||
result = launcher._run_services("node", 8000, False)
|
||||
result = launcher._run_services("node", 8000)
|
||||
assert result == (0 if interruption is KeyboardInterrupt else 1)
|
||||
assert process.poll() is not None
|
||||
finally:
|
||||
@@ -47,7 +47,7 @@ def test_unready_backend_does_not_start_frontend(launcher, monkeypatch):
|
||||
monkeypatch.setattr(launcher, "_spawn", lambda name, *args: started.append(name))
|
||||
monkeypatch.setattr(launcher, "_wait_for_http", lambda *args: False)
|
||||
monkeypatch.setattr(launcher, "_stop_all", lambda: stopped.append(True))
|
||||
assert launcher._run_services("node", 8000, True) == 1
|
||||
assert launcher._run_services("node", 8000) == 1
|
||||
assert started == ["backend"]
|
||||
assert stopped == [True]
|
||||
|
||||
@@ -69,15 +69,18 @@ def test_custom_backend_port_reaches_vite_proxy_and_cleanup(launcher, monkeypatc
|
||||
monkeypatch.setattr(launcher, "_wait_for_http", lambda *args: True)
|
||||
monkeypatch.setattr(launcher.time, "sleep", interrupt)
|
||||
monkeypatch.setattr(launcher, "_stop_all", lambda: stopped.append(True))
|
||||
assert launcher._run_services("node", 8123, False) == 0
|
||||
assert launcher._run_services("node", 8123) == 0
|
||||
assert set(environments) == {"backend", "web"}
|
||||
assert environments["backend"]["METRIX_PORT"] == "8123"
|
||||
assert environments["web"]["VITE_API_TARGET"] == "http://127.0.0.1:8123"
|
||||
assert stopped == [True]
|
||||
|
||||
|
||||
def test_check_does_not_start_or_install_services(launcher, monkeypatch):
|
||||
monkeypatch.setattr(launcher, "_python_ready", lambda *args: True)
|
||||
monkeypatch.setattr(launcher, "_frontend_ready", lambda *args: True)
|
||||
checked = []
|
||||
frontends = []
|
||||
monkeypatch.setattr(launcher, "_python_ready", lambda name, python, *args: checked.append((name, python)) or True)
|
||||
monkeypatch.setattr(launcher, "_frontend_ready", lambda name, directory, node: frontends.append((name, directory)) or True)
|
||||
monkeypatch.setattr(launcher.shutil, "which", lambda _: "node")
|
||||
|
||||
def unexpected(*args, **kwargs):
|
||||
@@ -85,7 +88,9 @@ def test_check_does_not_start_or_install_services(launcher, monkeypatch):
|
||||
|
||||
monkeypatch.setattr(launcher, "_run_services", unexpected)
|
||||
monkeypatch.setattr(launcher.subprocess, "run", unexpected)
|
||||
assert launcher.main(["--check", "--without-capacity-report"]) == 0
|
||||
assert launcher.main(["--check"]) == 0
|
||||
assert checked == [("backend", launcher.VENV_PYTHON)]
|
||||
assert frontends == [("web", launcher.ROOT / "web")]
|
||||
|
||||
|
||||
def test_invalid_port_is_reported_before_startup(launcher, monkeypatch):
|
||||
@@ -127,17 +132,15 @@ def test_cleanup_timeout_forces_termination(launcher, monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("port", ["9081", "5174"])
|
||||
def test_backend_port_collision_skips_optional_plugin(launcher, monkeypatch, tmp_path, port):
|
||||
(tmp_path / "app").mkdir()
|
||||
(tmp_path / "app/main.py").touch()
|
||||
checked = []
|
||||
monkeypatch.setattr(launcher, "CAPA_DIR", tmp_path)
|
||||
def test_other_backend_ports_remain_available(launcher, monkeypatch, port):
|
||||
started = []
|
||||
monkeypatch.setattr(launcher.shutil, "which", lambda _: "node")
|
||||
monkeypatch.setenv("METRIX_PORT", port)
|
||||
monkeypatch.setattr(launcher, "_python_ready", lambda name, *args: checked.append(name) or True)
|
||||
monkeypatch.setattr(launcher, "_python_ready", lambda *args: True)
|
||||
monkeypatch.setattr(launcher, "_frontend_ready", lambda *args: True)
|
||||
assert launcher.main(["--check"]) == 0
|
||||
assert checked == ["backend"]
|
||||
monkeypatch.setattr(launcher, "_run_services", lambda node, backend_port: started.append(backend_port) or 0)
|
||||
assert launcher.main([]) == 0
|
||||
assert started == [int(port)]
|
||||
|
||||
|
||||
def test_backend_cannot_use_primary_frontend_port(launcher, monkeypatch):
|
||||
|
||||
Reference in New Issue
Block a user