diff --git a/.gitignore b/.gitignore index 47d887f..67b71e9 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,13 @@ coverage/ .nyc_output/ # 上传的文件资源(本地磁盘,不入库) uploads/ +# 后端真实部署配置(含服务器地址与 SSH 私钥路径,不入库; +# 模板见 backend/config/deploy.config.example.cjs) +backend/config/deploy.config.local.cjs +# 后端发布脚本的本地临时工作目录(发布包/文件清单) +backend/temp/ +# 导出任务生成的运行期文件(backend/upload/exports/…,不入库) +backend/upload/ # frontend build output dist/ diff --git a/backend/app/middleware/cors.js b/backend/app/middleware/cors.js new file mode 100644 index 0000000..6c8ba09 --- /dev/null +++ b/backend/app/middleware/cors.js @@ -0,0 +1,53 @@ +'use strict'; + +/** + * 跨域(CORS)中间件 + * + * 前端站点(如 http://oms.gztbyc.com)与后端 API 站点(如 http://api.oms.gztbyc.com)不同源时, + * 浏览器会对带 Authorization 头的请求先发 OPTIONS 预检,并要求响应带 Access-Control-Allow-Origin, + * 否则请求会被浏览器直接拦截(Network 面板显示 CORS error)。 + * + * 白名单来自 config.cors.origins(可用环境变量 CORS_ORIGINS 覆盖,逗号分隔;'*' 表示不限制来源)。 + * 本服务用 Bearer Token 鉴权、不使用 Cookie,故不返回 Access-Control-Allow-Credentials。 + * + * @param {Object} options 配置项(config.cors) + * @param {Array} [options.origins] 允许跨域访问的来源白名单 + * @param {Array} [options.headers] 允许的请求头 + * @param {String} [options.methods] 允许的请求方法 + * @param {Number} [options.maxAge] 预检结果缓存秒数 + * @param {Egg.Application} app egg 应用实例 + * @return {Function} egg 中间件 + */ +module.exports = (options = {}, app) => { + const origins = (options.origins || []) + .map(item => String(item).trim().replace(/\/+$/, '')) + .filter(Boolean); + const allowAll = origins.includes('*'); + const allowHeaders = (options.headers || [ 'Content-Type', 'Authorization', 'X-Requested-With' ]).join(', '); + const allowMethods = options.methods || 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS'; + const maxAge = String(options.maxAge || 86400); + + if (!origins.length) { + app.logger.warn('[cors] config.cors.origins 为空,跨域请求将全部被浏览器拦截'); + } + + return async function cors(ctx, next) { + const origin = ctx.get('Origin'); + + if (origin && (allowAll || origins.includes(origin.replace(/\/+$/, '')))) { + ctx.set('Access-Control-Allow-Origin', origin); + ctx.set('Access-Control-Allow-Methods', allowMethods); + ctx.set('Access-Control-Allow-Headers', allowHeaders); + ctx.set('Access-Control-Max-Age', maxAge); + ctx.append('Vary', 'Origin'); + } + + // 预检请求直接返回 204,不进入路由(egg 路由不注册 OPTIONS) + if (ctx.method === 'OPTIONS') { + ctx.status = 204; + return; + } + + await next(); + }; +}; diff --git a/backend/config/config.default.js b/backend/config/config.default.js index 7b408b9..6e73196 100644 --- a/backend/config/config.default.js +++ b/backend/config/config.default.js @@ -19,8 +19,31 @@ module.exports = appInfo => { // use for cookie sign key, should change to your own and keep security config.keys = appInfo.name + '_1720000000000_1234'; - // 全局中间件:requestLog 记录请求日志(洋葱模型,在响应阶段读取用户信息) - config.middleware = [ 'requestLog' ]; + // 监听端口与地址 + // ⚠️ egg 只在 env=local 时加载 config.local.js(见 egg-core 的 getTypeFiles: + // 文件清单是 config.default + config.),生产(egg-scripts start → env=prod) + // **不会**加载 config.local.js,因此端口必须写在这里,否则会退回 egg 默认的 7001。 + // 双实例发布(v1/v2)由发布脚本按实例传入 EGG_PORT,两套实例必须用不同端口。 + config.cluster = { + listen: { + port: Number(process.env.EGG_PORT || 6090), + hostname: '127.0.0.1', + }, + }; + + // 全局中间件:cors 负责跨域预检(须在最前),requestLog 记录请求日志(洋葱模型,在响应阶段读取用户信息) + config.middleware = [ 'cors', 'requestLog' ]; + + // 跨域白名单:前端站点(oms.gztbyc.com)与后端 API 站点(api.oms.gztbyc.com)不同源时需要放行 + // 可用环境变量 CORS_ORIGINS 覆盖(逗号分隔);填 '*' 表示不限制来源(不推荐,任意站点都能读取接口) + config.cors = { + origins: ( + process.env.CORS_ORIGINS || + 'http://oms.gztbyc.com,https://oms.gztbyc.com,http://api.oms.gztbyc.com,https://api.oms.gztbyc.com,http://localhost:5173,http://127.0.0.1:5173' + ).split(','), + // 预检结果缓存秒数,减少 OPTIONS 请求 + maxAge: 86400, + }; // 请求日志配置 config.requestLog = { diff --git a/backend/config/config.local.js b/backend/config/config.local.js index 847c885..3182750 100644 --- a/backend/config/config.local.js +++ b/backend/config/config.local.js @@ -10,6 +10,8 @@ module.exports = () => { const config = {}; // 开发环境监听端口,可通过 EGG_PORT 覆盖 + // ⚠️ 本文件只在 env=local(如 npm run dev)时加载;生产(egg-scripts start → env=prod) + // 不会加载它,端口与数据库请用 config.default.js + 环境变量(.env 里的 EGG_PORT / MYSQL_*) config.cluster = { listen: { port: Number(process.env.EGG_PORT || 6090), diff --git a/backend/config/deploy.config.example.cjs b/backend/config/deploy.config.example.cjs new file mode 100644 index 0000000..ff0f3af --- /dev/null +++ b/backend/config/deploy.config.example.cjs @@ -0,0 +1,94 @@ +'use strict'; + +/** + * 后端部署配置模板(此文件提交 git,供复制使用) + * + * 真实配置请复制为同目录下的 config/deploy.config.local.cjs 并填写实际值; + * 该文件已被 .gitignore 排除,**不要提交**(内含服务器地址与 SSH 私钥路径)。 + * + * 发布模型(双实例蓝绿,与 WMS 后端一致): + * /v1、/v2 两套代码目录,每次发布交替部署另一套 + * /current.md 当前活跃版本(内容为 v1 或 v2) + * /nginx-upstream.conf Nginx 反代目标:proxy_pass http://127.0.0.1:<端口>; + * 需要站点配置里 include 它(见下方「Nginx 前置」) + * /.env 服务器端真实环境变量(密钥/数据库等),不入库、 + * 发布时按需复制到各版本目录 + * /.deploy/ 发布工作目录(incoming 上传包、state 状态文件) + * + * Nginx 前置(仅首次,站点 api.oms.gztbyc.com): + * 把反向代理 `location /` 里的 `proxy_pass http://127.0.0.1:6090;` 换成 + * `include /www/wwwroot/api.oms.gztbyc.com/nginx-upstream.conf;` + * 之后每次发布只需改写该文件并 reload,即可实现零中断切换。 + * (若不改,发布脚本会在切换 upstream 时告警:新版实例已起在另一个端口, + * 但站点仍指向旧端口,需要人工处理。) + * + * 服务器端环境变量(仅首次,需手工创建一次): + * /www/wwwroot/api.oms.gztbyc.com/.env —— 真实配置,不入库 + * 可从本地 backend/.env 复制,并注意: + * - MYSQL_HOST / MYSQL_PORT / MYSQL_USER / MYSQL_PASSWORD / MYSQL_DATABASE:生产数据库 + * - REDIS_HOST / REDIS_PORT / REDIS_PASSWORD + * - JWT_SECRET:生产必须单独设置 + * - UPLOAD_DIR=/www/wwwroot/api.oms.gztbyc.com/uploads + * (上传文件必须放在 deployRoot 下、版本目录之外,v1/v2 才能共用同一份文件) + * - OMS_CALLBACK_BASE_URL=http://api.oms.gztbyc.com (可选,用于对外展示回调地址) + * 发布时若目标版本目录没有 .env,会自动从该文件复制一份(各版本目录各自保留副本, + * 已存在则不覆盖)。 + */ +module.exports = { + production: { + // —— SSH 连接 —— + host: '112.124.21.102', + port: 22, + username: 'root', + // SSH 私钥:可用绝对路径,或相对 backend 根目录的路径 + privateKeyPath: 'C:/Users/lfmingren/.ssh/112.124.21.102_id_ed25519', + sshOptions: [ 'StrictHostKeyChecking=accept-new' ], + + // —— 发布目录 —— + deployRoot: '/www/wwwroot/api.oms.gztbyc.com', + + // —— 双实例端口(v1 / v2);nginx-upstream.conf 指向当前活跃版本的端口 —— + ports: { v1: 6090, v2: 6091 }, + + // —— 版本目录内需要跨发布保留的目录/文件(清理旧代码时不会删除)—— + // node_modules 保留可让 npm install 增量安装;如需每次全新安装,去掉它即可 + // .env 必须保留:每个版本目录的 .env 里写着本实例的 EGG_PORT(v1=6090 / v2=6091), + // 被清理掉后会从 deployRoot/.env 复制一份(那份是 v1 的端口),导致 v2 起在 6090 上 + sharedDirs: [ 'logs', 'run', 'node_modules', '.env' ], + + // —— 发布包内容(相对 backend 根目录,`**` 表示该目录下全部内容)—— + // 说明:.env / uploads / logs / run 等已被 .gitignore 忽略,git ls-files 不会列出, + // 这里再写进 deployExcludePaths 作为兜底。 + deployIncludePaths: [ + '.sequelizerc', + 'app.js', + 'app/**', + 'config/**', + 'database/**', + 'package.json', + 'package-lock.json', + ], + deployExcludePaths: [ + 'config/deploy.config.local.cjs', + 'config/deploy.config.example.cjs', + '.env', + '.env.*', + 'uploads/**', + 'logs/**', + 'run/**', + 'temp/**', + 'test/**', + 'swagger.json', + ], + + // —— 启动 / 安装命令 —— + // 若需要在服务器上跑迁移(npm run migration:up)、或希望 npx sequelize-cli 可用, + // 把 installCommand 改成 'npm install'(会一并装 devDependencies) + installCommand: 'npm install --production', + // 实例端口由 config/config.local.js 的 EGG_PORT 决定(默认 6090), + // 双实例发布时请在各版本目录的 .env 里分别写 EGG_PORT(v1=6090、v2=6091) + startCommand: 'npm start', + // 健康检查:实例启动后轮询 http://127.0.0.1:<端口> + healthCheckPath: '/', + }, +}; diff --git a/backend/env.production.example b/backend/env.production.example new file mode 100644 index 0000000..0466bf4 --- /dev/null +++ b/backend/env.production.example @@ -0,0 +1,67 @@ +# OMS 后端生产环境变量模板(此文件提交 git,供服务器上创建真实 .env 用;真实 .env 不入库) +# +# 服务器上的真实文件位置:/www/wwwroot/api.oms.gztbyc.com/.env +# cp env.production.example /www/wwwroot/api.oms.gztbyc.com/.env && vim /www/wwwroot/api.oms.gztbyc.com/.env +# 各版本目录(v1 / v2)下必须各有一份 .env:config.default.js 的 dotenv 只读「进程工作目录」下的 .env, +# 而实例的工作目录就是各自的版本目录。发布脚本会在目标版本目录缺少 .env 时自动从 deployRoot/.env 复制一份 +# (已存在则不覆盖,便于个别版本目录单独调整)。 + +# —— MySQL(必填)—— +# ⚠️ 服务器本机 MySQL 监听 3306;不配置时 database/config.js 的默认值是 3307(本地开发库端口), +# 会出现 ECONNREFUSED 127.0.0.1:3307 导致实例启动失败 +MYSQL_HOST=127.0.0.1 +MYSQL_PORT=3306 +MYSQL_USER=__FILL_MYSQL_USER__ +MYSQL_PASSWORD=__FILL_MYSQL_PASSWORD__ +MYSQL_DATABASE=oms + +# —— Redis(必填)—— +# 未设置 REDIS_PASSWORD 时 config.default.js 会回落到默认值 qwe2019,生产请显式写明 +REDIS_HOST=127.0.0.1 +REDIS_PORT=6379 +REDIS_PASSWORD=__FILL_REDIS_PASSWORD__ + +# —— JWT(必填)—— +# 生产必须单独设置,不要使用 config.default.js 里的开发默认值 +JWT_SECRET=__FILL_RANDOM_SECRET__ +JWT_EXPIRES_IN=2h +JWT_RENEW_THRESHOLD=1800 + +# —— 上传文件目录(必填)—— +# 必须放在 deployRoot 下、版本目录之外,v1 / v2 才能共用同一份上传文件 +UPLOAD_DIR=/www/wwwroot/api.oms.gztbyc.com/uploads + +# —— 对外回调地址(可选)—— +# 外部系统(WMS 等)回推 /openapi 时展示/使用的地址;不配则按请求 Host 动态生成 +OMS_CALLBACK_BASE_URL=http://api.oms.gztbyc.com + +# —— 跨域白名单(可选)—— +# 不配时默认已放行 http/https 的 oms.gztbyc.com 与 localhost:5173 +# CORS_ORIGINS=http://oms.gztbyc.com,https://oms.gztbyc.com + +# —— 实例监听端口(双实例发布必填且两套必须不同)—— +# v1 → 6090、v2 → 6091,需与 backend/config/deploy.config.local.cjs 的 ports 一致。 +# 注意:Egg 端口取 config/config.local.js 的 EGG_PORT(默认 6090), +# 两套实例都用默认值会抢同一端口(EADDRINUSE,表现为健康检查一直不通过)。 +# 若使用「发布脚本传入 EGG_PORT」的方式,本项可省略;手工 npm start 启动时必须写对。 +EGG_PORT=6090 + +# —— 邮件(可选;不配置时邮箱验证码只输出到日志)—— +# SMTP_HOST= +# SMTP_PORT=465 +# SMTP_SECURE=true +# SMTP_USER= +# SMTP_PASS= +# SMTP_FROM= + +# —— AI 收件人智能识别(可选;不配置时该接口返回 400 提示)—— +# DEEPSEEK_API_KEY= + +# —— 其它可选(有默认值,一般不用改)—— +# REQUEST_LOG_KEEP_DAYS=60 +# REQUEST_LOG_MAX_BODY=2000 +# CACHE_TTL_USER=600 +# CACHE_TTL_PRINCIPAL=600 +# CACHE_TTL_PRINCIPAL_OPTIONS=600 +# EMAIL_CODE_INTERVAL=60 +# EMAIL_CODE_DAILY_LIMIT=10 diff --git a/backend/package.json b/backend/package.json index 4f57e72..104ff3e 100644 --- a/backend/package.json +++ b/backend/package.json @@ -16,7 +16,12 @@ "migration:down": "sequelize-cli db:migrate:undo", "migration:down:all": "sequelize-cli db:migrate:undo:all", "migration:create": "sequelize-cli migration:generate --name", - "swagger:export": "node scripts/export-swagger.js" + "swagger:export": "node scripts/export-swagger.js", + "deploy": "npm run deploy:prod", + "deploy:prod": "node ./script/deploy-remote.cjs production", + "deploy:init": "node ./script/init-deploy-config.cjs", + "rollback": "npm run rollback:prod", + "rollback:prod": "node ./script/rollback-remote.cjs production" }, "dependencies": { "dotenv": "^17.4.2", @@ -26,6 +31,7 @@ "egg-scripts": "^3.1.0", "egg-sequelize": "^6.0.0", "egg-swagger-doc": "^2.3.2", + "exceljs": "^4.4.0", "mysql2": "^3.24.4", "nodemailer": "^10.0.1" }, diff --git a/backend/script/deploy-lib.cjs b/backend/script/deploy-lib.cjs new file mode 100644 index 0000000..2caec61 --- /dev/null +++ b/backend/script/deploy-lib.cjs @@ -0,0 +1,498 @@ +'use strict'; + +/** + * 后端发布公共库(配置加载/校验、SSH/SCP 封装、发布包构建、远端脚本片段) + * + * 发布模型:双实例蓝绿(参考 WMS 后端) + * /{v1,v2} 两套代码目录,发布时交替部署 + * /current.md 当前活跃版本(v1 / v2) + * /nginx-upstream.conf Nginx 反代目标(proxy_pass http://127.0.0.1:<端口>;) + * /.deploy/incoming 上传的发布包 + * /.deploy/state 状态文件(当前发布版本号) + */ + +const fs = require('node:fs'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +/** backend 根目录(本文件在 backend/script 下) */ +const ROOT = path.resolve(__dirname, '..'); +const LOCAL_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.local.cjs'); +const EXAMPLE_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.example.cjs'); +const DEFAULT_ENV = 'production'; +const VERSIONS = [ 'v1', 'v2' ]; + +/** 发布包默认包含的文件(相对 backend 根目录) */ +const DEFAULT_INCLUDE_PATHS = [ + 'app.js', + 'app/**', + 'config/**', + 'database/**', + 'package.json', + 'package-lock.json', +]; + +/** 发布包默认排除(叠加在 include 之上) */ +const DEFAULT_EXCLUDE_PATHS = [ + 'config/deploy.config.local.cjs', + 'config/deploy.config.example.cjs', + '.env', + '.env.*', + 'uploads/**', + 'logs/**', + 'run/**', + 'temp/**', + 'test/**', + 'swagger.json', +]; + +/** + * bash 单引号字符串里的单引号转义(' → '\'') + * @param {String} value 原始值 + * @return {String} 可安全放进单引号中的字符串 + */ +function quoteForBash(value) { + return `'${String(value).replace(/'/g, "'\\''")}'`; +} + +/** + * 执行本地命令 + * @param {String} command 命令 + * @param {String[]} args 参数 + * @param {Object} [options] 选项(cwd / stdio) + * @return {String} stdout(trim 后) + */ +function runCommand(command, args, options = {}) { + const result = spawnSync(command, args, { + cwd: options.cwd || ROOT, + encoding: 'utf8', + stdio: options.stdio || 'pipe', + shell: false, + }); + + if (result.error) throw result.error; + + if (result.status !== 0) { + const stderr = (result.stderr || '').trim(); + const stdout = (result.stdout || '').trim(); + throw new Error(stderr || stdout || `${command} 退出码 ${result.status}`); + } + + return (result.stdout || '').trim(); +} + +/** + * 检查本地命令是否存在(不存在时给出安装提示) + * @param {String} command 命令名 + * @param {String} installHint 安装提示 + * @return {void} + */ +function ensureCommandAvailable(command, installHint) { + const result = spawnSync(command, [], { cwd: ROOT, encoding: 'utf8', stdio: 'pipe', shell: false }); + if (result.error && result.error.code === 'ENOENT') { + throw new Error(`${command} 不可用。${installHint}`); + } +} + +/** @return {String} yyyyMMddHHmmss 时间戳 */ +function getNowStamp() { + const now = new Date(); + const pad = value => String(value).padStart(2, '0'); + return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`; +} + +/** @return {String} 本地临时工作目录 backend/temp/deploy(自动创建) */ +function ensureTempDeployDir() { + const tempDir = path.join(ROOT, 'temp', 'deploy'); + fs.mkdirSync(tempDir, { recursive: true }); + return tempDir; +} + +/** + * 是否为未填写的占位值 + * @param {String} value 值 + * @return {Boolean} 是占位值返回 true + */ +function isPlaceholder(value) { + if (!value) return true; + return String(value).includes('__FILL_'); +} + +/** + * 校验并补齐配置默认值 + * @param {Object} config 原始配置 + * @param {String} envName 环境名 + * @return {Object} 规范化后的配置 + */ +function normalizeDeployConfig(config, envName) { + const sshOptions = Array.isArray(config.sshOptions) ? [ ...config.sshOptions ] : []; + const guardedOptions = [ + 'IdentitiesOnly=yes', + 'PreferredAuthentications=publickey', + 'PubkeyAuthentication=yes', + 'PasswordAuthentication=no', + 'KbdInteractiveAuthentication=no', + 'BatchMode=yes', + 'ConnectTimeout=10', + ]; + for (const option of guardedOptions) { + const key = option.split('=')[0]; + if (!sshOptions.some(item => new RegExp(`^${key}=`, 'i').test(item))) sshOptions.push(option); + } + + const deployRoot = String(config.deployRoot || '/www/wwwroot/api.oms.gztbyc.com').replace(/\/+$/, ''); + const ports = config.ports || {}; + + return { + envName, + host: config.host, + port: Number(config.port || 22), + username: config.username, + // 支持绝对路径(Windows 下如 C:/Users/x/.ssh/id_ed25519)与相对 backend 根目录的路径 + privateKeyPath: config.privateKeyPath ? path.resolve(ROOT, config.privateKeyPath) : '', + deployRoot, + ports: { v1: Number(ports.v1 || 6090), v2: Number(ports.v2 || 6091) }, + incomingDir: `${deployRoot}/.deploy/incoming`, + stateDir: `${deployRoot}/.deploy/state`, + sharedDirs: Array.isArray(config.sharedDirs) ? config.sharedDirs : [ 'logs', 'run', 'node_modules' ], + deployIncludePaths: Array.isArray(config.deployIncludePaths) && config.deployIncludePaths.length + ? config.deployIncludePaths + : DEFAULT_INCLUDE_PATHS, + deployExcludePaths: Array.isArray(config.deployExcludePaths) && config.deployExcludePaths.length + ? config.deployExcludePaths + : DEFAULT_EXCLUDE_PATHS, + installCommand: config.installCommand || 'npm install --production', + startCommand: config.startCommand || 'npm start', + healthCheckPath: config.healthCheckPath || '/', + sshOptions, + }; +} + +/** + * 校验配置必填项 + * @param {Object} config 原始配置 + * @param {String} configPath 配置文件路径 + * @param {String} envName 环境名 + * @return {void} + */ +function validateDeployConfig(config, configPath, envName) { + if (!config) throw new Error(`${configPath} 中未找到 ${envName} 配置。`); + + const missing = []; + if (isPlaceholder(config.host)) missing.push('host'); + if (isPlaceholder(config.username)) missing.push('username'); + if (isPlaceholder(config.privateKeyPath)) missing.push('privateKeyPath'); + if (missing.length) { + throw new Error(`请先完善配置字段: ${missing.join(', ')}。配置文件: ${configPath}`); + } + + const resolvedPrivateKeyPath = path.resolve(ROOT, config.privateKeyPath); + if (!fs.existsSync(resolvedPrivateKeyPath)) { + throw new Error(`SSH 私钥不存在: ${resolvedPrivateKeyPath}。请修正 ${configPath} 中的 privateKeyPath。`); + } +} + +/** + * 加载本地部署配置 + * @param {String} [envName] 环境名,默认 production + * @return {Object} 规范化后的配置 + */ +function loadDeployConfig(envName = DEFAULT_ENV) { + if (!fs.existsSync(LOCAL_CONFIG_PATH)) { + throw new Error(`缺少本地部署配置 ${LOCAL_CONFIG_PATH}。请复制 ${EXAMPLE_CONFIG_PATH} 为 deploy.config.local.cjs 并填写 SSH 信息。`); + } + + delete require.cache[require.resolve(LOCAL_CONFIG_PATH)]; + const loaded = require(LOCAL_CONFIG_PATH); + const config = loaded[envName]; + validateDeployConfig(config, LOCAL_CONFIG_PATH, envName); + return normalizeDeployConfig(config, envName); +} + +/** + * 构造 ssh/scp 公共参数 + * @param {Object} config 部署配置 + * @return {String[]} 参数数组 + */ +function buildSshBaseArgs(config) { + const args = [ '-p', String(config.port), '-i', config.privateKeyPath ]; + for (const option of config.sshOptions) args.push('-o', option); + return args; +} + +/** + * 在服务器上执行 bash 脚本(通过 bash -lc,保证加载登录环境里的 node/npm) + * @param {Object} config 部署配置 + * @param {String} remoteScript 脚本内容 + * @param {Object} [options] 选项(stdio) + * @return {String} 输出 + */ +function runSsh(config, remoteScript, options = {}) { + const args = [ + ...buildSshBaseArgs(config), + `${config.username}@${config.host}`, + `bash -lc ${quoteForBash(remoteScript)}`, + ]; + return runCommand('ssh', args, { stdio: options.stdio || 'inherit' }); +} + +/** + * 上传文件到服务器 + * @param {Object} config 部署配置 + * @param {String} localPath 本地路径 + * @param {String} remotePath 远端路径 + * @return {String} 输出 + */ +function runScp(config, localPath, remotePath) { + const args = [ '-P', String(config.port), '-i', config.privateKeyPath ]; + for (const option of config.sshOptions) args.push('-o', option); + args.push(localPath, `${config.username}@${config.host}:${remotePath}`); + return runCommand('scp', args, { stdio: 'inherit' }); +} + +/** + * 判断路径是否命中规则(`a/**` 匹配 a 及其全部子项,其余为精确匹配) + * @param {String} filePath 相对路径 + * @param {String} rule 规则 + * @return {Boolean} 命中返回 true + */ +function pathMatchesRule(filePath, rule) { + const normalizedPath = String(filePath || '').replace(/\\/g, '/'); + const normalizedRule = String(rule || '').replace(/\\/g, '/').trim(); + if (!normalizedRule) return false; + if (normalizedRule.endsWith('/**')) { + const prefix = normalizedRule.slice(0, -3); + return normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`); + } + return normalizedPath === normalizedRule; +} + +/** + * 列出可发布文件:以 git 的视角取文件(天然排除 .gitignore 里的 .env / uploads 等), + * 再按 include / exclude 规则过滤 + * @param {Object} config 部署配置 + * @return {String[]} 相对 backend 根目录的文件列表 + */ +function listDeployableFiles(config) { + const output = runCommand('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ], { cwd: ROOT }); + + return Array.from(new Set( + output + .split(/\r?\n/) + .map(item => item.trim()) + .filter(Boolean) + .filter(item => !item.startsWith('.git/')) + .filter(item => fs.existsSync(path.join(ROOT, item))) + .filter(item => config.deployIncludePaths.some(rule => pathMatchesRule(item, rule))) + .filter(item => !config.deployExcludePaths.some(rule => pathMatchesRule(item, rule))) + )); +} + +/** + * 构建本地发布包(tar.gz) + * @param {String} stamp 时间戳 + * @param {Object} config 部署配置 + * @return {{ archivePath: String, fileCount: Number }} 发布包路径与文件数 + */ +function buildArchive(stamp, config) { + const tempDir = ensureTempDeployDir(); + const listPath = path.join(tempDir, `deploy-files-${stamp}.txt`); + const archivePath = path.join(tempDir, `release-${stamp}.tar.gz`); + const files = listDeployableFiles(config); + + if (!files.length) throw new Error('未找到可发布文件(请检查 deployIncludePaths 配置)。'); + + fs.writeFileSync(listPath, `${files.join('\n')}\n`, 'utf8'); + runCommand('tar', [ '-czf', archivePath, '-T', listPath ], { stdio: 'inherit', cwd: ROOT }); + + return { archivePath, fileCount: files.length }; +} + +/** + * 生成远端清理守卫:`find . -mindepth 1 -maxdepth 1 <守卫> -exec rm -rf {} +` + * 保留 .deploy 与 sharedDirs(logs / run / node_modules 等) + * @param {String[]} sharedDirs 需保留的目录名 + * @return {String} find 命令的守卫参数 + */ +function buildRemoteCleanupGuard(sharedDirs) { + const preserved = [ '.deploy', ...sharedDirs ]; + return preserved.map(item => `! -name ${quoteForBash(item)}`).join(' '); +} + +/** + * 生成「按目录停止 egg 进程」的远端脚本行: + * 通过 ps 匹配命令行里的版本目录 + node,先 kill 再 kill -9 兜底。 + * 不用 `npm run stop`(egg-scripts 按 title 停止,v1/v2 同 title 会互相误杀)。 + * @param {String} dirPath 目标目录绝对路径 + * @param {String} label 日志前缀 + * @return {String[]} 脚本行 + */ +function buildScopedEggStopLines(dirPath, label) { + const matchNode = '$2 == "node" || $2 ~ /\\/node$/'; + const awkProgram = `index($0, root) && (${matchNode}) { print $1 }`; + return [ + `TARGET_DIR=${quoteForBash(dirPath)}`, + `TARGET_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" ${quoteForBash(awkProgram)})`, + 'if [ -z "$TARGET_PIDS" ]; then', + ` echo "${label}_NONE"`, + 'else', + ` echo "${label} $TARGET_PIDS"`, + ' kill $TARGET_PIDS || true', + ' sleep 5', + ` REMAIN_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" ${quoteForBash(awkProgram)})`, + ' if [ -n "$REMAIN_PIDS" ]; then', + ` echo "${label}_FORCE $REMAIN_PIDS"`, + ' kill -9 $REMAIN_PIDS || true', + ' fi', + 'fi', + ]; +} + +/** + * 读取远端当前活跃版本 + * @param {Object} config 部署配置 + * @return {String} 'v1' / 'v2';尚未初始化(无 current.md)时返回空字符串 + */ +function readRemoteCurrentVersion(config) { + const currentMdPath = `${config.deployRoot}/current.md`; + const script = `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`; + const output = String(runSsh(config, script, { stdio: 'pipe' }) || '').replace(/\r/g, '').trim(); + + if (!output) return ''; + if (!VERSIONS.includes(output)) { + throw new Error(`远端 ${currentMdPath} 内容无效: "${output}",期望 v1 或 v2。`); + } + return output; +} + +/** + * 取另一个版本标识(v1 ↔ v2) + * @param {String} version 当前版本,为空时返回首次部署使用的 v1 + * @return {String} 目标版本 + */ +function otherVersion(version) { + if (!version) return 'v1'; + if (!VERSIONS.includes(version)) throw new Error(`版本标识无效: ${version}`); + return version === 'v1' ? 'v2' : 'v1'; +} + +/** + * 取版本对应端口 + * @param {Object} config 部署配置 + * @param {String} version 版本标识 + * @return {Number} 端口 + */ +function portOf(config, version) { + if (!VERSIONS.includes(version)) throw new Error(`版本标识无效: ${version}`); + return config.ports[version]; +} + +/** + * 生成「释放指定端口」的远端脚本行(结束占用该端口的残留进程) + * @param {Number} port 端口 + * @return {String[]} 脚本行 + */ +function buildFreePortLines(port) { + return [ + `TARGET_PORT=${port}`, + 'PORT_PID=$(ss -tlnp 2>/dev/null | awk -v p=":$TARGET_PORT " \'index($0, p) { print $0 }\' | grep -oP \'pid=\\K[0-9]+\' | head -1 || true)', + 'if [ -n "$PORT_PID" ]; then', + ' echo "端口 $TARGET_PORT 被进程 $PORT_PID 占用,先停止..."', + ' kill "$PORT_PID" 2>/dev/null || true', + ' sleep 5', + ' PORT_PID_CHECK=$(ss -tlnp 2>/dev/null | awk -v p=":$TARGET_PORT " \'index($0, p) { print $0 }\' | grep -oP \'pid=\\K[0-9]+\' | head -1 || true)', + ' if [ -n "$PORT_PID_CHECK" ]; then', + ' echo "端口 $TARGET_PORT 仍有残留进程 $PORT_PID_CHECK,强制停止"', + ' kill -9 "$PORT_PID_CHECK" 2>/dev/null || true', + ' fuser -k "$TARGET_PORT/tcp" 2>/dev/null || true', + ' fi', + 'else', + ' echo "端口 $TARGET_PORT 空闲"', + 'fi', + ]; +} + +/** + * 生成「启动实例」的远端脚本行(后台运行,输出重定向到启动日志) + * @param {String} dirPath 版本目录 + * @param {String} startCommand 启动命令(如 npm start) + * @param {String} logPath 启动日志路径 + * @return {String[]} 脚本行 + */ +function buildStartInstanceLines(dirPath, startCommand, logPath) { + return [ + `cd ${quoteForBash(dirPath)}`, + `nohup bash -lc ${quoteForBash(startCommand)} > ${quoteForBash(logPath)} 2>&1 < /dev/null &`, + `echo "已启动实例: ${dirPath},启动日志: ${logPath}"`, + ]; +} + +/** + * 生成「健康检查」的远端脚本行(轮询 http://127.0.0.1:<端口><路径>) + * @param {Number} port 端口 + * @param {String} healthPath 检查路径 + * @param {String} label 日志标签 + * @param {Number} [attempts] 重试次数 + * @param {Number} [interval] 重试间隔秒数 + * @return {String[]} 脚本行 + */ +function buildHealthCheckLines(port, healthPath, label, attempts = 10, interval = 2) { + return [ + `TARGET_PORT=${port}`, + `HEALTH_PATH=${quoteForBash(healthPath)}`, + `for attempt in $(seq 1 ${attempts}); do`, + ' if curl -fsS --connect-timeout 2 --max-time 3 "http://127.0.0.1:$TARGET_PORT$HEALTH_PATH" >/dev/null 2>&1; then', + ` echo "健康检查通过: ${label} 已就绪(端口 $TARGET_PORT)"`, + ' break', + ' fi', + ` if [ "$attempt" -eq ${attempts} ]; then`, + ` echo "健康检查超时: ${label}(端口 $TARGET_PORT)未就绪" >&2`, + ' exit 1', + ' fi', + ` sleep ${interval}`, + 'done', + ]; +} + +/** + * 生成「切换 Nginx upstream 并 reload」的远端脚本行 + * @param {String} upstreamPath upstream 文件路径 + * @param {Number} port 目标端口 + * @return {String[]} 脚本行 + */ +function buildNginxSwitchLines(upstreamPath, port) { + return [ + `printf 'proxy_pass http://127.0.0.1:%s;\\n' ${port} > ${quoteForBash(upstreamPath)}`, + 'nginx -t && nginx -s reload', + `echo "Nginx upstream 已切换至 127.0.0.1:${port}"`, + ]; +} + +module.exports = { + ROOT, + VERSIONS, + DEFAULT_ENV, + LOCAL_CONFIG_PATH, + EXAMPLE_CONFIG_PATH, + buildArchive, + buildFreePortLines, + buildHealthCheckLines, + buildNginxSwitchLines, + buildRemoteCleanupGuard, + buildScopedEggStopLines, + buildSshBaseArgs, + buildStartInstanceLines, + ensureCommandAvailable, + ensureTempDeployDir, + getNowStamp, + listDeployableFiles, + loadDeployConfig, + otherVersion, + pathMatchesRule, + portOf, + quoteForBash, + readRemoteCurrentVersion, + runCommand, + runScp, + runSsh, +}; diff --git a/backend/script/deploy-remote.cjs b/backend/script/deploy-remote.cjs new file mode 100644 index 0000000..b69dfb1 --- /dev/null +++ b/backend/script/deploy-remote.cjs @@ -0,0 +1,202 @@ +'use strict'; + +/** + * 后端发布脚本(双实例蓝绿) + * + * npm run deploy # 等价 npm run deploy:prod + * npm run deploy:prod + * + * 流程: + * 1. 本地按 git 文件清单打发布包(不含 .env / uploads / logs 等) + * 2. 读取远端 current.md,确定目标版本(v1 ↔ v2 交替;首次发布用 v1) + * 3. 上传到 /.deploy/incoming,清理目标版本目录(保留 logs/run/node_modules)后解压 + * 4. 补齐 .env、安装生产依赖、释放目标端口、启动新实例 + * 5. 健康检查通过后切换 Nginx upstream(nginx -t && nginx -s reload) + * 6. 停止旧实例、记录当前发布版本号 + * 健康检查失败:回滚 current.md、杀掉新实例,旧实例不受影响(线上不中断) + */ + +const fs = require('node:fs'); +const path = require('node:path'); +const { + ROOT, + buildArchive, + buildFreePortLines, + buildHealthCheckLines, + buildNginxSwitchLines, + buildRemoteCleanupGuard, + buildScopedEggStopLines, + buildStartInstanceLines, + ensureCommandAvailable, + getNowStamp, + loadDeployConfig, + otherVersion, + portOf, + quoteForBash, + readRemoteCurrentVersion, + runCommand, + runScp, + runSsh, +} = require('./deploy-lib.cjs'); + +function main() { + const envName = process.argv[2] || 'production'; + const config = loadDeployConfig(envName); + + ensureCommandAvailable('git', '请先安装 Git 并确保 git 在 PATH 中。'); + ensureCommandAvailable('tar', '请先安装 tar,Windows 10/11 通常已内置 bsdtar。'); + ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); + ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。'); + + // 1. 远端当前活跃版本 → 本次目标版本 + const currentVersion = readRemoteCurrentVersion(config); + const targetVersion = otherVersion(currentVersion); + const targetPort = portOf(config, targetVersion); + const targetDir = `${config.deployRoot}/${targetVersion}`; + const oldDir = currentVersion ? `${config.deployRoot}/${currentVersion}` : ''; + + if (currentVersion) { + console.log(`远端当前活跃版本: ${currentVersion}(端口 ${portOf(config, currentVersion)})`); + } else { + console.log('远端尚未初始化(无 current.md),本次作为首次发布,落到 v1'); + } + console.log(`本次发布目标: ${targetVersion} → ${targetDir}(端口 ${targetPort})`); + + // 2. 本地打包 + const stamp = getNowStamp(); + const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')); + const gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]); + const releaseVersion = `v${packageJson.version || '0.0.0'}-${stamp}-${gitCommitShort}`; + const { archivePath, fileCount } = buildArchive(stamp, config); + const remoteArchive = `${config.incomingDir}/${path.basename(archivePath)}`; + console.log(`发布包已生成: ${archivePath}(${fileCount} 个文件,版本号 ${releaseVersion})`); + + // 3. 远端准备目录并上传发布包 + runSsh(config, [ + 'set -euo pipefail', + `mkdir -p ${quoteForBash(targetDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.stateDir)}`, + `echo "远端目录已就绪: ${targetDir}"`, + ].join('\n')); + + runScp(config, archivePath, remoteArchive); + console.log(`发布包已上传: ${remoteArchive}`); + + // 4. 清理目标目录 → 解压 → 补齐 .env → 安装生产依赖 + const envFile = `${config.deployRoot}/.env`; + const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs); + const installScript = [ + 'set -euo pipefail', + `TARGET_DIR=${quoteForBash(targetDir)}`, + `REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`, + `ENV_FILE=${quoteForBash(envFile)}`, + 'cd "$TARGET_DIR"', + // 清理上一次遗留的代码(保留 .deploy 与 sharedDirs:logs / run / node_modules) + `find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`, + 'tar -xzf "$REMOTE_ARCHIVE" -C "$TARGET_DIR"', + 'rm -f "$REMOTE_ARCHIVE"', + // 服务器端真实环境变量只维护一份(/.env),首次落到某版本目录时复制过去; + // 已存在则不覆盖,便于个别版本目录单独调整 + 'if [ ! -f "$TARGET_DIR/.env" ]; then', + ' if [ -f "$ENV_FILE" ]; then', + ' cp -a "$ENV_FILE" "$TARGET_DIR/.env"', + ' echo "ENV_COPIED $ENV_FILE -> $TARGET_DIR/.env"', + ' else', + ' echo "WARN_ENV_MISSING 未找到 $ENV_FILE,请先在该文件写入生产环境变量(数据库、JWT_SECRET 等)" >&2', + ' fi', + 'else', + ' echo "ENV_KEPT $TARGET_DIR/.env(已存在,未覆盖)"', + 'fi', + config.installCommand, + ].join('\n'); + runSsh(config, installScript); + console.log(`远端代码已更新并安装依赖: ${targetDir}`); + + // 5. 释放目标端口(防止残留进程占用导致新实例起不来) + runSsh(config, [ 'set -euo pipefail', ...buildFreePortLines(targetPort) ].join('\n')); + const startLogPath = `/tmp/oms-${targetVersion}-start.log`; + + // 6. 记录 current.md 并启动新实例 + runSsh(config, [ + 'set -euo pipefail', + `printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(`${config.deployRoot}/current.md`)}`, + ...buildStartInstanceLines(targetDir, config.startCommand, startLogPath), + ].join('\n')); + + // 7. 健康检查(20 秒内轮询;失败则回滚记录并清理新实例,旧实例继续服务) + const healthCheckScript = [ + 'set -euo pipefail', + ...buildHealthCheckLines(targetPort, config.healthCheckPath, targetVersion), + ].join('\n'); + + try { + runSsh(config, healthCheckScript); + } catch (err) { + console.error(`[ERROR] 新实例健康检查失败: ${err.message}`); + console.error(`[ERROR] 发布中止(未切换 Nginx),请查看启动日志 ${startLogPath}`); + + if (currentVersion) { + try { + runSsh(config, [ + 'set -euo pipefail', + `printf '%s\\n' ${quoteForBash(currentVersion)} > ${quoteForBash(`${config.deployRoot}/current.md`)}`, + `echo "current.md 已回滚为 ${currentVersion}"`, + ].join('\n')); + } catch (revertErr) { + console.error(`[ERROR] current.md 回滚失败: ${revertErr.message}`); + } + } + + try { + runSsh(config, [ + 'set -euo pipefail', + ...buildScopedEggStopLines(targetDir, 'STOP_FAILED_NEW'), + ].join('\n')); + } catch (killErr) { + console.error(`[ERROR] 清理失败的新实例出错: ${killErr.message}`); + } + + console.error(`[ERROR] 发布失败: ${envName} -> ${config.username}@${config.host}:${targetDir}`); + if (currentVersion) console.error(`[ERROR] 旧实例(${currentVersion})仍在服务,线上不受影响`); + process.exit(1); + } + + // 8. 切换 Nginx upstream(仅健康检查通过后执行) + const upstreamPath = `${config.deployRoot}/nginx-upstream.conf`; + try { + runSsh(config, [ 'set -euo pipefail', ...buildNginxSwitchLines(upstreamPath, targetPort) ].join('\n')); + } catch (err) { + console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`); + console.warn(`[WARN] 请人工确认 ${upstreamPath} 内容并执行 nginx -t && nginx -s reload`); + console.warn('[WARN] 若站点配置尚未 include 该文件,请先按 config/deploy.config.example.cjs 顶部说明改一次站点配置'); + } + + // 9. 停止旧实例 + if (currentVersion) { + try { + runSsh(config, [ + 'set -euo pipefail', + ...buildScopedEggStopLines(oldDir, 'STOP_OLD'), + `echo "旧实例 ${currentVersion} 已停止"`, + ].join('\n')); + } catch (err) { + console.warn(`[WARN] 停止旧实例失败: ${err.message},请人工确认并停止 ${oldDir} 下的进程`); + } + } + + // 10. 记录当前发布版本号 + try { + runSsh(config, [ + 'set -euo pipefail', + `printf '%s\\n' ${quoteForBash(releaseVersion)} > ${quoteForBash(`${config.stateDir}/current-release.txt`)}`, + `echo "当前发布版本: ${releaseVersion}"`, + ].join('\n')); + } catch (err) { + console.warn(`[WARN] 记录发布版本号失败: ${err.message}`); + } + + console.log(`发布完成: ${config.username}@${config.host}:${targetDir}`); + console.log(`活跃版本: ${targetVersion}(端口 ${targetPort})`); + console.log(`发布版本号: ${releaseVersion}`); +} + +main(); diff --git a/backend/script/init-deploy-config.cjs b/backend/script/init-deploy-config.cjs new file mode 100644 index 0000000..5d98ce7 --- /dev/null +++ b/backend/script/init-deploy-config.cjs @@ -0,0 +1,21 @@ +'use strict'; + +/** + * 初始化后端部署配置:把 config/deploy.config.example.cjs 复制为 config/deploy.config.local.cjs。 + * deploy.config.local.cjs 含服务器地址与 SSH 私钥路径,已被 .gitignore 排除,不要提交。 + * + * 用法:npm run deploy:init + */ + +const fs = require('node:fs'); +const { EXAMPLE_CONFIG_PATH, LOCAL_CONFIG_PATH } = require('./deploy-lib.cjs'); + +if (fs.existsSync(LOCAL_CONFIG_PATH)) { + console.log('ℹ️ config/deploy.config.local.cjs 已存在,未覆盖。'); + console.log(` 如需重新生成,请先删除该文件:${LOCAL_CONFIG_PATH}`); + process.exit(0); +} + +fs.copyFileSync(EXAMPLE_CONFIG_PATH, LOCAL_CONFIG_PATH); +console.log('✅ 已生成 config/deploy.config.local.cjs'); +console.log(' 请按实际服务器信息确认 host / username / privateKeyPath / deployRoot / ports,然后执行 npm run deploy。'); diff --git a/backend/script/rollback-remote.cjs b/backend/script/rollback-remote.cjs new file mode 100644 index 0000000..1bbdd12 --- /dev/null +++ b/backend/script/rollback-remote.cjs @@ -0,0 +1,131 @@ +'use strict'; + +/** + * 后端回滚脚本(双实例蓝绿:切回另一套版本目录,无需重新构建/上传) + * + * npm run rollback # 回滚到上一个版本(v1 ↔ v2) + * npm run rollback -- --to=v1 # 指定切回某个版本 + * + * 流程:启动目标版本实例 → 健康检查通过 → 切换 Nginx upstream → 记录 current.md → 停止当前实例 + * 目标版本目录不可用(未发布过)时会直接报错,当前实例不受影响。 + */ + +const { + VERSIONS, + buildFreePortLines, + buildHealthCheckLines, + buildNginxSwitchLines, + buildScopedEggStopLines, + buildStartInstanceLines, + ensureCommandAvailable, + loadDeployConfig, + otherVersion, + portOf, + quoteForBash, + readRemoteCurrentVersion, + runSsh, +} = require('./deploy-lib.cjs'); + +/** + * 解析 --to=v1|v2 参数 + * @param {String[]} argv 参数数组 + * @return {String} 目标版本(未指定时返回空字符串) + */ +function parseTargetArg(argv) { + const arg = argv.find(item => item.startsWith('--to=')); + if (!arg) return ''; + const value = arg.slice('--to='.length).trim(); + if (!VERSIONS.includes(value)) { + throw new Error(`--to 取值无效: ${value}(支持 v1 / v2)`); + } + return value; +} + +function main() { + const envName = process.argv[2] || 'production'; + const config = loadDeployConfig(envName); + ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); + + const currentVersion = readRemoteCurrentVersion(config); + if (!currentVersion) { + throw new Error(`远端 ${config.deployRoot}/current.md 不存在或为空,没有可回滚的版本(请先执行 npm run deploy)。`); + } + + const targetVersion = parseTargetArg(process.argv.slice(3)) || otherVersion(currentVersion); + if (targetVersion === currentVersion) { + throw new Error(`目标版本与当前活跃版本相同(${targetVersion}),无需回滚。`); + } + + const currentPort = portOf(config, currentVersion); + const targetPort = portOf(config, targetVersion); + const currentDir = `${config.deployRoot}/${currentVersion}`; + const targetDir = `${config.deployRoot}/${targetVersion}`; + const startLogPath = `/tmp/oms-${targetVersion}-start.log`; + + console.log(`当前活跃版本: ${currentVersion}(端口 ${currentPort})`); + console.log(`回滚目标: ${targetVersion} → ${targetDir}(端口 ${targetPort})`); + + // 1. 校验目标版本可用;缺依赖时补装 + runSsh(config, [ + 'set -euo pipefail', + `TARGET_DIR=${quoteForBash(targetDir)}`, + 'if [ ! -f "$TARGET_DIR/package.json" ]; then', + ' echo "目标版本目录不可用:$TARGET_DIR/package.json 不存在(该版本可能尚未发布过)" >&2', + ' exit 1', + 'fi', + 'if [ ! -d "$TARGET_DIR/node_modules" ]; then', + ' echo "目标版本缺少 node_modules,先安装依赖..."', + ` ( cd "$TARGET_DIR" && ${config.installCommand} )`, + 'fi', + ].join('\n')); + + // 2. 释放目标端口并启动目标实例 + runSsh(config, [ 'set -euo pipefail', ...buildFreePortLines(targetPort) ].join('\n')); + runSsh(config, [ + 'set -euo pipefail', + ...buildStartInstanceLines(targetDir, config.startCommand, startLogPath), + ].join('\n')); + + // 3. 健康检查(失败则清理刚启动的实例,当前实例继续服务) + try { + runSsh(config, [ + 'set -euo pipefail', + ...buildHealthCheckLines(targetPort, config.healthCheckPath, targetVersion), + ].join('\n')); + } catch (err) { + console.error(`[ERROR] 回滚目标健康检查失败: ${err.message}`); + console.error(`[ERROR] 回滚中止(未切换 Nginx),请查看启动日志 ${startLogPath}`); + try { + runSsh(config, [ + 'set -euo pipefail', + ...buildScopedEggStopLines(targetDir, 'STOP_ROLLBACK_TARGET'), + ].join('\n')); + } catch (killErr) { + console.error(`[ERROR] 清理回滚目标实例出错: ${killErr.message}`); + } + console.error(`[ERROR] 当前实例(${currentVersion})仍在服务,线上不受影响`); + process.exit(1); + } + + // 4. 切换 Nginx upstream + const upstreamPath = `${config.deployRoot}/nginx-upstream.conf`; + try { + runSsh(config, [ 'set -euo pipefail', ...buildNginxSwitchLines(upstreamPath, targetPort) ].join('\n')); + } catch (err) { + console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`); + console.warn(`[WARN] 请人工确认 ${upstreamPath} 内容并执行 nginx -t && nginx -s reload`); + } + + // 5. 记录 current.md 并停止原实例 + runSsh(config, [ + 'set -euo pipefail', + `printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(`${config.deployRoot}/current.md`)}`, + ...buildScopedEggStopLines(currentDir, 'STOP_ROLLED_BACK'), + `echo "current.md 已更新为 ${targetVersion}"`, + ].join('\n')); + + console.log(`回滚完成: 线上已切回 ${targetVersion}(端口 ${targetPort})`); + console.log(`如需再次前进,执行 npm run rollback -- --to=${currentVersion}`); +} + +main();