410 lines
11 KiB
JavaScript
410 lines
11 KiB
JavaScript
const soap = require('soap');
|
||
const businessDict = require('../dict/businessDict');
|
||
|
||
const LOCAL_CACHE_CLEANUP_INTERVAL_MS = 60 * 1000;
|
||
const LOCAL_CACHE_STATE_KEY = '__wmsLocalCacheState';
|
||
|
||
/**
|
||
* 获取缓存日志记录器。
|
||
*
|
||
* @param {Object} app 应用实例。
|
||
* @return {Object|null} 日志对象。
|
||
*/
|
||
function getCacheLogger(app) {
|
||
return app && (app.logger || app.coreLogger) ? (app.logger || app.coreLogger) : null;
|
||
}
|
||
|
||
/**
|
||
* 获取或初始化进程内缓存状态。
|
||
*
|
||
* @param {Object} app 应用实例。
|
||
* @return {Object|null} 进程内缓存状态。
|
||
*/
|
||
function getLocalCacheState(app) {
|
||
if (!app) {
|
||
return null;
|
||
}
|
||
|
||
if (!app[LOCAL_CACHE_STATE_KEY]) {
|
||
app[LOCAL_CACHE_STATE_KEY] = {
|
||
store: new Map(),
|
||
cleanupTimer: null,
|
||
lastCleanupAt: 0,
|
||
};
|
||
}
|
||
|
||
return app[LOCAL_CACHE_STATE_KEY];
|
||
}
|
||
|
||
/**
|
||
* 规范化缓存过期秒数。
|
||
*
|
||
* @param {*} expireSeconds 过期秒数。
|
||
* @return {number} 规范化后的秒数。
|
||
*/
|
||
function normalizeExpireSeconds(expireSeconds) {
|
||
const ttl = Number(expireSeconds);
|
||
if (!Number.isFinite(ttl) || ttl <= 0) {
|
||
return 0;
|
||
}
|
||
return Math.floor(ttl);
|
||
}
|
||
|
||
/**
|
||
* 复制缓存值,避免进程内缓存被外部引用直接修改。
|
||
*
|
||
* @param {*} value 缓存值。
|
||
* @return {*} 复制后的缓存值。
|
||
*/
|
||
function cloneCacheValue(value) {
|
||
if (value === null || value === undefined) {
|
||
return value;
|
||
}
|
||
|
||
try {
|
||
return JSON.parse(JSON.stringify(value));
|
||
} catch (error) {
|
||
return value;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 清理已经过期的进程内缓存。
|
||
*
|
||
* @param {Object} state 进程内缓存状态。
|
||
* @return {number} 清理的条目数。
|
||
*/
|
||
function cleanupLocalCache(state) {
|
||
if (!state || !state.store) {
|
||
return 0;
|
||
}
|
||
|
||
const now = Date.now();
|
||
let removedCount = 0;
|
||
|
||
for (const [ cacheKey, cacheEntry ] of state.store.entries()) {
|
||
if (!cacheEntry || cacheEntry.expireAt <= now) {
|
||
state.store.delete(cacheKey);
|
||
removedCount += 1;
|
||
}
|
||
}
|
||
|
||
state.lastCleanupAt = now;
|
||
return removedCount;
|
||
}
|
||
|
||
/**
|
||
* 启动进程内缓存的定时清理任务。
|
||
*
|
||
* @param {Object} app 应用实例。
|
||
* @return {Object|null} 进程内缓存状态。
|
||
*/
|
||
function ensureLocalCacheCleanupTimer(app) {
|
||
const state = getLocalCacheState(app);
|
||
if (!state || state.cleanupTimer) {
|
||
return state;
|
||
}
|
||
|
||
state.cleanupTimer = setInterval(() => {
|
||
cleanupLocalCache(state);
|
||
}, LOCAL_CACHE_CLEANUP_INTERVAL_MS);
|
||
|
||
if (state.cleanupTimer && typeof state.cleanupTimer.unref === 'function') {
|
||
state.cleanupTimer.unref();
|
||
}
|
||
|
||
return state;
|
||
}
|
||
|
||
/**
|
||
* 获取 Redis 缓存客户端。
|
||
*
|
||
* @param {Object} app 应用实例。
|
||
* @return {Object|null} Redis 缓存客户端。
|
||
*/
|
||
function getRedisCacheClient(app) {
|
||
try {
|
||
return app && app.redis && typeof app.redis.get === 'function' ? app.redis.get('cache') : null;
|
||
} catch (error) {
|
||
const logger = getCacheLogger(app);
|
||
if (logger && typeof logger.warn === 'function') {
|
||
logger.warn('[CacheRedisUnavailable] 获取 Redis 缓存客户端失败', error.message);
|
||
}
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 将值写入进程内缓存。
|
||
*
|
||
* @param {Object} app 应用实例。
|
||
* @param {string} cacheKey 缓存键。
|
||
* @param {*} data 缓存数据。
|
||
* @param {number} expireSeconds 过期秒数。
|
||
*/
|
||
function setLocalCacheValue(app, cacheKey, data, expireSeconds) {
|
||
const state = ensureLocalCacheCleanupTimer(app);
|
||
if (!state) {
|
||
return;
|
||
}
|
||
|
||
const ttl = normalizeExpireSeconds(expireSeconds);
|
||
if (ttl <= 0) {
|
||
state.store.delete(cacheKey);
|
||
return;
|
||
}
|
||
|
||
state.store.set(cacheKey, {
|
||
value: cloneCacheValue(data),
|
||
expireAt: Date.now() + (ttl * 1000),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 从进程内缓存读取值。
|
||
*
|
||
* @param {Object} app 应用实例。
|
||
* @param {string} cacheKey 缓存键。
|
||
* @return {*} 缓存值或 null。
|
||
*/
|
||
function getLocalCacheValue(app, cacheKey) {
|
||
const state = getLocalCacheState(app);
|
||
if (!state) {
|
||
return null;
|
||
}
|
||
|
||
const cacheEntry = state.store.get(cacheKey);
|
||
if (!cacheEntry) {
|
||
return null;
|
||
}
|
||
|
||
if (cacheEntry.expireAt <= Date.now()) {
|
||
state.store.delete(cacheKey);
|
||
return null;
|
||
}
|
||
|
||
return cloneCacheValue(cacheEntry.value);
|
||
}
|
||
|
||
/**
|
||
* 从进程内缓存删除值。
|
||
*
|
||
* @param {Object} app 应用实例。
|
||
* @param {string} cacheKey 缓存键。
|
||
*/
|
||
function deleteLocalCacheValue(app, cacheKey) {
|
||
const state = getLocalCacheState(app);
|
||
if (!state) {
|
||
return;
|
||
}
|
||
|
||
state.store.delete(cacheKey);
|
||
}
|
||
|
||
/**
|
||
* 将 Redis 返回的数据解析为对象。
|
||
*
|
||
* @param {string} cacheValue Redis 缓存字符串。
|
||
* @return {*} 解析后的值。
|
||
*/
|
||
function parseRedisCacheValue(cacheValue) {
|
||
if (cacheValue === undefined || cacheValue === null) {
|
||
return null;
|
||
}
|
||
|
||
return JSON.parse(cacheValue);
|
||
}
|
||
|
||
/**
|
||
* 使用超时保护执行 Redis 命令,避免 Redis 卡顿拖慢接口响应。
|
||
*
|
||
* @param {Object} app 应用实例。
|
||
* @param {Promise<*>} commandPromise Redis 命令 Promise。
|
||
* @param {string} commandName Redis 命令名。
|
||
* @return {Promise<*>} Redis 命令执行结果。
|
||
*/
|
||
async function withRedisCommandTimeout(app, commandPromise, commandName) {
|
||
const timeoutConfig = Number(app && app.config ? app.config.cacheRedisCommandTimeoutMs : 0);
|
||
const timeoutMs = Number.isFinite(timeoutConfig) && timeoutConfig > 0 ? timeoutConfig : 800;
|
||
|
||
let timeoutId = null;
|
||
|
||
const timeoutPromise = new Promise((resolve, reject) => {
|
||
timeoutId = setTimeout(() => {
|
||
const timeoutError = new Error(`Redis 命令执行超时: ${commandName}, timeout=${timeoutMs}ms`);
|
||
timeoutError.code = 'CACHE_REDIS_TIMEOUT';
|
||
reject(timeoutError);
|
||
}, timeoutMs);
|
||
|
||
if (timeoutId && typeof timeoutId.unref === 'function') {
|
||
timeoutId.unref();
|
||
}
|
||
});
|
||
|
||
try {
|
||
return await Promise.race([ commandPromise, timeoutPromise ]);
|
||
} finally {
|
||
if (timeoutId) {
|
||
clearTimeout(timeoutId);
|
||
}
|
||
}
|
||
}
|
||
module.exports = {
|
||
get businessDict() {
|
||
return businessDict;
|
||
},
|
||
getBusinessTypeName(code) {
|
||
const dict = this.businessDict.BUSINESS_TYPE || {};
|
||
for (const key in dict) {
|
||
if (dict[key].code === code) {
|
||
return dict[key].name;
|
||
}
|
||
}
|
||
return code;
|
||
},
|
||
getOperationCodeName(code) {
|
||
return this.businessDict.OPERATION_CODE?.[code] || code;
|
||
},
|
||
getPlatformName(code) {
|
||
return this.businessDict.PLATFORM_CODE?.[code] || code;
|
||
},
|
||
getExternalLogTypeName(type) {
|
||
return this.businessDict.EXTERNAL_LOG_TYPE?.[type] || type;
|
||
},
|
||
formatDate(date, formatStr = 'YYYY-MM-DD HH:mm:ss') {
|
||
const targetDate = date instanceof Date ? date : new Date(date);
|
||
const year = targetDate.getFullYear();
|
||
const month = String(targetDate.getMonth() + 1).padStart(2, '0');
|
||
const day = String(targetDate.getDate()).padStart(2, '0');
|
||
const hours = String(targetDate.getHours()).padStart(2, '0');
|
||
const minutes = String(targetDate.getMinutes()).padStart(2, '0');
|
||
const seconds = String(targetDate.getSeconds()).padStart(2, '0');
|
||
|
||
return formatStr
|
||
.replace('YYYY', year)
|
||
.replace('MM', month)
|
||
.replace('DD', day)
|
||
.replace('HH', hours)
|
||
.replace('mm', minutes)
|
||
.replace('ss', seconds);
|
||
},
|
||
async wsdl(methodName, args) {
|
||
try {
|
||
const wsdlUrl = 'http://ye4s.com/webservice/ws?wsdl';
|
||
const obj = {};
|
||
args.forEach((value, index) => {
|
||
obj['arg' + index] = value;
|
||
});
|
||
const client = await soap.createClientAsync(wsdlUrl);
|
||
const result = await client[methodName + 'Async'](obj);
|
||
return result[0];
|
||
} catch (error) {
|
||
throw error;
|
||
}
|
||
},
|
||
/**
|
||
* 写入缓存。
|
||
*
|
||
* Redis 可用时优先写入 Redis;当 Redis 不可用或写入失败时,自动降级到进程内缓存。
|
||
*
|
||
* @param {string} cacheKey 缓存键。
|
||
* @param {*} data 缓存数据。
|
||
* @param {number} [expireSeconds=300] 过期秒数。
|
||
* @return {Promise<void>}
|
||
*/
|
||
async setCacheAsync(cacheKey, data, expireSeconds = 300) {
|
||
const ttl = normalizeExpireSeconds(expireSeconds);
|
||
const cacheRedis = getRedisCacheClient(this);
|
||
|
||
if (ttl <= 0) {
|
||
if (cacheRedis && typeof cacheRedis.del === 'function') {
|
||
try {
|
||
await withRedisCommandTimeout(this, cacheRedis.del(cacheKey), 'del');
|
||
} catch (error) {
|
||
const logger = getCacheLogger(this);
|
||
if (logger && typeof logger.warn === 'function') {
|
||
logger.warn('[CacheRedisDeleteError] Redis 删除缓存失败', error.message, cacheKey);
|
||
}
|
||
}
|
||
}
|
||
|
||
deleteLocalCacheValue(this, cacheKey);
|
||
return;
|
||
}
|
||
|
||
if (cacheRedis && typeof cacheRedis.setex === 'function') {
|
||
try {
|
||
await withRedisCommandTimeout(this, cacheRedis.setex(cacheKey, ttl, JSON.stringify(data)), 'setex');
|
||
|
||
setLocalCacheValue(this, cacheKey, data, ttl);
|
||
|
||
return;
|
||
} catch (error) {
|
||
const logger = getCacheLogger(this);
|
||
if (logger && typeof logger.warn === 'function') {
|
||
logger.warn('[CacheRedisSetError] Redis 写入缓存失败,已降级到进程内缓存', error.message, cacheKey);
|
||
}
|
||
}
|
||
}
|
||
|
||
setLocalCacheValue(this, cacheKey, data, ttl);
|
||
},
|
||
/**
|
||
* 删除缓存。
|
||
*
|
||
* Redis 可用时优先删除 Redis;无论 Redis 是否可用,都会同步清理进程内缓存。
|
||
*
|
||
* @param {string} cacheKey 缓存键。
|
||
* @return {Promise<void>}
|
||
*/
|
||
async delCacheAsync(cacheKey) {
|
||
if (!cacheKey) {
|
||
return;
|
||
}
|
||
|
||
const cacheRedis = getRedisCacheClient(this);
|
||
|
||
if (cacheRedis && typeof cacheRedis.del === 'function') {
|
||
try {
|
||
await withRedisCommandTimeout(this, cacheRedis.del(cacheKey), 'del');
|
||
} catch (error) {
|
||
const logger = getCacheLogger(this);
|
||
if (logger && typeof logger.warn === 'function') {
|
||
logger.warn('[CacheRedisDeleteError] Redis 删除缓存失败', error.message, cacheKey);
|
||
}
|
||
}
|
||
}
|
||
|
||
deleteLocalCacheValue(this, cacheKey);
|
||
},
|
||
/**
|
||
* 读取缓存。
|
||
*
|
||
* Redis 可用时优先读取 Redis;当 Redis 不可用、读取失败或命中为空时,自动回退到进程内缓存。
|
||
*
|
||
* @param {string} cacheKey 缓存键。
|
||
* @return {Promise<*>} 缓存数据,未命中时返回 null。
|
||
*/
|
||
async getCacheAsync(cacheKey) {
|
||
const cacheRedis = getRedisCacheClient(this);
|
||
|
||
if (cacheRedis && typeof cacheRedis.get === 'function') {
|
||
try {
|
||
const data = await withRedisCommandTimeout(this, cacheRedis.get(cacheKey), 'get');
|
||
if (data === undefined || data === null) {
|
||
return null;
|
||
}
|
||
|
||
return parseRedisCacheValue(data);
|
||
} catch (error) {
|
||
const logger = getCacheLogger(this);
|
||
if (logger && typeof logger.warn === 'function') {
|
||
logger.warn('[CacheRedisGetError] Redis 读取缓存失败,已回退到进程内缓存', error.message, cacheKey);
|
||
}
|
||
}
|
||
}
|
||
|
||
return getLocalCacheValue(this, cacheKey);
|
||
},
|
||
};
|