dev.py:无 .env/旧自动生成 .env 自动进安装向导(不连库),有 .env 才迁移+种子+起三端; popen 支持 env,移除 build_env/write_env/wait_db_auth/ensure_mysql_database,config.yaml 精简; build_docker 不再预置 DATABASE_URL/管理员,挂载 data/config 并注入安装预填充; entrypoint 直接启动,建库/迁移/建超管交由安装向导,杜绝默认口令。
196 lines
7.7 KiB
Python
196 lines
7.7 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`。
|
|
|
|
`scripts/config.yaml` 仅用于:三端端口 + 安装向导 MySQL/Redis 预填充 + 迁移前的连通探测。
|
|
|
|
用法:
|
|
python scripts/dev.py # 有 .env 走完整开发;无 .env 自动进安装向导
|
|
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,
|
|
install_console_ctrl_handler,
|
|
kill_project_servers,
|
|
load_config,
|
|
popen,
|
|
run,
|
|
run_retry,
|
|
stop_all,
|
|
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 main() -> None:
|
|
args = sys.argv[1:]
|
|
force_install = "--install-mode" in args
|
|
cfg = load_config()
|
|
app = cfg["app"]
|
|
|
|
# 清理上次残留服务(含 idle 的 nest --watch 监视器,避免其重启抢占端口)
|
|
ports = [app["api_port"], app["admin_port"], app["client_port"]]
|
|
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)
|
|
|
|
try:
|
|
if install_mode:
|
|
env_file = INSTALL_DEV_ENV_FILE if force_install else ENV_FILE
|
|
child_env = install_env(cfg, env_file)
|
|
procs.append(popen("pnpm dev:api", job=job, env=child_env))
|
|
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")
|
|
print(
|
|
" 说明 : 在向导页填写本机 MySQL/Redis 与管理员账号后提交;"
|
|
f"安装成功会写入 {env_file.name} 并退出 API。"
|
|
)
|
|
print(" 重新运行 python scripts/dev.py 即进入正式开发模式。")
|
|
else:
|
|
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))
|
|
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()
|