packServer/backend/scripts/deploy/publish-desktop.cjs
liufumingren 5bd90a45ff fix(agent): 面单识别断流死循环改指数退避 + 后台服务单实例
- label-scan 断流重连从固定 3s 改为 3s 起指数退避到 60s;连上稳定 30s 才清零;
  内存不足(OutOfMemory / Cannot allocate memory)固定等 60s。
  现场 2026-11-18:两路主码流 + 系统提交内存耗尽时,每 3 秒重拉一次 ffmpeg 自己踩自己
- AgentHost 加 Global\YuncangTraceAgent.instance 单实例锁:服务与 --agent-run 双开时
  第二个实例直接退出,不再重复拉流、抢写 agent-status.json、抢 hik-worker 管道
- hik-worker 管道创建失败改为 3→30s 退避重试,连续 12 次失败退出(交给主进程熔断)
- agent-status.json 的「变了就写」判据剔除每帧都变的诊断计数器,不再 2.5 次/秒重写
- scan-records.json 改为共享读 + 原子替换(File.Move),桌面端不再刷「文件被另一个进程占用」
- publish-desktop:releaseNotes 用 node 侧字符串回写 version.json,避免命令行中文乱码

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-19 00:46:12 +08:00

296 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/**
* 桌面端正式包:构建 MSI + EXE + version.json,并单独发布到 nginx 静态目录
*
* 特点:
* - 只动桌面端产物,不重新发布后端、不重启 Egg、不跑数据库迁移;
* - 构建复用 desktop/installer/build.ps1(Production 环境,默认同时出 MSI 和 EXE);
* - 安装包上传到 deploy.config.local.cjs 里的 desktopDownloadDir(deployRoot/download/desktop);
* - version.json 上传到 desktopVersionDir(默认 deployRoot/download,nginx 对 /download/version.json 关缓存);
* - 同时刷新 front.conf 里的 /download/ 静态托管配置并 reload nginx。
*
* 为什么两个包都要传:老客户端只认 downloadUrl(MSI);新客户端优先 downloadUrlExe(EXE,
* 不依赖 Windows Installer,现场装不了 MSI 的机器靠它)。少传任何一个都会让对应客户端 404。
*
* 用法:
* npm run desktop:publish # 自动递增补丁版本并发布
* npm run desktop:publish -- --version=1.0.90
* npm run desktop:publish -- --notes="修复 xxx" --keep=10
* npm run desktop:build # 只构建,不上传(--dry-run)
* npm run desktop:publish -- --skip-nginx # 不改 nginx
*/
const fs = require('node:fs');
const path = require('node:path');
const {
ROOT,
ensureCommandAvailable,
getNowStamp,
loadDeployConfig,
quoteForBash,
refreshNginx,
runCommand,
runScp,
runSsh,
} = require('./deploy-lib.cjs');
function parseArgs(argv) {
const options = {
envName: 'production',
version: '',
notes: '',
keep: 0,
target: '',
dryRun: false,
skipNginx: false,
};
for (const item of argv) {
if (!item) continue;
if (!item.startsWith('--') && !options.envNameExplicit) {
options.envName = item;
options.envNameExplicit = true;
continue;
}
if (item === '--dry-run') {
options.dryRun = true;
} else if (item === '--skip-nginx') {
options.skipNginx = true;
} else if (item.startsWith('--version=')) {
options.version = item.slice('--version='.length).trim().replace(/^v/i, '');
} else if (item.startsWith('--notes=')) {
options.notes = item.slice('--notes='.length);
} else if (item.startsWith('--keep=')) {
options.keep = Number(item.slice('--keep='.length)) || 0;
} else if (item.startsWith('--target=')) {
options.target = item.slice('--target='.length).trim();
const allowed = [ 'Both', 'Msi', 'Exe' ];
if (!allowed.includes(options.target)) {
throw new Error(`--target 只能是 ${allowed.join(' / ')}:${options.target}`);
}
}
}
if (options.version && !/^\d+\.\d+\.\d+$/.test(options.version)) {
throw new Error(`版本号格式应为 x.y.z:${options.version}`);
}
return options;
}
function compareVersion(a, b) {
const pa = a.split('.').map(Number);
const pb = b.split('.').map(Number);
for (let i = 0; i < 3; i++) {
if (pa[i] !== pb[i]) return pa[i] - pb[i];
}
return 0;
}
/** 取本地已有安装包 / version.json 中最高的版本,并默认 +1 补丁号 */
function nextVersion(outDir) {
const versions = [];
if (fs.existsSync(outDir)) {
for (const name of fs.readdirSync(outDir)) {
const match = name.match(/^YuncangTraceSetup-(\d+\.\d+\.\d+)\.(?:msi|exe)$/);
if (match) versions.push(match[1]);
}
}
const versionFile = path.join(outDir, 'version.json');
if (fs.existsSync(versionFile)) {
try {
const data = JSON.parse(fs.readFileSync(versionFile, 'utf8'));
if (data && /^\d+\.\d+\.\d+$/.test(String(data.version || ''))) {
versions.push(String(data.version));
}
} catch (error) {
// 忽略损坏的本地 version.json
}
}
if (!versions.length) return '1.0.0';
versions.sort(compareVersion);
const [ major, minor, patch ] = versions[versions.length - 1].split('.').map(Number);
return `${major}.${minor}.${patch + 1}`;
}
/** 用 build.ps1 构建 Production 包 */
function buildDesktop(config, { version, notes, baseUrl, target }) {
const buildScript = path.resolve(ROOT, config.desktopBuildScript);
if (!fs.existsSync(buildScript)) {
throw new Error(`找不到桌面端构建脚本: ${buildScript}`);
}
const shell = process.platform === 'win32' ? 'powershell.exe' : 'pwsh';
const args = [
'-NoProfile',
'-ExecutionPolicy', 'Bypass',
'-File', buildScript,
'-Environment', 'Production',
'-Version', version,
'-ServerBaseUrl', baseUrl,
];
if (notes) {
args.push('-ReleaseNotes', notes);
}
// 只出某一种包(例如老客户端 MD5 校验有 bug 时,先发一个「只有 MSI」的版本把它们拉上来)
if (target) {
args.push('-Target', target);
}
console.log(`构建桌面端正式包: ${version}(${baseUrl})`);
runCommand(shell, args, { cwd: path.dirname(buildScript), stdio: 'inherit' });
}
/** 写 front.conf(静态 /download + /api 反代)并 reload nginx */
function main() {
const options = parseArgs(process.argv.slice(2));
const config = loadDeployConfig(options.envName);
const outDir = path.resolve(ROOT, config.desktopOutDir);
const remoteDir = config.desktopDownloadDir;
// version.json 不放安装包目录里:nginx 对 /download/version.json 单独关缓存,安装包目录走长缓存
const remoteVersionDir = config.desktopVersionDir || path.posix.dirname(String(remoteDir || ''));
const baseUrl = String(config.desktopBaseUrl || `http://${config.serverName}`).replace(/\/+$/, '');
const keep = options.keep > 0 ? options.keep : Number(config.desktopKeepVersions || 5);
const version = options.version || nextVersion(outDir);
if (!remoteDir) {
throw new Error('未配置 desktopDownloadDir(桌面安装包发布目录)。');
}
if (!remoteVersionDir || remoteVersionDir === '.' || remoteVersionDir === '/') {
throw new Error('未配置 desktopVersionDir(version.json 发布目录)。');
}
buildDesktop(config, { version, notes: options.notes, baseUrl, target: options.target });
const msiName = `YuncangTraceSetup-${version}.msi`;
const exeName = `YuncangTraceSetup-${version}.exe`;
const msiPath = path.join(outDir, msiName);
const exePath = path.join(outDir, exeName);
const versionPath = path.join(outDir, 'version.json');
if (!fs.existsSync(versionPath)) {
throw new Error(`构建完成但 version.json 不存在: ${versionPath}`);
}
const versionJson = JSON.parse(fs.readFileSync(versionPath, 'utf8'));
// --notes 要穿过 shell/powershell 两层命令行,中文偶尔会被按 GBK 解一遍(上一次发布就是乱码)。
// 这里用 node 里这份(Unicode 一定正确)覆盖写回,保证客户端更新弹窗里的说明不乱码。
if (options.notes && versionJson.releaseNotes !== options.notes) {
versionJson.releaseNotes = options.notes;
fs.writeFileSync(versionPath, JSON.stringify(versionJson, null, 2), 'utf8');
console.log('更新说明已按 UTF-8 重新写入 version.json');
}
// version.json 里有 downloadUrlExe 就必须把 EXE 一起传上去,否则新客户端拿到的是 404
const packages = [];
if (fs.existsSync(msiPath)) packages.push(msiPath);
if (versionJson.downloadUrlExe) {
if (!fs.existsSync(exePath)) {
throw new Error(`version.json 指向 EXE,但文件不存在: ${exePath}`);
}
packages.push(exePath);
}
if (!packages.length) {
throw new Error(`构建完成但没找到安装包(${msiName} / ${exeName})`);
}
for (const pkg of packages) {
console.log(`安装包: ${pkg}(${(fs.statSync(pkg).size / 1024 / 1024).toFixed(1)} MB)`);
}
console.log(`版本文件: ${versionPath}`);
console.log(`下载地址: ${versionJson.downloadUrl}`);
if (versionJson.downloadUrlExe) {
console.log(`下载地址(EXE): ${versionJson.downloadUrlExe}`);
}
console.log(`发布目录: ${config.username}@${config.host}:${remoteDir}`);
console.log(`版本目录: ${config.username}@${config.host}:${remoteVersionDir}`);
if (options.dryRun) {
console.log('DRY-RUN:只构建,不上传。');
return;
}
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
const stamp = getNowStamp();
const remoteVersionTmp = `${remoteVersionDir}/.version.json.upload-${stamp}`;
runSsh(config, [
'set -euo pipefail',
`DIR=${quoteForBash(remoteDir)}`,
`VDIR=${quoteForBash(remoteVersionDir)}`,
'mkdir -p "$DIR" "$VDIR"',
// 清理上次中断留下的隐藏临时文件
'find "$DIR" "$VDIR" -maxdepth 1 -type f -name ".*.upload-*" -delete',
].join('\n'), { stdio: 'pipe' });
for (const pkg of packages) {
const name = path.basename(pkg);
const remoteTmp = `${remoteDir}/.${name}.upload-${stamp}`;
console.log(`上传安装包 ${name}(${(fs.statSync(pkg).size / 1024 / 1024).toFixed(1)} MB)…`);
runScp(config, pkg, remoteTmp);
runSsh(config, [
'set -euo pipefail',
`TMP=${quoteForBash(remoteTmp)}`,
`FINAL=${quoteForBash(`${remoteDir}/${name}`)}`,
'mv "$TMP" "$FINAL"',
'chmod 644 "$FINAL"',
`chown ${quoteForBash(config.desktopOwner || 'www:www')} "$FINAL" || true`,
`echo "PACKAGE_UPLOADED ${name}"`,
].join('\n'), { stdio: 'pipe' });
console.log(`安装包已发布: ${remoteDir}/${name}`);
}
// 所有安装包就位后再更新 version.json,避免客户端拿到指向不存在文件的版本信息
runScp(config, versionPath, remoteVersionTmp);
runSsh(config, [
'set -euo pipefail',
`DIR=${quoteForBash(remoteDir)}`,
`VDIR=${quoteForBash(remoteVersionDir)}`,
`TMP=${quoteForBash(remoteVersionTmp)}`,
'mv "$TMP" "$VDIR/version.json"',
'chmod 644 "$VDIR/version.json"',
`chown ${quoteForBash(config.desktopOwner || 'www:www')} "$VDIR/version.json" || true`,
'echo "VERSION_JSON_UPLOADED"',
// 只保留最近 N 个安装包(MSI / EXE 分别计算)
'COUNT=0',
`for FILE in $(ls -1t "$DIR"/YuncangTraceSetup-*.msi 2>/dev/null || true); do`,
' COUNT=$((COUNT + 1))',
` if [ "$COUNT" -gt ${Number(keep)} ]; then rm -f "$FILE"; fi`,
'done',
'COUNT=0',
`for FILE in $(ls -1t "$DIR"/YuncangTraceSetup-*.exe 2>/dev/null || true); do`,
' COUNT=$((COUNT + 1))',
` if [ "$COUNT" -gt ${Number(keep)} ]; then rm -f "$FILE"; fi`,
'done',
'ls -1t "$DIR" | head -20',
].join('\n'), { stdio: 'pipe' });
if (!options.skipNginx) {
refreshNginx(config);
}
console.log('');
console.log('桌面端发布完成:');
console.log(` 版本: ${version}`);
for (const pkg of packages) {
console.log(` 安装包: ${baseUrl}/download/desktop/${path.basename(pkg)}`);
}
console.log(` 更新信息: ${baseUrl}/download/version.json`);
}
try {
main();
} catch (err) {
console.error(`[DESKTOP] ${err && err.message ? err.message : err}`);
process.exit(1);
}