'use strict'; const { Controller } = require('egg'); const crypto = require('crypto'); const { toSuccess, toFailure } = require('../lib/api_response'); /** 日志内容长度上限 */ const LOG_BODY_MAX = 65535; 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'; } /** * 截断日志内容到上限长度。 * @param {string} value 原始字符串。 * @return {string} 截断后的字符串。 */ truncateLogBody(value) { const str = typeof value === 'string' ? value : JSON.stringify(value); if (str.length > LOG_BODY_MAX) { return str.substring(0, LOG_BODY_MAX); } return str; } /** * 仓库 API 统一入口,记录请求日志并转发到 warehouse service。 * @return {Promise} 无返回值,结果写入 ctx.body。 */ async index() { const { ctx, app } = this; const startTime = Date.now(); const logId = 'WL-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'); const query = ctx.query || {}; let result; try { 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'; // 异常情况下 result 为 undefined,构造一个 fallback result = { ok: false, httpStatus: 500, message: error.message || '未知错误', warehouseId: null, appKey: String(query.app_key || '').trim() || null, }; } finally { // 异步写日志,不阻塞响应 try { const logData = { log_id: logId, app_key: (result && result.appKey) || String(query.app_key || '').trim() || null, method: String(query.method || '').trim() || null, warehouse_id: (result && result.warehouseId) || null, url: ctx.request.href || null, http_status: ctx.status || (result && result.httpStatus) || null, body: this.truncateLogBody(ctx.request.rawBody || JSON.stringify(ctx.request.body || {})), result: this.truncateLogBody(typeof ctx.body === 'string' ? ctx.body : JSON.stringify(ctx.body || {})), use_time: Date.now() - startTime, created_at: new Date(), }; app.fileWriter.writeRecord('warehouse-logs', logData).catch(writeErr => { ctx.logger.error('[warehouse-log-sink] 写入文件失败: ' + writeErr.message); }); } catch (logErr) { ctx.logger.error('[warehouse-log] 日志记录异常: ' + logErr.message); } } } } module.exports = WarehouseController;