feat(deploy): 部署脚本增加端口强制清理 + 健康检查超时延长至 20s

- 新增步骤 5.5:启动前通过 ss + fuser -k 强制释放目标端口残留进程
- 健康检查重试次数从 5 次增加到 10 次,最长等待从 10s 延长至 20s
- 健康检查失败日志增加启动日志路径提示
This commit is contained in:
liufumingren 2026-08-01 15:31:00 +08:00
parent fbb12cf205
commit 5759c1fb19
10 changed files with 723 additions and 19 deletions

View File

@ -0,0 +1,56 @@
'use strict';
const { Controller } = require('egg');
const { toSuccess, toFailure } = require('../lib/api_response');
class WarehouseController extends Controller {
/**
* 输出仓库 API 统一失败响应。
* @param {number} httpStatus HTTP 状态码。
* @param {string} message 错误消息。
* @param {number} [code=httpStatus] 业务错误码。
* @return {void} 无返回值。
*/
writeFailureResponse(httpStatus, message, code = httpStatus) {
const { ctx } = this;
ctx.status = httpStatus;
ctx.body = toFailure({
message,
httpStatus,
code,
});
ctx.type = 'application/json';
}
/**
* 仓库 API 统一入口,仅负责转发到 warehouse service 并输出标准响应。
* @return {Promise<void>} 无返回值,结果写入 ctx.body。
*/
async index() {
const { ctx } = this;
try {
const result = await ctx.service.warehouse.processRequest();
if (result.ok) {
ctx.status = Number(result.httpStatus) || 200;
ctx.body = toSuccess(result.data, result.message || 'ok');
ctx.type = 'application/json';
return;
}
this.writeFailureResponse(
Number(result.httpStatus) || 500,
String(result.message || '请求失败'),
Number(result.code) || Number(result.httpStatus) || 500
);
ctx.type = 'application/json';
return;
} catch (error) {
const message = String(error && error.message || '请求失败');
this.writeFailureResponse(500, `接口错误: ${message}`, 500);
ctx.type = 'application/json';
}
}
}
module.exports = WarehouseController;

View File

