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:
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "opendance-admin",
|
||||
"private": true,
|
||||
"version": "0.7.1",
|
||||
"version": "0.7.2",
|
||||
"type": "module",
|
||||
"description": "OpenDance Studio 管理端(React + TypeScript + Vite)",
|
||||
"scripts": {
|
||||
|
||||
Generated
+3
-3
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "opendance-web-server",
|
||||
"version": "0.2.0",
|
||||
"version": "0.7.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "opendance-web-server",
|
||||
"version": "0.2.0",
|
||||
"version": "0.7.2",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^11.0.12",
|
||||
@@ -35,7 +35,7 @@
|
||||
"vitest": "^3.0.8"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
"node": ">=22.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@angular-devkit/core": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "opendance-web-server",
|
||||
"version": "0.7.1",
|
||||
"version": "0.7.2",
|
||||
"description": "OpenDance Studio Web 管理服务端(NestJS + TypeORM + 现有 MySQL 实例)",
|
||||
"license": "MIT",
|
||||
"private": true,
|
||||
@@ -16,13 +16,15 @@
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:smoke": "node test/smoke.mjs",
|
||||
"contracts:check": "node scripts/check-contracts.mjs && node scripts/check-routes.mjs",
|
||||
"verify": "npm run contracts:check && npm run typecheck && npm run test && npm run build",
|
||||
"contracts:check": "node scripts/check-contracts.mjs && node scripts/check-routes.mjs && node scripts/check-version.mjs",
|
||||
"verify": "npm run contracts:check && npm run typecheck && npm run test && npm run build && npm run bootstrap:check",
|
||||
"typeorm": "node scripts/migrate.mjs",
|
||||
"migration:generate": "node scripts/migrate.mjs generate",
|
||||
"migration:run": "node scripts/migrate.mjs run",
|
||||
"migration:revert": "node scripts/migrate.mjs revert",
|
||||
"migration:show": "node scripts/migrate.mjs show"
|
||||
"migration:show": "node scripts/migrate.mjs show",
|
||||
"version:check": "node scripts/check-version.mjs",
|
||||
"bootstrap:check": "node scripts/check-bootstrap.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^11.0.12",
|
||||
|
||||
@@ -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();
|
||||
@@ -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`,
|
||||
);
|
||||
@@ -5,6 +5,7 @@ import { Motion } from '../entities/motion.entity';
|
||||
import { Song } from '../entities/song.entity';
|
||||
import { ModelsModule } from '../models/models.module';
|
||||
import { MotionsModule } from '../motions/motions.module';
|
||||
import { ScenesModule } from '../scenes/scenes.module';
|
||||
import { SongsModule } from '../songs/songs.module';
|
||||
import { CatalogController } from './catalog.controller';
|
||||
import { CatalogService } from './catalog.service';
|
||||
@@ -15,6 +16,11 @@ import { CatalogService } from './catalog.service';
|
||||
SongsModule,
|
||||
MotionsModule,
|
||||
ModelsModule,
|
||||
// CatalogService 注入 ScenesService(catalog/export 要下发 scenes[])。
|
||||
// Nest 的 DI 是**按模块**解析的:不在这里 import,bootstrap 时会直接
|
||||
// UnknownDependenciesException,服务根本起不来 —— 由 scripts/check-bootstrap.mjs
|
||||
// 在构建后强制拦截(v0.7.0/v0.7.1 就是漏了这一步才把「装得上、起不来」的产物发了出去)。
|
||||
ScenesModule,
|
||||
],
|
||||
controllers: [CatalogController],
|
||||
providers: [CatalogService],
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
|
||||
/**
|
||||
* 应用版本号的**运行时唯一解析点**(文档 §11.1 / §11.2)。
|
||||
*
|
||||
* 为什么不能只用 `process.env.npm_package_version`:
|
||||
* 那个环境变量**只在通过 npm 脚本启动时**才存在(`npm start` / `npm run start:prod`)。
|
||||
* 而本项目的正式部署方式是**原生服务**(systemd / OpenRC / initd),
|
||||
* `ExecStart=node dist/main.js` —— npm 不参与,于是 `npm_package_version` 为 undefined,
|
||||
* 原来那句 `?? '0.1.0'` 会让 `GET /health` 在真实部署里**永远报 0.1.0**,
|
||||
* 与「管理端左下角展示 vX.Y.Z、且必须与 /health 一致」的硬性要求直接冲突。
|
||||
*
|
||||
* 因此改为从 **`package.json` 实体文件**读取(构建期注入管理端的也是这同一份文件),
|
||||
* 依次尝试多个候选路径,取第一个「包名匹配」的结果:
|
||||
*
|
||||
* 1. `APP_VERSION` 环境变量(显式覆盖,给运维留一个不重新打包即可改的口子)
|
||||
* 2. 运行入口所在目录的 `../package.json`(`dist/main.js` → `web-server/package.json`)
|
||||
* 3. 进程工作目录下的 `package.json`(systemd 的 `WorkingDirectory=.../web-server`)
|
||||
* 4. `npm_package_version`(npm 脚本启动时的兜底)
|
||||
* 5. 都没有则 `'0.0.0'` —— 显式可见的“未知版本”,绝不伪装成某个具体版本
|
||||
*
|
||||
* 候选路径都必须通过 [parsePackageVersion] 的**包名校验**,
|
||||
* 避免把上层仓库或别的 Node 项目的 `package.json` 误当成自己。
|
||||
*/
|
||||
|
||||
/** 本包的 `name`,用于校验读到的 package.json 确实是本项目 */
|
||||
export const PACKAGE_NAME = 'opendance-web-server';
|
||||
|
||||
/** 无法解析时的显式占位值(不是任何真实版本,便于一眼看出异常) */
|
||||
export const UNKNOWN_VERSION = '0.0.0';
|
||||
|
||||
/**
|
||||
* 从 `package.json` 文本中解析版本号。
|
||||
* **纯函数**:只在「JSON 合法 + 包名匹配 + version 形如 x.y.z」时才返回版本,
|
||||
* 否则返回 null(调用方继续尝试下一个候选路径)。
|
||||
*/
|
||||
export function parsePackageVersion(content: string): string | null {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(content);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (typeof parsed !== 'object' || parsed === null) return null;
|
||||
const pkg = parsed as Record<string, unknown>;
|
||||
if (pkg.name !== PACKAGE_NAME) return null;
|
||||
const version = pkg.version;
|
||||
if (typeof version !== 'string') return null;
|
||||
const trimmed = version.trim();
|
||||
// 形如 X.Y.Z(允许预发布后缀),防止读到 'workspace:*' 之类的非版本值
|
||||
if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(trimmed)) return null;
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/** 收集候选 `package.json` 路径(顺序即优先级) */
|
||||
export function packageJsonCandidates(): string[] {
|
||||
const out: string[] = [];
|
||||
|
||||
// 2. 运行入口:CJS 下可用 require.main;ESM/测试环境下跳过
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const main = typeof require !== 'undefined' ? require.main : undefined;
|
||||
const filename: unknown = main?.filename;
|
||||
if (typeof filename === 'string' && filename.length > 0) {
|
||||
out.push(resolve(dirname(filename), '..', 'package.json'));
|
||||
}
|
||||
} catch {
|
||||
/* 非 CJS 环境,忽略 */
|
||||
}
|
||||
|
||||
// 2b. 编译产物相对位置:dist/config/app-version.js → web-server/package.json
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-undef
|
||||
const here = typeof __dirname === 'string' ? __dirname : '';
|
||||
if (here) out.push(resolve(here, '..', '..', 'package.json'));
|
||||
} catch {
|
||||
/* ESM 下 __dirname 未定义,忽略 */
|
||||
}
|
||||
|
||||
// 3. 工作目录(systemd 的 WorkingDirectory=.../web-server)
|
||||
out.push(join(process.cwd(), 'package.json'));
|
||||
|
||||
return [...new Set(out)];
|
||||
}
|
||||
|
||||
function readVersion(file: string): string | null {
|
||||
if (!existsSync(file)) return null;
|
||||
try {
|
||||
return parsePackageVersion(readFileSync(file, 'utf8'));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 解析当前运行版本;结果对同一进程稳定(缓存) */
|
||||
let cached: string | null = null;
|
||||
|
||||
export function resolveAppVersion(): string {
|
||||
if (cached !== null) return cached;
|
||||
|
||||
const explicit = process.env.APP_VERSION?.trim();
|
||||
if (explicit) {
|
||||
cached = explicit;
|
||||
return cached;
|
||||
}
|
||||
|
||||
for (const file of packageJsonCandidates()) {
|
||||
const version = readVersion(file);
|
||||
if (version) {
|
||||
cached = version;
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
const npmVersion = process.env.npm_package_version?.trim();
|
||||
if (npmVersion && /^\d+\.\d+\.\d+/.test(npmVersion)) {
|
||||
cached = npmVersion;
|
||||
return cached;
|
||||
}
|
||||
|
||||
cached = UNKNOWN_VERSION;
|
||||
return cached;
|
||||
}
|
||||
|
||||
/** 测试用:清空缓存(生产代码不要调用) */
|
||||
export function resetAppVersionCache(): void {
|
||||
cached = null;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { Controller, Get, Res, ServiceUnavailableException } from '@nestjs/commo
|
||||
import { InjectDataSource } from '@nestjs/typeorm';
|
||||
import { Response } from 'express';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { resolveAppVersion } from '../config/app-version';
|
||||
import { AppConfig } from '../config/configuration';
|
||||
import { detectAssimp } from '../preprocess/assimp';
|
||||
|
||||
@@ -69,7 +70,10 @@ export class HealthController {
|
||||
const report: HealthReport = {
|
||||
status: database.connected ? 'ok' : 'degraded',
|
||||
uptimeSec: Math.round(process.uptime() * 1000) / 1000,
|
||||
version: process.env.npm_package_version ?? '0.1.0',
|
||||
// 版本号唯一解析点:读 package.json 实体文件,而不是只在 npm 脚本下才存在的
|
||||
// npm_package_version(原生部署 ExecStart=node dist/main.js 时它是 undefined,
|
||||
// 会让 /health 永远报一个陈旧的硬编码版本,与管理端左下角的展示冲突)。
|
||||
version: resolveAppVersion(),
|
||||
contractVersion: this.config.contractVersions,
|
||||
database,
|
||||
storage: {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { existsSync, mkdirSync } from 'node:fs';
|
||||
import { extname, join, resolve } from 'node:path';
|
||||
import { AppModule } from './app.module';
|
||||
import { describeDualAccess, preferredUrl } from './config/access-hint';
|
||||
import { resolveAppVersion } from './config/app-version';
|
||||
import {
|
||||
AppConfig,
|
||||
configuration,
|
||||
@@ -37,6 +38,12 @@ function listenServer(server: Server, port: number, host: string): Promise<void>
|
||||
async function bootstrap(): Promise<void> {
|
||||
const logger = new Logger('Bootstrap');
|
||||
|
||||
// 先打版本号:这是「当前运行版本」的唯一来源(web-server/package.json,
|
||||
// 由 resolveAppVersion() 解析,不依赖 npm 环境变量)。
|
||||
// 放在最前面还有一个作用:即使后面数据库连不上、进程退出,
|
||||
// 日志里也一定能看到本次运行的版本号(便于与 /health、管理端左下角核对)。
|
||||
logger.log(`OpenDance Studio Web 服务端 应用版本 v${resolveAppVersion()}`);
|
||||
|
||||
// 启动前校验环境变量(生产环境禁止 DB_SYNCHRONIZE=true、端口必须合法等)
|
||||
const { errors, warnings } = validateEnv(configuration());
|
||||
for (const warning of warnings) logger.warn(`环境变量提示:${warning}`);
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
PACKAGE_NAME,
|
||||
UNKNOWN_VERSION,
|
||||
packageJsonCandidates,
|
||||
parsePackageVersion,
|
||||
resetAppVersionCache,
|
||||
resolveAppVersion,
|
||||
} from '../src/config/app-version';
|
||||
|
||||
/**
|
||||
* 版本号展示的**运行时唯一来源**(文档 §11.1 / §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 不一致,
|
||||
* 直接违反「可核对:Web 端至少与 GET /health 的 version 一致」。
|
||||
*/
|
||||
|
||||
const serverPackageJson = JSON.parse(
|
||||
readFileSync(resolve(__dirname, '..', 'package.json'), 'utf8'),
|
||||
) as { name: string; version: string };
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.APP_VERSION;
|
||||
resetAppVersionCache();
|
||||
});
|
||||
|
||||
describe('parsePackageVersion(纯函数:只在包名与格式都对时才认)', () => {
|
||||
it('接受本项目的 package.json', () => {
|
||||
expect(
|
||||
parsePackageVersion(JSON.stringify({ name: PACKAGE_NAME, version: '1.2.3' })),
|
||||
).toBe('1.2.3');
|
||||
});
|
||||
|
||||
it('接受带预发布后缀的版本', () => {
|
||||
expect(
|
||||
parsePackageVersion(JSON.stringify({ name: PACKAGE_NAME, version: '1.2.3-rc.1' })),
|
||||
).toBe('1.2.3-rc.1');
|
||||
});
|
||||
|
||||
it('拒绝包名不匹配的文件(避免读到上层仓库的 package.json)', () => {
|
||||
expect(parsePackageVersion(JSON.stringify({ name: 'some-other-pkg', version: '9.9.9' }))).toBeNull();
|
||||
});
|
||||
|
||||
it('拒绝缺少 name / version 的文件', () => {
|
||||
expect(parsePackageVersion(JSON.stringify({ version: '1.2.3' }))).toBeNull();
|
||||
expect(parsePackageVersion(JSON.stringify({ name: PACKAGE_NAME }))).toBeNull();
|
||||
expect(parsePackageVersion(JSON.stringify({ name: PACKAGE_NAME, version: 123 }))).toBeNull();
|
||||
});
|
||||
|
||||
it('拒绝非版本串(例如 workspace:*)', () => {
|
||||
expect(parsePackageVersion(JSON.stringify({ name: PACKAGE_NAME, version: 'workspace:*' }))).toBeNull();
|
||||
expect(parsePackageVersion(JSON.stringify({ name: PACKAGE_NAME, version: '^1.0.0' }))).toBeNull();
|
||||
});
|
||||
|
||||
it('拒绝非法 JSON 与非对象', () => {
|
||||
expect(parsePackageVersion('{ 不是 JSON')).toBeNull();
|
||||
expect(parsePackageVersion('"字符串"')).toBeNull();
|
||||
expect(parsePackageVersion('null')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveAppVersion(运行时解析)', () => {
|
||||
it('解析结果等于 web-server/package.json 的 version(单一来源)', () => {
|
||||
expect(resolveAppVersion()).toBe(serverPackageJson.version);
|
||||
});
|
||||
|
||||
it('与 package.json 里声明的包名一致(校验逻辑没有把别的包读进来)', () => {
|
||||
expect(serverPackageJson.name).toBe(PACKAGE_NAME);
|
||||
});
|
||||
|
||||
it('未通过 npm 启动时也能拿到真实版本(不依赖 npm_package_version)', () => {
|
||||
// 模拟原生部署:systemd 直接跑 node dist/main.js,没有 npm 环境变量
|
||||
const saved = process.env.npm_package_version;
|
||||
delete process.env.npm_package_version;
|
||||
delete process.env.APP_VERSION;
|
||||
resetAppVersionCache();
|
||||
try {
|
||||
const version = resolveAppVersion();
|
||||
expect(version).toBe(serverPackageJson.version);
|
||||
expect(version).not.toBe('0.1.0');
|
||||
expect(version).not.toBe(UNKNOWN_VERSION);
|
||||
} finally {
|
||||
if (saved !== undefined) process.env.npm_package_version = saved;
|
||||
resetAppVersionCache();
|
||||
}
|
||||
});
|
||||
|
||||
it('APP_VERSION 环境变量可显式覆盖(运维不重新打包也能改)', () => {
|
||||
process.env.APP_VERSION = '9.8.7';
|
||||
resetAppVersionCache();
|
||||
expect(resolveAppVersion()).toBe('9.8.7');
|
||||
});
|
||||
|
||||
it('候选路径包含工作目录(systemd WorkingDirectory=web-server)', () => {
|
||||
const candidates = packageJsonCandidates();
|
||||
expect(candidates).toContain(join(process.cwd(), 'package.json'));
|
||||
// 去重:同一路径不应出现两次
|
||||
expect(new Set(candidates).size).toBe(candidates.length);
|
||||
});
|
||||
|
||||
it('结果稳定(同一进程内缓存,不会来回变)', () => {
|
||||
const first = resolveAppVersion();
|
||||
const second = resolveAppVersion();
|
||||
expect(first).toBe(second);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user