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
+6
View File
@@ -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],
+129
View File
@@ -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;
}
+5 -1
View File
@@ -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
View File
@@ -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}`);