refactor: dev 脚本不再生成 .env,Docker 部署改走首次安装向导
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 直接启动,建库/迁移/建超管交由安装向导,杜绝默认口令。
This commit is contained in:
+99
-64
@@ -4,30 +4,31 @@
|
||||
# ///
|
||||
"""本地开发一键启动(纯本地,不使用 Docker)。
|
||||
|
||||
连接信息写在 scripts/config.yaml(本机 MySQL 8 / Redis)。
|
||||
流程:生成 .env -> 构建 shared -> (MySQL 可连则确保库+迁移+种子)-> 同时启动 api/admin/client。
|
||||
数据库/Redis 连不上不会阻塞:只告警并继续启动——配置了就按配置跑,运行期由服务自行连接;
|
||||
想重新配置可用 --install-mode 走安装向导。
|
||||
启动契约与生产一致:**唯一配置来源是仓库根目录的 `.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 # 完整启动
|
||||
python scripts/dev.py --install # 先 pnpm install
|
||||
python scripts/dev.py --no-seed # 跳过种子数据
|
||||
python scripts/dev.py --install-mode # 调试首次安装向导(API + admin,不迁移/种子)
|
||||
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
|
||||
|
||||
INSTALL_DEV_ENV_FILE = Path(__file__).resolve().parent.parent / "apps/api/.env.install-dev"
|
||||
|
||||
from _lib import (
|
||||
build_env,
|
||||
ROOT,
|
||||
create_kill_job,
|
||||
ensure_mysql_database,
|
||||
ensure_pnpm,
|
||||
install_console_ctrl_handler,
|
||||
kill_project_servers,
|
||||
@@ -36,78 +37,105 @@ from _lib import (
|
||||
run,
|
||||
run_retry,
|
||||
stop_all,
|
||||
wait_db_auth,
|
||||
wait_port,
|
||||
write_env,
|
||||
)
|
||||
|
||||
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:]
|
||||
install_mode = "--install-mode" in args
|
||||
force_install = "--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(不污染仓库根 .env),退出调试后由脚本清理
|
||||
env["ARTVERIS_ENV_FILE"] = str(INSTALL_DEV_ENV_FILE).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)
|
||||
# 清理上次残留服务(含 idle 的 nest --watch 监视器,避免其重启抢占端口)
|
||||
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_ENV_FILE.exists():
|
||||
|
||||
# 旧版自动生成的 .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")
|
||||
|
||||
# 1. 构建共享包 + 生成 Prisma 客户端(均不需要数据库)
|
||||
# 构建共享包 + 生成 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 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(
|
||||
f"[artveris] 未连接到 MySQL({db['host']}:{db['port']}),跳过迁移/种子,仍继续启动。"
|
||||
"若已在 config.yaml 配置数据库,请启动 MySQL 后重跑;服务运行期需要可用的 MySQL/Redis。"
|
||||
"[artveris] 未探测到可连接的 MySQL(读取 .env 的 DATABASE_URL),"
|
||||
"跳过迁移/种子,仍继续启动;服务运行期需要可用的 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()
|
||||
@@ -123,25 +151,32 @@ def main() -> None:
|
||||
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] 安装向导调试服务启动中:")
|
||||
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(" 说明 : 安装成功后 API 会退出;重新运行普通 python scripts/dev.py 可进入正式开发模式。")
|
||||
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)")
|
||||
|
||||
Reference in New Issue
Block a user