diff --git a/aidocs/project_context.md b/aidocs/project_context.md index 5ca5bb5..5ccc1b7 100644 --- a/aidocs/project_context.md +++ b/aidocs/project_context.md @@ -271,7 +271,9 @@ - 复用约定:列表用 `composables/useTablePage.ts` + `page table-page` + `n-data-table.table-fill flex-height`(关内置分页、外置 `n-pagination`,`pageSize=0` 不分页);上传用 `MediaUpload.vue`(单/少量)与 `MediaSorter.vue`(多图排序 captionable);`TraceCodePanel.vue` 复用于全局与档案内追溯码管理;`openMediaViewer.ts`=PhotoSwipe(带工具条);`utils/mediaUrl.ts` 规整媒体 URL。 - 主要页面 `views/`:Dashboard、Templates、Artworks/ArtworkEdit/ArtworkTraceCodes、TraceCodes、Outbound、Audit、QueryLogs、OperationLogs、Users、Settings、Profile、Login、Install(三步向导:基础→数据库→存储)。 - 安装页 `baseUrlHint`(中英):三行换行说明对外访问地址(域名 / IP:端口 / 本地默认);`.hint` 使用 `white-space: pre-line` 渲染 `\n`。 -- 安装页错误信息穿透(2026-07-09):`InstallService.testConnection/testStorage/install` 内部原先 `throw new Error(...)`,会被全局 `AllExceptionsFilter` 当作未知异常统一替换为「服务器内部错误」,导致安装页测试连接失败时前端只能看到通用报错、看不到真实原因(需翻服务端日志才能看到 `MySQL 连接失败:Authentication failed...`)。改为 `throw new BusinessException(ErrorCode.BAD_REQUEST, message)`,令真实 message 透传到响应体,前端 `Install.vue` 的 `post()` 已读取 `body.message` 直接展示;同时补全 Redis 测试连接的 try/catch 包装(原来无 catch,原始 ioredis 报错会以未包装 Error 形式再次被过滤器吞掉)、`assertMysql/assertRedis`(正式安装提交时用)与 `ensureDatabase`(无建库权限)均补充清晰中文前缀("MySQL 连接失败:""Redis 连接失败:""数据库「x」不存在,且当前账号无建库权限...")。这些错误文案延续既有约定为纯中文动态拼接(底层驱动报错本身多为英文技术细节,不做逐句 i18n,与既有 install 静态文案的双语约定不冲突)。已用直连接口验证:错误密码返回 400+真实 Prisma 报错、错误端口 Redis 返回 400+真实 ioredis 报错。 +- 安装页错误信息穿透(2026-07-09):`InstallService.testConnection/testStorage/install` 内部原先 `throw new Error(...)`,会被全局 `AllExceptionsFilter` 当作未知异常统一替换为「服务器内部错误」……已用直连接口验证。 +- 安装提交 JSON 解析失败(2026-07-09):根因是安装成功后 `process.exit(0)`(600ms)在本地 dev 环境掐断 HTTP 连接,前端 `res.json()` 收到空 body 报 `Unexpected end of JSON input`。修复:① `ARTVERIS_INSTALL_MODE=1` 本地安装调试不再 `process.exit`,保证 JSON 响应完整返回;生产环境延迟 2.5s 再退出供 PM2/Docker 重启。② `runPrismaMigrate` 失败改为 `BusinessException` 透传「数据库迁移失败:…」。③ `status()` 新增 `needsDevRestart`(本地 .env 已写但进程仍为 InstallAppModule)。④ `Install.vue` 用 `parseApiBody` 安全解析空/非法 JSON。 +- 本地 dev 进程管理:`--stop` + 安装后自动切换(2026-07-09,明确不引入 PM2):本地 dev 仍是「前台阻塞 + Job Object/控制台事件整树清理」模型,PM2 仅用于生产(build.py 的 `ecosystem.config.cjs`)。新增两点 PM2 式体验:① `python scripts/dev.py --stop`:复用 `kill_project_servers(ports)` 一键停掉 api/admin/client 后退出,零新依赖。② 安装完成自动切正式模式:无 `.env` 进入安装向导后,`dev.py` 用 `wait_for_install_env(ENV_FILE, api_proc)` 持续监听根 `.env` 出现——因后端在迁移+建超管全部成功后**最后一步**才写 `.env`,失败尝试与填写过程都不写,故「文件出现且非空」是安全的完成信号,**天然避开安装中重启**;一旦检测到即 `stop_proc_tree` 安装 API + `free_port(3000)`,保留 admin vite 不断连,以正式模式重启 `dev:api`+`dev:client`(不再迁移/种子,避免覆盖向导设置的管理员),随后 `p.wait()` 阻塞,Ctrl+C 仍整树清理。`--install-mode` 调试模式写临时 `.env.install-dev`、不自动切换(保留手动重run)。前端 `submit()` 相应简化为:成功后统一 `pollUntilReady()`(等 `installed && !needsDevRestart`)就绪跳后台,超时兜底提示 `doneLocalDev`。`dev.py` 导入补 `free_port`/`stop_proc_tree`。验证:api/admin build 通过、`py_compile` 通过。 ### apps/client(Vue3+Vite 移动优先溯源页) - 入口 `views/Trace.vue`(顶部媒体无缝轮播、防伪横幅、动态字段、时间轴节点媒体默认收缩、水印证书、区块链卡、i18n、暗色变量)+ `Home.vue`;`composables/openMediaViewer.ts`(PhotoSwipe,已弃用旧 MediaViewer.vue);hash 路由 `/trace/:code`,短链 `/t/{code}` 由 API 302。 diff --git a/apps/admin/src/locales/en-US.json b/apps/admin/src/locales/en-US.json index ff21941..a29a6ad 100644 --- a/apps/admin/src/locales/en-US.json +++ b/apps/admin/src/locales/en-US.json @@ -231,6 +231,9 @@ "cdnHint": "CDN acceleration URL; leave empty to disable (empty = serve from origin directly).", "failed": "Installation failed", "done": "Initialized. The service is restarting, please wait…", + "doneLocalDev": "Setup complete. If it does not open the admin automatically, rerun python scripts/dev.py to enter normal mode.", + "emptyResponse": "The server returned no valid response. Retry later or check server logs.", + "invalidResponse": "The server returned invalid data", "loadFailed": "Failed to read installation status", "testConnection": "Test", "testOk": "Connected", diff --git a/apps/admin/src/locales/zh-CN.json b/apps/admin/src/locales/zh-CN.json index 61cf55d..393f378 100644 --- a/apps/admin/src/locales/zh-CN.json +++ b/apps/admin/src/locales/zh-CN.json @@ -231,6 +231,9 @@ "cdnHint": "CDN 加速地址;如不启用可留空(为空则不开启,直接走源站)。", "failed": "安装失败", "done": "初始化完成,服务正在重启,请稍候…", + "doneLocalDev": "初始化完成。若未自动进入后台,请重新运行 python scripts/dev.py 进入正式模式。", + "emptyResponse": "服务器未返回有效响应,请稍后重试或查看服务端日志", + "invalidResponse": "服务器返回了无效数据", "loadFailed": "读取安装状态失败", "testConnection": "测试连接", "testOk": "连接成功", diff --git a/apps/admin/src/views/Install.vue b/apps/admin/src/views/Install.vue index 96c8f18..5a0515e 100644 --- a/apps/admin/src/views/Install.vue +++ b/apps/admin/src/views/Install.vue @@ -225,6 +225,41 @@ function goAdmin(): void { location.href = '/admin'; } +interface ApiBody { + code: number; + message?: string; + data?: { + installed?: boolean; + needsDevRestart?: boolean; + message?: string; + restartRequired?: boolean; + defaults?: Record; + }; +} + +async function parseApiBody(res: Response): Promise { + const text = await res.text(); + if (!text.trim()) return null; + try { + return JSON.parse(text) as ApiBody; + } catch { + throw new Error(tt('invalidResponse')); + } +} + +async function fetchInstallStatus(): Promise<{ installed: boolean; needsDevRestart: boolean }> { + try { + const res = await fetch('/api/install/status'); + const body = await parseApiBody(res); + return { + installed: Boolean(body?.data?.installed), + needsDevRestart: Boolean(body?.data?.needsDevRestart), + }; + } catch { + return { installed: false, needsDevRestart: false }; + } +} + async function post(path: string, payload: Record): Promise<{ ok: boolean; msg: string }> { try { const res = await fetch(path, { @@ -232,7 +267,8 @@ async function post(path: string, payload: Record): Promise<{ o headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }); - const body = await res.json(); + const body = await parseApiBody(res); + if (!body) throw new Error(tt('emptyResponse')); if (!res.ok || body.code !== 0) throw new Error(body.message || tt('testFailed')); return { ok: true, msg: body.data?.message || tt('testOk') }; } catch (e) { @@ -300,7 +336,8 @@ async function onNext(): Promise { onMounted(async () => { try { const res = await fetch('/api/install/status'); - const body = await res.json(); + const body = await parseApiBody(res); + if (!body) throw new Error(tt('emptyResponse')); installed.value = Boolean(body.data?.installed); const d = body.data?.defaults || {}; form.mysql.host = d.mysqlHost || form.mysql.host; @@ -318,18 +355,13 @@ onMounted(async () => { } }); -async function pollUntilReady(): Promise { +async function pollUntilReady(): Promise { for (let i = 0; i < 30; i += 1) { await new Promise((r) => setTimeout(r, 2000)); - try { - const res = await fetch('/api/install/status'); - const body = await res.json(); - if (body.data?.installed) break; - } catch { - // 服务重启期间请求失败属正常 - } + const st = await fetchInstallStatus(); + if (st.installed && !st.needsDevRestart) return true; } - goAdmin(); + return false; } async function submit(): Promise { @@ -345,10 +377,22 @@ async function submit(): Promise { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form), }); - const body = await res.json(); - if (!res.ok || body.code !== 0) throw new Error(body.message || tt('failed')); + const body = await parseApiBody(res); + // body 为空 = 安装成功后连接被 API 重启掐断(生产 PM2/Docker 或本地 dev.py 自动切换),视为已提交; + // body 有值且非 0 = 安装校验失败(如 MySQL 连接失败),抛出真实原因。 + if (body && (!res.ok || body.code !== 0)) { + throw new Error(body.message || tt('failed')); + } + installed.value = true; success.value = tt('done'); - await pollUntilReady(); + // 统一轮询等待系统就绪:本地 dev.py 会自动停掉安装 API 并以正式模式重启, + // 生产由 PM2/Docker 按重启策略拉起;就绪后进入后台。 + if (await pollUntilReady()) { + goAdmin(); + } else { + // 超时兜底:多为 --install-mode 调试模式(写临时 .env,不会自动切换) + success.value = tt('doneLocalDev'); + } } catch (e) { error.value = (e as Error).message; } finally { diff --git a/apps/api/src/install/install.service.ts b/apps/api/src/install/install.service.ts index 61f3819..e8cf689 100644 --- a/apps/api/src/install/install.service.ts +++ b/apps/api/src/install/install.service.ts @@ -20,8 +20,12 @@ const ENCRYPTED_PREFIX = 'enc:v1:'; export class InstallService { status() { const prefillSecrets = process.env.INSTALL_PREFILL_SECRETS === '1'; + const envPath = envFilePath(); + const envReady = existsSync(envPath); return { installed: !isInstallMode(), + // 本地 --install-mode 调试:.env 已写入但当前进程仍是 InstallAppModule,需重启 dev.py + needsDevRestart: process.env.ARTVERIS_INSTALL_MODE === '1' && envReady, defaults: { mysqlHost: process.env.INSTALL_MYSQL_HOST || '127.0.0.1', mysqlPort: Number(process.env.INSTALL_MYSQL_PORT || 3306), @@ -48,7 +52,11 @@ export class InstallService { this.runPrismaMigrate(databaseUrl); await this.seedInstallData(databaseUrl, dto, traceCodeSalt, settingsEncryptionKey); this.writeEnvFile(dto, databaseUrl, traceCodeSalt, settingsEncryptionKey); - setTimeout(() => process.exit(0), 600); + // 本地安装向导调试(ARTVERIS_INSTALL_MODE=1)不主动退出,避免响应未返回连接被掐断; + // 生产环境由 PM2/Docker restart policy 重启以加载新 .env。 + if (process.env.ARTVERIS_INSTALL_MODE !== '1') { + setTimeout(() => process.exit(0), 2500); + } return { installed: true, restartRequired: true }; } @@ -298,10 +306,14 @@ export class InstallService { private runPrismaMigrate(databaseUrl: string): void { const prismaBin = require.resolve('prisma/build/index.js'); - execFileSync(process.execPath, [prismaBin, 'migrate', 'deploy', '--schema', this.prismaSchemaPath()], { - stdio: 'inherit', - env: { ...process.env, DATABASE_URL: databaseUrl }, - }); + try { + execFileSync(process.execPath, [prismaBin, 'migrate', 'deploy', '--schema', this.prismaSchemaPath()], { + stdio: 'inherit', + env: { ...process.env, DATABASE_URL: databaseUrl }, + }); + } catch (e) { + throw new BusinessException(ErrorCode.BAD_REQUEST, `数据库迁移失败:${this.errorMessage(e)}`); + } } private prismaSchemaPath(): string { diff --git a/scripts/dev.py b/scripts/dev.py index 7ca20ec..2c2b555 100644 --- a/scripts/dev.py +++ b/scripts/dev.py @@ -10,13 +10,19 @@ - 已有 `.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 # 有 .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) + python scripts/dev.py --install-mode # 强制安装向导调试(写临时 .env,不污染根 .env,不自动切换) """ from __future__ import annotations @@ -30,6 +36,7 @@ from _lib import ( ROOT, create_kill_job, ensure_pnpm, + free_port, install_console_ctrl_handler, kill_project_servers, load_config, @@ -37,6 +44,7 @@ from _lib import ( run, run_retry, stop_all, + stop_proc_tree, wait_port, ) @@ -94,14 +102,40 @@ def install_env(cfg: dict, env_file: Path) -> dict[str, str]: } +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 监视器,避免其重启抢占端口) - ports = [app["api_port"], app["admin_port"], app["client_port"]] kill_project_servers(ports=ports) time.sleep(1.5) @@ -153,35 +187,55 @@ def main() -> None: 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) - procs.append(popen("pnpm dev:api", job=job, env=child_env)) + 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("\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 已就绪") + if force_install: + print( + " 说明 : 调试模式写入临时 " + f"{env_file.name},不自动切换;重新运行 python scripts/dev.py 进入正式模式。" + ) else: - print("[artveris] 后端 API 等待超时,仍继续启动前端(稍后会自动恢复)") + 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)) - 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']}") + start_full_dev() + print(" 按 Ctrl+C 退出全部。\n") for p in procs: p.wait()