@ -44,6 +44,9 @@ module.exports = app => {
// OpenAPI 入口
router.post('/openapi', controller.openapi.index);
// 仓库 OpenAPI 入口
router.post('/warehouse', controller.warehouse.index);
// 打印模板
router.get('/template/xml/:id', controller.template.xml);

View File

@ -6,29 +6,35 @@ const apiSignLib = require('../../lib/api_sign');
const API_APP_CACHE_PREFIX = 'openapi:api-app';
const API_APP_CACHE_TTL_SECONDS = 300;
const OPENAPI_INTERFACE_TYPE_ID = 2;
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
class ApiSignService extends Service {
/**
* 构建 API 应用配置缓存键。
* @param {string} appKey 开放接口 app_key。
* @param {number} [interfaceTypeId] 接口类型 ID,用于区分不同入口的缓存。
* @return {string} 缓存键。
*/
getApiAppCacheKey(appKey) {
return `${API_APP_CACHE_PREFIX}:${String(appKey || '').trim()}`;
getApiAppCacheKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) {
const prefix = interfaceTypeId === WAREHOUSE_INTERFACE_TYPE_ID
? 'warehouse:api-app'
: API_APP_CACHE_PREFIX;
return `${prefix}:${String(appKey || '').trim()}`;
}
/**
* 根据 app_key 查询 API 应用可用配置(带缓存)。
* @param {string} appKey 开放接口 app_key。
* @param {number} [interfaceTypeId=2] 接口类型 ID,2=货主级 / 3=仓库级。
* @return {Promise<Object>} 查询结果,包含应用主键与密钥。
*/
async getApiAppConfigByAppKey(appKey) {
async getApiAppConfigByAppKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) {
const normalizedAppKey = String(appKey || '').trim();
if (!normalizedAppKey) {
throw new Error('appKey 不能为空');
}
const cacheKey = this.getApiAppCacheKey(normalizedAppKey);
const cacheKey = this.getApiAppCacheKey(normalizedAppKey, interfaceTypeId);
if (this.app && typeof this.app.getCacheAsync === 'function') {
try {
const cached = await this.app.getCacheAsync(cacheKey);
@ -41,9 +47,10 @@ class ApiSignService extends Service {
}
const row = await this.ctx.model.ApiApp.findOne({
attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id' ],
attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id', 'warehouse_id' ],
where: {
self_app_key: normalizedAppKey,
interface_type_id: interfaceTypeId,
},
raw: true,
});
@ -56,10 +63,6 @@ class ApiSignService extends Service {
throw new Error('API 应用已禁用');
}
if (Number(row.interface_type_id) !== OPENAPI_INTERFACE_TYPE_ID) {
throw new Error('app_key 无效或不可用');
}
if (!row.self_app_secret) {
throw new Error('API 应用缺少 self_app_secret 配置');
}
@ -68,6 +71,8 @@ class ApiSignService extends Service {
id: row.id,
appKey: row.self_app_key,
selfAppSecret: row.self_app_secret,
interfaceTypeId: Number(row.interface_type_id),
warehouseId: row.warehouse_id ? Number(row.warehouse_id) : null,
};
if (this.app && typeof this.app.setCacheAsync === 'function') {
@ -83,10 +88,11 @@ class ApiSignService extends Service {
/**
* 根据 app_key 查询 API 应用密钥信息。
* @param {string} appKey 开放接口 app_key。
* @param {number} [interfaceTypeId=2] 接口类型 ID。
* @return {Promise<Object>} 查询结果,包含应用主键与密钥。
*/
async getApiAppSecretByAppKey(appKey) {
return await this.getApiAppConfigByAppKey(appKey);
async getApiAppSecretByAppKey(appKey, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID) {
return await this.getApiAppConfigByAppKey(appKey, interfaceTypeId);
}
/**
@ -97,12 +103,13 @@ class ApiSignService extends Service {
* @param {*} [options.body] 请求体。
* @param {string} options.providedSign 请求中携带的 sign。
* @param {string[]} [options.ignoreKeys] 额外忽略的 query 字段。
* @param {number} [options.interfaceTypeId=2] 接口类型 ID。
* @return {Promise<Object>} 验签结果。
*/
async verifyRequestSignByAppKey({ appKey, query = {}, body, providedSign, ignoreKeys } = {}) {
async verifyRequestSignByAppKey({ appKey, query = {}, body, providedSign, ignoreKeys, interfaceTypeId = OPENAPI_INTERFACE_TYPE_ID } = {}) {
let appConfig;
try {
appConfig = await this.getApiAppSecretByAppKey(appKey);
appConfig = await this.getApiAppSecretByAppKey(appKey, interfaceTypeId);
} catch (error) {
return {
ok: false,
@ -137,6 +144,8 @@ class ApiSignService extends Service {
sign: verifyResult.expectedSign,
appId: appConfig.id,
appKey: appConfig.appKey,
interfaceTypeId: appConfig.interfaceTypeId,
warehouseId: appConfig.warehouseId,
};
}
}

View File

@ -706,7 +706,7 @@ class ExpressPlatformService extends MainService {
let playload = {
object_Id: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单唯一标识必须为字符串
orderno: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串
plattradeno: order.source_order_codes || order.delivery_order_code || '',
plattradeno: order.sys_platform_code === 'DY'? order.source_order_codes.split(",")[0] : order.source_order_codes || order.delivery_order_code || '',
ismultiplepieces: order.package_count > 1 ? 1 : 0,
logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '',
logistictype: order.logistics_code || '',

274
app/service/warehouse.js Normal file
View File

@ -0,0 +1,274 @@
'use strict';
const Service = require('egg').Service;
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
class WarehouseService extends Service {
/**
* 解析 warehouse method,拆分为服务路径与动作名。
* @param {string} methodName method 名称。
* @return {{ servicePath: string, actionName: string }} 解析结果。
*/
resolveWarehouseMethod(methodName = '') {
const method = String(methodName || '').trim();
const parts = method.split('.').filter(Boolean);
const actionName = parts.pop() || '';
const servicePath = parts.join('.');
return {
servicePath,
actionName,
};
}
/**
* 根据服务路径查找 warehouseMethods 下的目标服务。
* @param {string} servicePath 服务路径。
* @return {Object|null} 目标服务实例。
*/
getWarehouseMethodService(servicePath = '') {
const { ctx } = this;
const pathSegments = String(servicePath || '').split('.').filter(Boolean);
let methodService = ctx.service.warehouseMethods;
if (pathSegments.length === 0) {
return methodService;
}
for (const segment of pathSegments) {
methodService = methodService && methodService[segment];
}
return methodService || null;
}
/**
* 分发 warehouse method 到 warehouseMethods 目录。
* 分发前统一注入仓库上下文(warehouseId/appKey)。
* @param {string} methodName method 名称。
* @param {Object} body 请求体。
* @param {Object} query 请求 query。
* @param {Object} warehouseInfo 仓库上下文信息。
* @return {Promise<Object>} method 执行结果。
*/
async dispatchWarehouseMethod(methodName, body, query, warehouseInfo) {
const { servicePath, actionName } = this.resolveWarehouseMethod(methodName);
const methodService = this.getWarehouseMethodService(servicePath);
if (!methodService || typeof methodService[actionName] !== 'function') {
return {
ok: false,
httpStatus: 400,
code: 400,
message: `warehouse method 不存在: ${methodName}`,
data: null,
};
}
// 统一注入仓库上下文到方法服务实例
if (warehouseInfo && typeof methodService.setInfo === 'function') {
methodService.setInfo(
null, // storeId
warehouseInfo.warehouseId,
warehouseInfo.appKey,
null, // customerId
null // warehouseCode
);
}
const methodResult = await methodService[actionName]({
body,
query,
});
return {
ok: true,
httpStatus: 200,
code: 1,
message: 'ok',
data: methodResult,
};
}
/**
* 校验 warehouse 基础 query 参数。
* @param {Object} query 请求 query 参数。
* @return {boolean} 是否通过基础参数校验。
*/
validateWarehouseParams(query) {
const requiredFields = [ 'method', 'v', 'timestamp' ];
for (const field of requiredFields) {
if (!query || !query[field]) {
return false;
}
}
if (typeof query.method !== 'string' || !query.method.includes('.')) {
return false;
}
return true;
}
/**
* 读取并解析 JSON 请求体。
* @return {Promise<Object>} 解析后的 JSON 对象。
*/
async parseJsonBody() {
const { ctx } = this;
let jsonData = '';
if (ctx.request.rawBody) {
jsonData = ctx.request.rawBody;
} else if (ctx.request.body !== undefined) {
jsonData = typeof ctx.request.body === 'string'
? ctx.request.body
: JSON.stringify(ctx.request.body);
} else {
jsonData = await new Promise((resolve, reject) => {
let data = '';
ctx.req.on('data', chunk => {
data += chunk;
});
ctx.req.on('end', () => {
resolve(data);
});
ctx.req.on('error', reject);
});
}
jsonData = jsonData ? String(jsonData) : '';
if (!jsonData || jsonData.trim() === '') {
return {
ok: false,
httpStatus: 400,
code: 400,
message: 'json数据为空',
data: null,
};
}
try {
return JSON.parse(jsonData);
} catch (error) {
return {
ok: false,
httpStatus: 400,
code: 400,
message: 'json数据解析错误',
data: null,
};
}
}
/**
* 提取并归一化 warehouse 所需的 appKey 与 sign。
* @param {Object} query 请求 query 参数。
* @return {{ appKey: string, providedSign: string }} 归一化后的关键信息。
*/
normalizeSignFields(query = {}) {
const appKey = String(query.app_key || query.appkey || query.self_app_key || '').trim();
const providedSign = String(query.sign || query.signature || '').trim();
return {
appKey,
providedSign,
};
}
/**
* 处理 warehouse 请求并返回统一结果。
* 核心差异:使用 interface_type_id=3(仓库级),无需合约关联,直接取 warehouse_id。
* @return {Promise<Object>} 统一结果对象。
*/
async processRequest() {
const { ctx } = this;
const query = ctx.query || {};
if (!this.validateWarehouseParams(query)) {
return {
ok: false,
httpStatus: 400,
code: 400,
message: '参数缺失或错误: method/v/timestamp',
data: null,
};
}
// 时间戳时效校验(±10分钟)
const nowTs = Math.floor(Date.now() / 1000);
const reqTs = Number(query.timestamp);
if (!Number.isFinite(reqTs) || Math.abs(nowTs - reqTs) > 600) {
return {
ok: false,
httpStatus: 400,
code: 400,
message: `时间戳已过期或无效,服务器时间: ${nowTs}`,
data: null,
};
}
const body = await this.parseJsonBody();
if (body && body.ok === false) {
return body;
}
const { appKey, providedSign } = this.normalizeSignFields(query);
if (!appKey) {
return {
ok: false,
httpStatus: 400,
code: 400,
message: '参数缺失或错误: app_key',
data: null,
};
}
const { systems: systemsService } = ctx.service;
const apiSignService = systemsService.apiSign;
// 仓库级验签:interface_type_id = 3
const verifyResult = await apiSignService.verifyRequestSignByAppKey({
appKey,
query,
body,
providedSign,
interfaceTypeId: WAREHOUSE_INTERFACE_TYPE_ID,
});
if (!verifyResult.ok) {
return {
ok: false,
httpStatus: 401,
code: 401,
message: `签名校验失败: ${verifyResult.message}`,
data: null,
};
}
// 仓库级无需合约关联,直接使用 api_app.warehouse_id
const warehouseId = verifyResult.warehouseId;
if (!warehouseId) {
return {
ok: false,
httpStatus: 403,
code: 403,
message: 'API 应用未绑定仓库',
data: null,
};
}
const queryWithAppKey = {
...query,
app_key: verifyResult.appKey,
};
return await this.dispatchWarehouseMethod(query.method, body, queryWithAppKey, {
warehouseId,
appKey: verifyResult.appKey,
});
}
}
module.exports = WarehouseService;

View File

@ -0,0 +1,22 @@
'use strict';
const MainService = require('../main');
class WarehouseIndexService extends MainService {
/**
* 心跳接口,返回服务可用性与仓库上下文信息。
* @return {Promise<Object>} 心跳响应。
*/
async ping() {
const { warehouseId, appKey } = this.getInfo();
return {
warehouse_id: warehouseId,
app_key: appKey,
server_time: Math.floor(Date.now() / 1000),
status: 'ok',
};
}
}
module.exports = WarehouseIndexService;

View File

@ -0,0 +1,88 @@
'use strict';
const MainService = require('../main');
class WarehouseStoreService extends MainService {
/**
* 查询当前仓库下已授权的货主列表。
* 返回货主基本信息(id、公司名、联系人、联系电话、授权状态)。
* @param {Object} options 请求参数。
* @param {Object} options.body 请求体。
* @return {Promise<Object>} 货主列表。
*/
async list({ body = {} } = {}) {
const { ctx } = this;
const { warehouseId } = this.getInfo();
const page = Math.max(1, Number(body.page) || 1);
const pageSize = Math.min(100, Math.max(1, Number(body.pageSize) || 20));
// 通过 store_warehouse 关联查询已授权的货主
const { StoreWarehouse, Store } = ctx.model;
const where = {
warehouse_id: warehouseId,
auth_status: 2, // 已通过
warehouse_use_status: 1, // 仓库侧可用
};
const { count: total, rows } = await StoreWarehouse.findAndCountAll({
attributes: [
'id',
'store_id',
'auth_status',
'auth_start',
'auth_end',
'store_remask',
'warehouse_remask',
],
where,
include: [
{
model: Store,
as: 'store',
attributes: [
'id',
'company_name',
'contact_person',
'contact_phone',
'status',
],
required: true,
where: {
status: 1, // 启用
},
},
],
offset: (page - 1) * pageSize,
limit: pageSize,
order: [[ 'id', 'DESC' ]],
raw: true,
});
const list = rows.map(row => ({
store_id: row['store.id'],
company_name: row['store.company_name'],
contact_person: row['store.contact_person'],
contact_phone: row['store.contact_phone'],
contract_id: row.id,
auth_status: row.auth_status,
auth_start: row.auth_start,
auth_end: row.auth_end,
store_remask: row.store_remask,
warehouse_remask: row.warehouse_remask,
}));
return {
list,
pagination: {
page,
pageSize,
total,
totalPages: Math.ceil(total / pageSize),
},
};
}
}
module.exports = WarehouseStoreService;

View File

@ -0,0 +1,22 @@
[
{
"version": "2026.08.01-warehouse-01",
"date": "2026-08-01",
"type": "added",
"summary": "新增 /warehouse 仓库开放 API 入口,支持仓库级外部适配器 HMAC-SHA256 签名鉴权调用,首批上线 index.ping 心跳 + store.list 货主列表",
"methods": [
"index.ping",
"store.list"
],
"notes": [
"POST /warehouse 为新增入口,独立于 /openapi(货主级),鉴权使用 interface_type_id=3 的仓库 API 应用(由 apiApp 模块管理)。",
"签名算法与 /openapi 完全一致:query 参数字典序 + body 拼接 → HMAC-SHA256 → hex。",
"时间戳 ±10 分钟有效期,Redis 缓存 API 应用配置 300 秒(缓存前缀 warehouse:api-app)。",
"无需 StoreWarehouse 合约关联,直接通过 api_app.warehouse_id 确定仓库上下文。",
"index.ping:无需 body 参数,返回 warehouse_id / app_key / server_time / status。",
"store.list:分页查询当前仓库下已授权的货主,通过 wms_store_warehouse 关联 wms_store,仅返回 auth_status=2 + store.status=1 + warehouse_use_status=1 的记录。",
"api_sign.js 改造:getApiAppConfigByAppKey 新增 interfaceTypeId 参数(默认 2 保持向后兼容),warehouse 入口传 3,查询增加 interface_type_id 条件并返回 warehouse_id。"
],
"module": "warehouse"
}
]

203
methods/warehouse.json Normal file
View File

@ -0,0 +1,203 @@
{
"module": "warehouse",
"description": "仓库开放 API 统一入口,供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 HMAC-SHA256 签名鉴权(interface_type_id=3)",
"version": "1.0.0",
"updatedAt": "2026-08-01",
"http": {
"path": "/warehouse",
"method": "POST"
},
"headers": [],
"methods": {
"groups": [
{
"groupName": "基础模块",
"module": "index",
"list": [
{
"method": "index.ping",
"description": "心跳接口,验证仓库 API 应用连通性,返回仓库上下文与应用信息",
"isNeedAuth": false,
"isNeedLogin": false,
"headers": [],
"params": [],
"response": [
{
"name": "warehouse_id",
"type": "number",
"required": true,
"description": "当前仓库 ID"
},
{
"name": "app_key",
"type": "string",
"required": true,
"description": "当前请求的 AppKey"
},
{
"name": "server_time",
"type": "number",
"required": true,
"description": "服务器 Unix 时间戳(秒)"
},
{
"name": "status",
"type": "string",
"required": true,
"description": "服务状态,正常时返回 ok"
}
],
"errors": [],
"notes": [
"模块:基础模块",
"方法部署位置:warehouseMethods/index.ping",
"无需 body 参数,GET query 参数满足 method/v/timestamp/app_key/sign 即可",
"timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400"
]
}
]
},
{
"groupName": "货主模块",
"module": "store",
"list": [
{
"method": "store.list",
"description": "查询当前仓库下已授权的货主列表,返回货主基本信息与授权状态(需 auth_status=2 已通过 + store.status=1 启用 + warehouse_use_status=1 可用)",
"isNeedAuth": false,
"isNeedLogin": false,
"headers": [],
"params": [
{
"name": "page",
"type": "number",
"required": false,
"source": "body",
"description": "页码,默认 1",
"defaultValue": 1
},
{
"name": "pageSize",
"type": "number",
"required": false,
"source": "body",
"description": "每页数量,默认 20,最大 100",
"defaultValue": 20
}
],
"response": [
{
"name": "list",
"type": "array",
"required": true,
"description": "货主列表",
"children": [
{
"name": "store_id",
"type": "number",
"required": true,
"description": "货主 ID(wms_store.id)"
},
{
"name": "company_name",
"type": "string",
"required": true,
"description": "公司全称"
},
{
"name": "contact_person",
"type": "string",
"required": true,
"description": "联系人"
},
{
"name": "contact_phone",
"type": "string",
"required": true,
"description": "联系电话"
},
{
"name": "contract_id",
"type": "number",
"required": true,
"description": "授权关系 ID(wms_store_warehouse.id)"
},
{
"name": "auth_status",
"type": "number",
"required": true,
"description": "授权状态:2=已通过"
},
{
"name": "auth_start",
"type": "string",
"required": false,
"description": "授权开始日期"
},
{
"name": "auth_end",
"type": "string",
"required": false,
"description": "授权结束日期"
},
{
"name": "store_remask",
"type": "string",
"required": false,
"description": "商家备注"
},
{
"name": "warehouse_remask",
"type": "string",
"required": false,
"description": "仓库备注"
}
]
},
{
"name": "pagination",
"type": "object",
"required": true,
"description": "分页信息",
"children": [
{
"name": "page",
"type": "number",
"required": true,
"description": "当前页码"
},
{
"name": "pageSize",
"type": "number",
"required": true,
"description": "每页数量"
},
{
"name": "total",
"type": "number",
"required": true,
"description": "总记录数"
},
{
"name": "totalPages",
"type": "number",
"required": true,
"description": "总页数"
}
]
}
],
"errors": [],
"notes": [
"模块:货主模块",
"方法部署位置:warehouseMethods/store.list",
"仓库隔离:自动使用当前 API 应用绑定的 warehouse_id",
"仅返回已通过授权(auth_status=2)、仓库侧可用(warehouse_use_status=1)、货主启用(store.status=1)的记录",
"分页查询:默认 20 条/页,最大 100 条/页"
]
}
]
}
]
}
}

View File

@ -148,6 +148,33 @@ function main() {
const startLogPath = `/tmp/wms-${targetVersion}-start.log`;
const currentMdPath = `${config.deployRoot}/current.md`;
// 5.5. 强制清理目标端口残留进程,防止端口占用导致启动失败
const killPortScript = [
'set -euo pipefail',
`TARGET_PORT=${targetPort}`,
'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 -9 "$PORT_PID" 2>/dev/null || true',
' sleep 1',
' 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 "[WARN] 端口 $TARGET_PORT 仍有残留进程 $PORT_PID_CHECK,尝试再次强制停止..."`,
' fuser -k "$TARGET_PORT/tcp" 2>/dev/null || true',
' fi',
` echo "端口 $TARGET_PORT 已释放"`,
'else',
` echo "端口 $TARGET_PORT 空闲,无需清理"`,
'fi',
].join('\n');
try {
const killPortOutput = runSsh(config, killPortScript, { stdio: 'pipe' });
console.log(String(killPortOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 端口 ${targetPort} 清理失败: ${err.message}`);
}
// 6. 更新远端 current.md 并启动新实例
const switchAndStartScript = [
'set -euo pipefail',
@ -162,17 +189,17 @@ function main() {
const switchOutput = runSsh(config, switchAndStartScript, { stdio: 'pipe' });
console.log(String(switchOutput || '').trim());
// 6.5. 健康检查新实例(curl 循环等待,最多 10 秒)
// 6.5. 健康检查新实例(curl 循环等待,最多 20 秒)
const oldDir = `${config.deployRoot}/${currentVersion}`;
const healthCheckScript = [
'set -euo pipefail',
`TARGET_PORT=${targetPort}`,
'for attempt in $(seq 1 5); do',
'for attempt in $(seq 1 10); do',
' if curl -fsS --connect-timeout 2 --max-time 3 "http://127.0.0.1:$TARGET_PORT/" >/dev/null 2>&1; then',
` echo "新实例 (${targetVersion}) 健康检查通过 (端口 $TARGET_PORT)"`,
' break',
' fi',
' if [ "$attempt" -eq 5 ]; then',
' if [ "$attempt" -eq 10 ]; then',
` echo "新实例 (${targetVersion}) 健康检查超时 (端口 $TARGET_PORT)" >&2`,
' exit 1',
' fi',
@ -185,8 +212,8 @@ function main() {
console.log(String(healthOutput || '').trim());
} catch (err) {
// 健康检查失败 → 不做切换,回滚 current.md 并清理失败的新实例
console.error(`[ERROR] 新实例健康检查失败 (10s 超时): ${err.message}`);
console.error(`[ERROR] 发布中止:不切换 Nginx upstream,不停旧实例`);
console.error(`[ERROR] 新实例健康检查失败 (20s 超时): ${err.message}`);
console.error(`[ERROR] 发布中止:不切换 Nginx upstream,不停旧实例。可检查启动日志 ${startLogPath}`);
// 回滚:将 current.md 恢复为旧版本
const revertCurrentMdScript = [