fix(boot): CatalogModule 漏 import ScenesModule 导致产物起不来 + /health 版本号错

两个都是**只有真正启动服务才会暴露**的缺陷,v0.7.0 / v0.7.1 的产物受影响。

1. 【致命】CatalogModule 漏 import ScenesModule
   CatalogService 因为 catalog/export 要下发 scenes[] 而注入 ScenesService,但
   CatalogModule 的 imports 只列了 SongsModule / MotionsModule / ModelsModule。
   Nest 的 DI 按模块解析,于是 node dist/main.js 在 bootstrap 阶段直接抛
   UnknownDependenciesException: Nest can't resolve dependencies of the
   CatalogService (... ? ...) —— 服务完全起不来(装得上、起不来)。
   为什么三层检查全绿:nest build/tsc 看不出运行时 DI;258 项单元测试直接 new
   服务或测纯函数,从不编译 AppModule;打包脚本只校验文件清单与压缩包完整性。
   修复:CatalogModule.imports 补上 ScenesModule。

2. /health 的 version 在原生部署下永远是 0.1.0
   原实现 process.env.npm_package_version ?? '0.1.0',而该变量只在 npm 脚本下
   存在;正式部署是原生服务(ExecStart=node dist/main.js),npm 不参与 ->
   恒为 undefined -> 回退到硬编码 0.1.0,与管理端左下角展示的 vX.Y.Z 冲突,
   违反文档 11.2 第 4 条「可核对:Web 端至少与 GET /health 的 version 一致」。
   修复:新增 src/config/app-version.ts 作为运行时唯一解析点
   (APP_VERSION -> 运行入口旁/工作目录的 package.json(带包名校验)
   -> npm_package_version -> 显式 0.0.0),/health 改用 resolveAppVersion(),
   main.ts 启动首行也打印版本号。新增 12 项测试,其中一项显式模拟无 npm
   环境变量的原生部署。

防线(都挂进了 verify 与打包脚本)
- scripts/check-bootstrap.mjs:以正式部署方式(node dist/main.js、无 npm 环境
  变量、不需要数据库)拉起真实产物,断言①无依赖解析类错误②启动日志的应用版本
  等于 package.json ③已推进到数据库连接阶段。已做反向验证:删掉 ScenesModule
  后该检查立刻失败。
- scripts/check-version.mjs(并入 contracts:check):校验
  web-server/package.json = admin/package.json = project.yaml,正则禁止
  health.controller.ts 再出现硬编码版本回退,管理端已构建时断言产物 JS 含 vX.Y.Z。
- npm run verify 现在包含 bootstrap:check;package-release.sh 在构建后、打包前
  各跑一次(构建管理端后再跑 version:check,因为此时才需要校验产物内版本)。

文档:README.md / README.txt 增加 v0.7.2 修订说明;
tasks/011-version-display.md 与 tasks/015-scene-management.md 补「缺陷修复记录」
(含为什么当时没被发现的三层检查对照表)。

