Files
Artveris/scripts/dev.py
T

171 lines
6.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# /// script
# requires-python = ">=3.9"
# dependencies = ["pyyaml", "psutil", "pymysql"]
# ///
"""本地开发一键启动(纯本地,不使用 Docker)。
前置:本机已安装并启动 MySQL 8 与 Redis,连接信息写在 scripts/config.yaml。
流程:生成 .env -> 确保本机数据库存在 -> 构建 shared -> 迁移+种子 -> 同时启动 api/admin/client。
用法:
python scripts/dev.py # 完整启动
python scripts/dev.py --install # 先 pnpm install
python scripts/dev.py --no-seed # 跳过种子数据
python scripts/dev.py --install-mode # 调试首次安装向导(API + admin,不迁移/种子)
"""
from __future__ import annotations
import shutil
import sys
import threading
import time
from pathlib import Path
INSTALL_DEV_RUNTIME_DIR = Path(__file__).resolve().parent.parent / "apps/api/runtime/install-dev"
from _lib import (
build_env,
create_kill_job,
ensure_mysql_database,
ensure_pnpm,
install_console_ctrl_handler,
kill_project_servers,
load_config,
popen,
run,
run_retry,
stop_all,
wait_db_auth,
wait_port,
write_env,
)
def local_host(host: str) -> str:
return "127.0.0.1" if str(host) in {"localhost", "127.0.0.1"} else str(host)
def main() -> None:
args = sys.argv[1:]
install_mode = "--install-mode" in args
cfg = load_config()
app = cfg["app"]
db, rds = cfg["database"], cfg["redis"]
env = build_env(cfg)
if install_mode:
env["ARTVERIS_INSTALL_MODE"] = "1"
env["ARTVERIS_RUNTIME_DIR"] = str(INSTALL_DEV_RUNTIME_DIR).replace("\\", "/")
env["INSTALL_PREFILL_SECRETS"] = "1"
env["INSTALL_MYSQL_HOST"] = local_host(db["host"])
env["INSTALL_MYSQL_PORT"] = str(db["port"])
env["INSTALL_MYSQL_PASSWORD"] = str(db.get("password", ""))
env["INSTALL_REDIS_HOST"] = local_host(rds["host"])
env["INSTALL_REDIS_PORT"] = str(rds["port"])
env["INSTALL_REDIS_PASSWORD"] = str(rds.get("password", ""))
write_env(env)
# 0. 清理上次残留服务(按命令行清掉 idle 的 nest --watch 监视器,避免其重启抢占端口;
# 同时解除对 Prisma 引擎 DLL 的占用,避免 generate EPERM)
ports = [app["api_port"], app["admin_port"], app["client_port"]]
kill_project_servers(ports=ports)
time.sleep(1.5)
if install_mode and INSTALL_DEV_RUNTIME_DIR.exists():
shutil.rmtree(INSTALL_DEV_RUNTIME_DIR)
ensure_pnpm()
if "--install" in args:
run("pnpm install")
# 1. 检查本机 MySQL / Redis 可达(不启动 Docker)
print(
f"[artveris] 使用本机数据源:MySQL {db['host']}:{db['port']} / "
f"Redis {rds['host']}:{rds['port']}(不使用 Docker)"
)
if not wait_port(db["host"], int(db["port"]), 20):
print(
f"[artveris] 无法连接 MySQL({db['host']}:{db['port']})。"
"请先在本机安装并启动 MySQL 8,并在 scripts/config.yaml 填写正确连接信息。"
)
sys.exit(1)
if not wait_port(rds["host"], int(rds["port"]), 15):
print(
f"[artveris] 无法连接 Redis({rds['host']}:{rds['port']})。"
"请先在本机安装并启动 Redis。"
)
sys.exit(1)
# 2. 鉴权就绪 + 确保业务库存在(库不存在则用该账号尝试创建)
if not wait_db_auth(db["host"], db["port"], db["user"], db["password"], timeout=30):
print("[artveris] 无法用 config.yaml 的账号登录 MySQL,请检查账号/密码是否正确。")
sys.exit(1)
if not ensure_mysql_database(db["host"], db["port"], db["user"], db["password"], db["name"]):
print("[artveris] 数据库未就绪,已中止(请先创建数据库或使用有建库权限的账号)。")
sys.exit(1)
# 3. 构建共享包
run("pnpm build:shared")
# 4. 数据库迁移 + 种子(generate 偶发被占用,自动重试)
if not run_retry("pnpm --filter @artveris/api prisma:generate", attempts=4, delay=2):
print("[artveris] 警告:prisma generate 仍失败(客户端可能已存在),继续启动 …")
if install_mode:
print("[artveris] install-mode:跳过 prisma migrate/seed,保留安装向导首次初始化流程。")
else:
run("pnpm --filter @artveris/api prisma:deploy")
if "--no-seed" not in args:
run("pnpm --filter @artveris/api seed", check=False)
# 5. 同时启动前后端
# 加入 KILL_ON_JOB_CLOSE 的 Job:本脚本无论如何退出,子进程都会被系统连带结束
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] 已停止全部服务。")
# OS 层兜底:Ctrl+C / Ctrl+Break / 关闭终端窗口 / 注销 / 关机 都会触发清理
install_console_ctrl_handler(_cleanup)
try:
# 先启动后端并等待其监听端口,再启动前端:
# 否则前端(及已打开的浏览器页)会在 API 首次编译完成前请求 /api,刷出无害但扰人的 ECONNREFUSED
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:admin", job=job))
if install_mode:
print("\n[artveris] 安装向导调试服务启动中:")
print(f" 安装向导 : http://localhost:{app['admin_port']} (admin 探测到未安装会自动进入安装向导)")
print(f" 安装 API : http://localhost:{app['api_port']}/api/install/status")
print(" 说明 : 安装成功后 API 会退出;重新运行普通 python scripts/dev.py 可进入正式开发模式。")
else:
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']}")
print(" 按 Ctrl+C 退出全部。\n")
for p in procs:
p.wait()
except KeyboardInterrupt:
pass
finally:
_cleanup()
if __name__ == "__main__":
main()