Files
Artveris/scripts/dev.py
T

161 lines
6.7 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)。
连接信息写在 scripts/config.yaml(本机 MySQL 8 / Redis)。
流程:生成 .env -> 构建 shared -> (MySQL 可连则确保库+迁移+种子)-> 同时启动 api/admin/client。
数据库/Redis 连不上不会阻塞:只告警并继续启动——配置了就按配置跑,运行期由服务自行连接;
想重新配置可用 --install-mode 走安装向导。
用法:
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. 构建共享包 + 生成 Prisma 客户端(均不需要数据库)
run("pnpm build:shared")
if not run_retry("pnpm --filter @artveris/api prisma:generate", attempts=4, delay=2):
print("[artveris] 警告:prisma generate 仍失败(客户端可能已存在),继续启动 …")
# 2. 数据库初始化为 best-effort,绝不阻塞启动:
# - MySQL 可连:确保库存在 + 迁移 + 种子(配置了就按配置自动初始化);
# - 连不上:仅告警并继续启动(是否配置/连接交给运行期;想改配置可用安装向导:
# python scripts/dev.py --install-mode)。
if install_mode:
print("[artveris] install-mode:跳过 prisma migrate/seed,由安装向导完成首次初始化。")
else:
db_ready = wait_port(db["host"], int(db["port"]), 3) and wait_db_auth(
db["host"], db["port"], db["user"], db["password"], timeout=6
)
if db_ready and ensure_mysql_database(db["host"], db["port"], db["user"], db["password"], db["name"]):
run("pnpm --filter @artveris/api prisma:deploy")
if "--no-seed" not in args:
run("pnpm --filter @artveris/api seed", check=False)
else:
print(
f"[artveris] 未连接到 MySQL({db['host']}:{db['port']}),跳过迁移/种子,仍继续启动。"
"若已在 config.yaml 配置数据库,请启动 MySQL 后重跑;服务运行期需要可用的 MySQL/Redis。"
)
if not wait_port(rds["host"], int(rds["port"]), 3):
print(f"[artveris] 未连接到 Redis({rds['host']}:{rds['port']}),队列/缓存在 Redis 启动前不可用。")
# 3. 同时启动前后端
# 加入 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()