验证:npm run verify 通过(契约六项一致、35 条路由、258 项测试、nest build、
启动冒烟);产物 opendance-web-v0.7.2.tar.gz
sha256 f04ecc85d17517ec00754238616eb1237cdb2fe17440af6dce731827c0922b26。
This commit is contained in:
2026-09-17 01:49:52 +08:00
parent 698d60bb65
commit 2433cd22a5
16 changed files with 673 additions and 22 deletions
+175
View File
@@ -0,0 +1,175 @@
#!/usr/bin/env node
/**
* 启动冒烟检查:**编译产物能不能真正 boot 起来**(不需要数据库)。
*
* 为什么必须有这一层:`src/catalog/catalog.module.ts` 曾经漏了 `ScenesModule`,
* 而 `CatalogService` 注入了 `ScenesService` —— Nest 的 DI 是**按模块**解析的,
* 于是 `node dist/main.js` 在 bootstrap 阶段直接抛 `UnknownDependenciesException`,
* **服务根本起不来**。但当时所有检查都是绿的:
* - `nest build` 通过(类型没问题);
* - 258 项单元测试通过(它们直接 new 服务 / 测纯函数,从不编译 AppModule);
* - 打包脚本只校验文件清单与压缩包完整性。
* 结果就是 v0.7.0 / v0.7.1 的产物「装得上、起不来」。
*
* 本脚本以**正式部署的方式**(systemd 的 `ExecStart=node dist/main.js`,
* 不带任何 npm 环境变量)拉起真实产物,然后:
* 1. 断言日志里**没有**依赖解析类错误(UnknownDependenciesException 等)→ 模块图可解析;
* 2. 断言日志里的「应用版本 vX.Y.Z」等于 `package.json` 的 version
* → 原生部署下版本号解析正确(原先会退化成硬编码的 0.1.0);
* 3. 断言启动确实**推进到了数据库连接阶段** → 证明 Nest 已把整个 DI 图解析完,
* 而不是中途失败。
*
* 不需要数据库:TypeORM 连不上时日志里会出现明确的连接错误,那就够了 ——
* 本脚本的职责是「启动能否走到连库这一步」,真连库的端到端验收由
* `test/smoke.mjs`(部署好服务端后运行)负责。
*
* 用法:node scripts/check-bootstrap.mjs
*/
import { spawn } from 'node:child_process';
import { mkdtempSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const here = dirname(fileURLToPath(import.meta.url));
const serverDir = join(here, '..');
const entry = join(serverDir, 'dist', 'main.js');
const EXPECTED_VERSION = JSON.parse(
readFileSync(join(serverDir, 'package.json'), 'utf8'),
).version;
/** 依赖解析失败的标志(任一出现即失败) */
const DI_ERROR_PATTERNS = [
/UnknownDependenciesException/,
/Nest can't resolve dependencies/i,
/cannot resolve dependencies/i,
/Nest can't resolve/i,
];
/** 走到数据库连接阶段的标志 */
const DB_STAGE_PATTERNS = [
/Unable to connect to the database/i,
/ECONNREFUSED/,
/getaddrinfo/i,
/Access denied for user/i,
/Unknown database/i,
/服务已?启动/,
/已启动,监听/,
];
const TIMEOUT_MS = Number(process.env.BOOTSTRAP_TIMEOUT_MS ?? 40_000);
function freePort(base) {
// 用一个不常见的端口即可;连库失败是预期的,端口只要不撞上真实服务
return base + Math.floor(Math.random() * 200);
}
async function main() {
const scratch = mkdtempSync(join(tmpdir(), 'opendance-boot-'));
// 模拟 systemd:删掉 npm_* 环境变量(ExecStart=node dist/main.js 时它们不存在)
const env = { ...process.env };
for (const key of Object.keys(env)) {
if (key.startsWith('npm_')) delete env[key];
}
delete env.APP_VERSION; // 也不允许用显式覆盖,必须走 package.json
Object.assign(env, {
NODE_ENV: 'development', // 免得 validateEnv 在生产模式直接 exit(1)
HOST: '127.0.0.1',
PORT: String(freePort(34000)),
ADMIN_PORT: String(freePort(35000)),
DB_HOST: '127.0.0.1',
DB_PORT: '3399', // 故意指向一个没有 MySQL 的端口
DB_USER: 'opendance_probe',
DB_PASSWORD: 'opendance_probe',
DB_NAME: 'opendance_probe',
DB_LOGGING: 'false',
STORAGE_DIR: join(scratch, 'storage'),
ADMIN_DIR: join(scratch, 'admin'),
});
const child = spawn(process.execPath, [entry], {
cwd: serverDir,
env,
stdio: ['ignore', 'pipe', 'pipe'],
});
let output = '';
let finished = false;
const decide = () => {
if (finished) return null;
const diError = DI_ERROR_PATTERNS.find((re) => re.test(output));
if (diError) {
finished = true;
return { ok: false, reason: 'di', pattern: String(diError) };
}
const versionLine = output.match(/应用版本 v(\S+)/);
const dbStage = DB_STAGE_PATTERNS.some((re) => re.test(output));
if (versionLine && dbStage) {
finished = true;
return { ok: true, version: versionLine[1] };
}
return null;
};
const result = await new Promise((resolvePromise) => {
const timer = setTimeout(() => {
resolvePromise(decide() ?? { ok: false, reason: 'timeout' });
}, TIMEOUT_MS);
const onData = (chunk) => {
output += chunk.toString();
const decided = decide();
if (decided) {
clearTimeout(timer);
child.kill('SIGKILL');
resolvePromise(decided);
}
};
child.stdout.on('data', onData);
child.stderr.on('data', onData);
child.on('exit', () => {
clearTimeout(timer);
resolvePromise(decide() ?? { ok: false, reason: 'exit' });
});
child.on('error', (error) => {
clearTimeout(timer);
resolvePromise({ ok: false, reason: 'spawn', error: error.message });
});
});
if (result.ok) {
if (result.version !== EXPECTED_VERSION) {
console.error(
`✗ 启动日志里的应用版本 v${result.version} 与 web-server/package.json 的 ${EXPECTED_VERSION} 不一致`,
);
console.error(' (原生部署下版本号必须从 package.json 解析,不能依赖 npm 环境变量)');
process.exit(1);
}
console.log(
`✓ 启动冒烟通过:模块依赖图可解析(无 UnknownDependenciesException)、` +
`应用版本 v${result.version} 与 package.json 一致、已推进到数据库连接阶段`,
);
return;
}
console.error('✗ 启动冒烟失败:');
if (result.reason === 'di') {
console.error(` 依赖解析错误(匹配 ${result.pattern})—— 有模块忘记 import 提供者了。`);
console.error(' 提示:检查各 @Module 的 imports 是否覆盖了构造函数里注入的服务。');
} else if (result.reason === 'timeout') {
console.error(' 进程既没有报依赖错误,也没有推进到数据库连接阶段(超时)。');
} else if (result.reason === 'exit') {
console.error(' 进程提前退出,且日志里既没有依赖错误也没有数据库阶段标志。');
} else if (result.reason === 'spawn') {
console.error(` 无法启动 ${entry}:${result.error}`);
}
console.error('\n---- 进程输出(末尾 40 行)----');
console.error(output.split('\n').slice(-40).join('\n'));
process.exit(1);
}
await main();
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env node
/**
* 版本号一致性校验(文档 §11.2「单一来源 / 可核对」)。
*
* 守护的缺陷:`/health` 曾经用
* process.env.npm_package_version ?? '0.1.0'
* 而正式部署方式是原生服务(`ExecStart=node dist/main.js`),npm 不参与,
* 该环境变量为 undefined —— 于是真实部署里 `/health` 永远报 **0.1.0**,
* 与管理端左下角展示的 vX.Y.Z 不一致。
*
* 校验项:
* 1. web-server/package.json 的 version === project.yaml 的 version
* 2. web-server/admin/package.json 的 version === web-server/package.json 的 version
* 3. src/config/app-version.ts 存在,且 health.controller 通过它取版本
* 4. health.controller 里不得再出现硬编码的版本回退(如 `?? '0.1.0'`)
* 5. 若管理端已构建(web-server/admin/dist 存在),其 JS 包内必须含 `v<version>`
*
* 用法:node scripts/check-version.mjs
*/
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const here = dirname(fileURLToPath(import.meta.url));
const serverDir = join(here, '..');
const repoDir = join(serverDir, '..');
const problems = [];
const notes = [];
function readJson(file) {
try {
return JSON.parse(readFileSync(file, 'utf8'));
} catch (error) {
problems.push(`无法解析 ${file}:${error.message}`);
return null;
}
}
function readYamlVersion(file) {
if (!existsSync(file)) {
problems.push(`缺少 ${file}`);
return null;
}
const line = readFileSync(file, 'utf8')
.split(/\r?\n/)
.find((l) => l.trimStart().startsWith('version:'));
if (!line) {
problems.push(`无法在 ${file} 中定位 version:`);
return null;
}
return line.slice(line.indexOf(':') + 1).trim();
}
// ---- 1. package.json 与 project.yaml ----
const serverPkg = readJson(join(serverDir, 'package.json'));
const yamlVersion = readYamlVersion(join(repoDir, 'project.yaml'));
if (serverPkg && yamlVersion && serverPkg.version !== yamlVersion) {
problems.push(`版本不一致:web-server/package.json=${serverPkg.version} vs project.yaml=${yamlVersion}`);
}
// ---- 2. 管理端 package.json 与之同源 ----
const adminPkgPath = join(serverDir, 'admin', 'package.json');
if (existsSync(adminPkgPath)) {
const adminPkg = readJson(adminPkgPath);
if (serverPkg && adminPkg && adminPkg.version !== serverPkg.version) {
problems.push(
`版本不一致:web-server/admin/package.json=${adminPkg.version} vs web-server/package.json=${serverPkg.version}`,
);
}
}
// ---- 3 & 4. /health 的版本必须来自 package.json,不能再硬编码 ----
const healthPath = join(serverDir, 'src', 'health', 'health.controller.ts');
const versionModulePath = join(serverDir, 'src', 'config', 'app-version.ts');
if (!existsSync(versionModulePath)) {
problems.push('缺少 src/config/app-version.ts(版本号运行时唯一解析点)');
}
if (!existsSync(healthPath)) {
problems.push('缺少 src/health/health.controller.ts');
} else {
const health = readFileSync(healthPath, 'utf8');
if (!health.includes('resolveAppVersion')) {
problems.push('health.controller.ts 未使用 resolveAppVersion(),/health 的版本可能不是单一来源');
}
// 硬编码版本回退:`?? 'x.y.z'` 或 `|| "x.y.z"`
const hardcoded = health.match(/\?\?\s*['"]\d+\.\d+\.\d+['"]|\|\|\s*['"]\d+\.\d+\.\d+['"]/);
if (hardcoded) {
problems.push(
`health.controller.ts 存在硬编码版本回退 ${hardcoded[0]};应使用 resolveAppVersion()(否则原生部署下 /health 会报错版本)`,
);
}
}
// ---- 5. 管理端构建产物必须带上与 package.json 相同的版本 ----
const adminDist = join(serverDir, 'admin', 'dist', 'assets');
if (serverPkg && existsSync(adminDist)) {
const files = readdirSync(adminDist).filter((f) => f.endsWith('.js'));
const found = new Set();
for (const file of files) {
const text = readFileSync(join(adminDist, file), 'utf8');
for (const m of text.matchAll(/v\d+\.\d+\.\d+/g)) found.add(m[0]);
}
const expected = `v${serverPkg.version}`;
if (found.size === 0) {
problems.push(`管理端构建产物中找不到任何 vX.Y.Z(期望 ${expected})`);
} else if (!found.has(expected)) {
problems.push(`管理端构建产物中的版本 ${[...found].join('/')} 与 package.json 的 ${expected} 不一致`);
} else {
notes.push(`管理端构建产物含 ${expected}`);
}
} else {
notes.push('管理端尚未构建,跳过产物内版本校验(打包脚本会在构建后再次执行本脚本)');
}
if (problems.length > 0) {
console.error('✗ 版本一致性校验失败:');
for (const p of problems) console.error(` - ${p}`);
console.error('\n请同步 web-server/package.json、web-server/admin/package.json、project.yaml;');
console.error('/health 的版本必须来自 src/config/app-version.ts(读 package.json),不得硬编码。');
process.exit(1);
}
for (const n of notes) console.log(` · ${n}`);
console.log(
`✓ 版本一致(${serverPkg?.version}):web-server/package.json = admin/package.json = project.yaml,` +
`/health 由 resolveAppVersion() 读取 package.json`,
);