- 本地 dev 保持前台模型、不引入 PM2;--stop 复用 kill_project_servers 一键停止 - 无 .env 时监听根 .env 出现作为安装成功信号,自动停安装 API 并以正式模式重启 api/client,避开安装中重启 - 安装 API 在 dev 模式下不再退出、迁移失败透传真实原因;前端提交后统一轮询就绪再进后台
250 lines
10 KiB
Python
250 lines
10 KiB
Python
# /// script
|
|
# requires-python = ">=3.9"
|
|
# dependencies = ["pyyaml", "psutil", "pymysql"]
|
|
# ///
|
|
"""本地开发一键启动(纯本地,不使用 Docker)。
|
|
|
|
启动契约与生产一致:**唯一配置来源是仓库根目录的 `.env`**。
|
|
- 没有 `.env`(或检测到旧版自动生成的 `.env`):进入安装向导(API 安装模式 + admin),
|
|
不连接数据库/Redis,不迁移不种子;在向导页填写本机 MySQL/Redis 后写入根 `.env`。
|
|
- 已有 `.env`:正常开发——构建 shared + prisma generate,探测 DB 可连则迁移+种子,
|
|
然后同时启动 api/admin/client。dev.py 不再自动生成 `.env`。
|
|
|
|
安装完成后自动切换:无 `.env` 进入安装向导后,脚本会持续监听根 `.env`;
|
|
向导提交成功(后端最后一步才写 `.env`)后自动停掉安装 API、以正式模式重启 api/client
|
|
(保留 admin 页面不断连),无需手动再次运行本脚本。失败的安装尝试不写 `.env`,
|
|
因此不会在安装过程中误触发重启。
|
|
|
|
`scripts/config.yaml` 仅用于:三端端口 + 安装向导 MySQL/Redis 预填充 + 迁移前的连通探测。
|
|
|
|
用法:
|
|
python scripts/dev.py # 有 .env 走完整开发;无 .env 自动进安装向导(装完自动切正式模式)
|
|
python scripts/dev.py --stop # 停止所有本地开发服务(api/admin/client)后退出
|
|
python scripts/dev.py --install # 先 pnpm install
|
|
python scripts/dev.py --no-seed # 跳过种子数据
|
|
python scripts/dev.py --install-mode # 强制安装向导调试(写临时 .env,不污染根 .env,不自动切换)
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import sys
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
|
|
from _lib import (
|
|
ROOT,
|
|
create_kill_job,
|
|
ensure_pnpm,
|
|
free_port,
|
|
install_console_ctrl_handler,
|
|
kill_project_servers,
|
|
load_config,
|
|
popen,
|
|
run,
|
|
run_retry,
|
|
stop_all,
|
|
stop_proc_tree,
|
|
wait_port,
|
|
)
|
|
|
|
ENV_FILE = ROOT / ".env"
|
|
INSTALL_DEV_ENV_FILE = ROOT / "apps/api/.env.install-dev"
|
|
AUTOGEN_MARKER = "由 scripts/config.yaml 自动生成"
|
|
|
|
|
|
def local_host(host: str) -> str:
|
|
return "127.0.0.1" if str(host) in {"localhost", "127.0.0.1"} else str(host)
|
|
|
|
|
|
def is_autogenerated_env(path: Path) -> bool:
|
|
"""旧版脚本自动生成的 .env(首行带标记)不再使用,检测到即视为需重新配置。"""
|
|
try:
|
|
with open(path, "r", encoding="utf-8") as f:
|
|
return AUTOGEN_MARKER in f.readline()
|
|
except OSError:
|
|
return False
|
|
|
|
|
|
def parse_database_endpoint(path: Path) -> tuple[str, int] | None:
|
|
"""从 .env 的 DATABASE_URL 解析 host:port,用于迁移前的连通探测。"""
|
|
try:
|
|
text = path.read_text(encoding="utf-8")
|
|
except OSError:
|
|
return None
|
|
for raw in text.splitlines():
|
|
line = raw.strip()
|
|
if not line.startswith("DATABASE_URL"):
|
|
continue
|
|
value = line.split("=", 1)[1].strip().strip('"').strip("'")
|
|
m = re.search(r"@([^/:]+):(\d+)/", value)
|
|
if m:
|
|
return m.group(1), int(m.group(2))
|
|
return None
|
|
|
|
|
|
def install_env(cfg: dict, env_file: Path) -> dict[str, str]:
|
|
"""安装向导子进程环境变量:强制安装模式 + 本机连接信息预填充。"""
|
|
db, rds, app = cfg["database"], cfg["redis"], cfg["app"]
|
|
return {
|
|
"ARTVERIS_INSTALL_MODE": "1",
|
|
"ARTVERIS_ENV_FILE": str(env_file).replace("\\", "/"),
|
|
"INSTALL_PREFILL_SECRETS": "1",
|
|
"INSTALL_MYSQL_HOST": local_host(db["host"]),
|
|
"INSTALL_MYSQL_PORT": str(db["port"]),
|
|
"INSTALL_MYSQL_PASSWORD": str(db.get("password", "")),
|
|
"INSTALL_REDIS_HOST": local_host(rds["host"]),
|
|
"INSTALL_REDIS_PORT": str(rds["port"]),
|
|
"INSTALL_REDIS_PASSWORD": str(rds.get("password", "")),
|
|
"MYSQL_DATABASE": db["name"],
|
|
"MYSQL_USER": db["user"],
|
|
"API_PORT": str(app["api_port"]),
|
|
}
|
|
|
|
|
|
def wait_for_install_env(env_file: Path, api_proc, poll: float = 1.0) -> bool:
|
|
"""安装模式下轮询等待根 .env 生成(= 安装成功)。
|
|
|
|
后端在数据库迁移、建超管全部成功后,最后一步才写 .env;失败尝试不写文件,
|
|
填写向导期间也不写。因此「文件出现且非空」是安全的完成信号,天然避开安装中重启。
|
|
期间若安装 API 进程意外退出则返回 False。
|
|
"""
|
|
while True:
|
|
try:
|
|
if env_file.exists() and env_file.stat().st_size > 0:
|
|
time.sleep(1.0) # 稍等确保写入完整
|
|
return True
|
|
except OSError:
|
|
pass
|
|
if api_proc.poll() is not None:
|
|
return False
|
|
time.sleep(poll)
|
|
|
|
|
|
def main() -> None:
|
|
args = sys.argv[1:]
|
|
force_install = "--install-mode" in args
|
|
cfg = load_config()
|
|
app = cfg["app"]
|
|
ports = [app["api_port"], app["admin_port"], app["client_port"]]
|
|
|
|
# --stop:仅停止本地开发服务后退出,不启动任何东西
|
|
if "--stop" in args:
|
|
print("[artveris] 停止所有本地开发服务(api/admin/client)…")
|
|
kill_project_servers(ports=ports)
|
|
print("[artveris] 已停止。")
|
|
return
|
|
|
|
# 清理上次残留服务(含 idle 的 nest --watch 监视器,避免其重启抢占端口)
|
|
kill_project_servers(ports=ports)
|
|
time.sleep(1.5)
|
|
|
|
# 旧版自动生成的 .env 不再使用:删除后转由安装向导重新配置
|
|
if ENV_FILE.exists() and is_autogenerated_env(ENV_FILE):
|
|
print("[artveris] 检测到旧版自动生成的 .env,已删除,将进入安装向导重新配置。")
|
|
ENV_FILE.unlink()
|
|
|
|
install_mode = force_install or not ENV_FILE.exists()
|
|
if force_install and INSTALL_DEV_ENV_FILE.exists():
|
|
INSTALL_DEV_ENV_FILE.unlink()
|
|
|
|
ensure_pnpm()
|
|
if "--install" in args:
|
|
run("pnpm install")
|
|
|
|
# 构建共享包 + 生成 Prisma 客户端(均不需要数据库)
|
|
run("pnpm build:shared")
|
|
if not run_retry("pnpm --filter @artveris/api prisma:generate", attempts=4, delay=2):
|
|
print("[artveris] 警告:prisma generate 仍失败(客户端可能已存在),继续启动 …")
|
|
|
|
if not install_mode:
|
|
# 正常开发:.env 已存在(安装向导或手动写入),迁移/种子为 best-effort,不阻塞启动
|
|
endpoint = parse_database_endpoint(ENV_FILE)
|
|
if endpoint and wait_port(endpoint[0], endpoint[1], 3):
|
|
run("pnpm --filter @artveris/api prisma:deploy", check=False)
|
|
if "--no-seed" not in args:
|
|
run("pnpm --filter @artveris/api seed", check=False)
|
|
else:
|
|
print(
|
|
"[artveris] 未探测到可连接的 MySQL(读取 .env 的 DATABASE_URL),"
|
|
"跳过迁移/种子,仍继续启动;服务运行期需要可用的 MySQL/Redis。"
|
|
)
|
|
|
|
job = create_kill_job()
|
|
procs: list = []
|
|
_stop_lock = threading.Lock()
|
|
_stopped = {"done": False}
|
|
|
|
def _cleanup() -> None:
|
|
with _stop_lock:
|
|
if _stopped["done"]:
|
|
return
|
|
_stopped["done"] = True
|
|
print("\n[artveris] 正在停止所有服务 …")
|
|
stop_all(procs)
|
|
kill_project_servers()
|
|
print("[artveris] 已停止全部服务。")
|
|
|
|
install_console_ctrl_handler(_cleanup)
|
|
|
|
def start_full_dev() -> None:
|
|
"""以正式开发模式启动 api/client(admin 若未在跑则一并启动)。"""
|
|
procs.append(popen("pnpm dev:api", job=job))
|
|
print(f"\n[artveris] 等待后端 API 就绪(http://localhost:{app['api_port']})…")
|
|
if wait_port("127.0.0.1", int(app["api_port"]), 90):
|
|
print("[artveris] 后端 API 已就绪")
|
|
else:
|
|
print("[artveris] 后端 API 等待超时,仍继续启动前端(稍后会自动恢复)")
|
|
procs.append(popen("pnpm dev:client", job=job))
|
|
print("\n[artveris] 开发服务启动中:")
|
|
print(f" 后端 API : http://localhost:{app['api_port']}/api (文档 /api/docs)")
|
|
print(f" 管理后台 : http://localhost:{app['admin_port']}")
|
|
print(f" C 端 : http://localhost:{app['client_port']}")
|
|
|
|
try:
|
|
if install_mode:
|
|
env_file = INSTALL_DEV_ENV_FILE if force_install else ENV_FILE
|
|
child_env = install_env(cfg, env_file)
|
|
api_proc = popen("pnpm dev:api", job=job, env=child_env)
|
|
procs.append(api_proc)
|
|
print(f"\n[artveris] 等待安装 API 就绪(http://localhost:{app['api_port']})…")
|
|
wait_port("127.0.0.1", int(app["api_port"]), 90)
|
|
procs.append(popen("pnpm dev:admin", job=job))
|
|
print("\n[artveris] 首次安装向导服务启动中:")
|
|
print(f" 安装向导 : http://localhost:{app['admin_port']} (admin 探测到未安装会自动进入安装向导)")
|
|
print(f" 安装 API : http://localhost:{app['api_port']}/api/install/status")
|
|
if force_install:
|
|
print(
|
|
" 说明 : 调试模式写入临时 "
|
|
f"{env_file.name},不自动切换;重新运行 python scripts/dev.py 进入正式模式。"
|
|
)
|
|
else:
|
|
print(" 说明 : 在向导页填写本机 MySQL/Redis 与管理员账号后提交,安装成功后自动进入正式开发模式。")
|
|
# 监听根 .env 出现(安装成功)→ 停掉安装 API、以正式模式重启(保留 admin 不断连)
|
|
if wait_for_install_env(ENV_FILE, api_proc):
|
|
print("\n[artveris] 检测到安装完成,自动切换到正式开发模式 …")
|
|
stop_proc_tree(api_proc)
|
|
free_port(int(app["api_port"]))
|
|
time.sleep(1.5)
|
|
if api_proc in procs:
|
|
procs.remove(api_proc)
|
|
# 迁移与建超管已在安装流程完成,此处不再迁移/种子(避免覆盖向导设置的管理员)
|
|
start_full_dev()
|
|
else:
|
|
print("[artveris] 安装 API 已退出(未检测到 .env),停止。")
|
|
else:
|
|
procs.append(popen("pnpm dev:admin", job=job))
|
|
start_full_dev()
|
|
|
|
print(" 按 Ctrl+C 退出全部。\n")
|
|
for p in procs:
|
|
p.wait()
|
|
except KeyboardInterrupt:
|
|
pass
|
|
finally:
|
|
_cleanup()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|