@kne/fastify-task 3.0.0-alpha.6 → 3.0.0-alpha.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +841 -314
- package/index.js +47 -6
- package/libs/controllers/main.js +1 -2
- package/libs/helpers/task-service-context.js +558 -0
- package/libs/models/task.js +7 -3
- package/libs/services/append.js +45 -0
- package/libs/services/callback.js +109 -0
- package/libs/services/executor.js +10 -0
- package/libs/services/main.js +7 -836
- package/libs/services/scheduler.js +230 -0
- package/libs/services/statistics.js +18 -27
- package/libs/services/task.js +230 -0
- package/package.json +2 -2
- package/libs/utils/cache-manager.js +0 -162
- package/libs/utils/config.js +0 -326
- package/libs/utils/errors.js +0 -191
- package/libs/utils/modules/task-executor.js +0 -196
- package/libs/utils/modules/task-processor.js +0 -185
- package/libs/utils/security-validator.js +0 -203
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 内存缓存管理器
|
|
3
|
-
* 提供简单的缓存功能,支持过期时间
|
|
4
|
-
*/
|
|
5
|
-
class CacheManager {
|
|
6
|
-
constructor(defaultTTL = 300000) { // 默认5分钟过期
|
|
7
|
-
this.cache = new Map();
|
|
8
|
-
this.defaultTTL = defaultTTL;
|
|
9
|
-
this.timers = new Map();
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* 设置缓存
|
|
14
|
-
* @param {string} key - 缓存键
|
|
15
|
-
* @param {*} value - 缓存值
|
|
16
|
-
* @param {number} ttl - 过期时间(毫秒)
|
|
17
|
-
*/
|
|
18
|
-
set(key, value, ttl = this.defaultTTL) {
|
|
19
|
-
// 清除现有的定时器
|
|
20
|
-
if (this.timers.has(key)) {
|
|
21
|
-
clearTimeout(this.timers.get(key));
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
// 设置缓存
|
|
25
|
-
this.cache.set(key, {
|
|
26
|
-
value,
|
|
27
|
-
expiresAt: Date.now() + ttl
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
// 设置过期定时器
|
|
31
|
-
const timer = setTimeout(() => {
|
|
32
|
-
this.delete(key);
|
|
33
|
-
}, ttl);
|
|
34
|
-
timer.unref();
|
|
35
|
-
|
|
36
|
-
this.timers.set(key, timer);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* 获取缓存
|
|
41
|
-
* @param {string} key - 缓存键
|
|
42
|
-
* @returns {*} 缓存值,如果不存在或已过期返回 null
|
|
43
|
-
*/
|
|
44
|
-
get(key) {
|
|
45
|
-
const item = this.cache.get(key);
|
|
46
|
-
|
|
47
|
-
if (!item) {
|
|
48
|
-
return null;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// 检查是否过期
|
|
52
|
-
if (Date.now() > item.expiresAt) {
|
|
53
|
-
this.delete(key);
|
|
54
|
-
return null;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
return item.value;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* 删除缓存
|
|
62
|
-
* @param {string} key - 缓存键
|
|
63
|
-
*/
|
|
64
|
-
delete(key) {
|
|
65
|
-
if (this.timers.has(key)) {
|
|
66
|
-
clearTimeout(this.timers.get(key));
|
|
67
|
-
this.timers.delete(key);
|
|
68
|
-
}
|
|
69
|
-
this.cache.delete(key);
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* 清空所有缓存
|
|
74
|
-
*/
|
|
75
|
-
clear() {
|
|
76
|
-
// 清除所有定时器
|
|
77
|
-
for (const timer of this.timers.values()) {
|
|
78
|
-
clearTimeout(timer);
|
|
79
|
-
}
|
|
80
|
-
this.timers.clear();
|
|
81
|
-
this.cache.clear();
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* 检查缓存是否存在且未过期
|
|
86
|
-
* @param {string} key - 缓存键
|
|
87
|
-
* @returns {boolean} 是否存在有效缓存
|
|
88
|
-
*/
|
|
89
|
-
has(key) {
|
|
90
|
-
return this.get(key) !== null;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* 获取或设置缓存
|
|
95
|
-
* @param {string} key - 缓存键
|
|
96
|
-
* @param {Function} factory - 值工厂函数
|
|
97
|
-
* @param {number} ttl - 过期时间(毫秒)
|
|
98
|
-
* @returns {*} 缓存值
|
|
99
|
-
*/
|
|
100
|
-
async getOrSet(key, factory, ttl = this.defaultTTL) {
|
|
101
|
-
const cached = this.get(key);
|
|
102
|
-
if (cached !== null) {
|
|
103
|
-
return cached;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
const value = await factory();
|
|
107
|
-
this.set(key, value, ttl);
|
|
108
|
-
return value;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* 清理过期缓存
|
|
113
|
-
*/
|
|
114
|
-
cleanup() {
|
|
115
|
-
const now = Date.now();
|
|
116
|
-
for (const [key, item] of this.cache.entries()) {
|
|
117
|
-
if (now > item.expiresAt) {
|
|
118
|
-
this.delete(key);
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
/**
|
|
124
|
-
* 获取缓存统计信息
|
|
125
|
-
* @returns {Object} 统计信息
|
|
126
|
-
*/
|
|
127
|
-
getStats() {
|
|
128
|
-
return {
|
|
129
|
-
size: this.cache.size,
|
|
130
|
-
timerCount: this.timers.size
|
|
131
|
-
};
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
// 创建单例实例
|
|
136
|
-
let cacheManagerInstance = null;
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* 获取缓存管理器实例
|
|
140
|
-
* @param {number} defaultTTL - 默认过期时间
|
|
141
|
-
* @returns {CacheManager} 缓存管理器实例
|
|
142
|
-
*/
|
|
143
|
-
function getCacheManager(defaultTTL = null) {
|
|
144
|
-
if (defaultTTL !== null || !cacheManagerInstance) {
|
|
145
|
-
cacheManagerInstance = new CacheManager(defaultTTL);
|
|
146
|
-
}
|
|
147
|
-
return cacheManagerInstance;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
// 测试用:重置单例
|
|
151
|
-
function _resetCacheManager() {
|
|
152
|
-
if (cacheManagerInstance) {
|
|
153
|
-
cacheManagerInstance.clear();
|
|
154
|
-
}
|
|
155
|
-
cacheManagerInstance = null;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
module.exports = {
|
|
159
|
-
CacheManager,
|
|
160
|
-
getCacheManager,
|
|
161
|
-
_resetCacheManager
|
|
162
|
-
};
|
package/libs/utils/config.js
DELETED
|
@@ -1,326 +0,0 @@
|
|
|
1
|
-
const path = require('node:path');
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* 配置常量定义
|
|
5
|
-
*/
|
|
6
|
-
const CONFIG_CONSTANTS = {
|
|
7
|
-
// 日志相关
|
|
8
|
-
LOGS_MAX_SIZE: 100,
|
|
9
|
-
LOGS_RETENTION_DAYS: 30,
|
|
10
|
-
|
|
11
|
-
// 轮询相关
|
|
12
|
-
POLL_MAX_TIMES: 20,
|
|
13
|
-
POLL_INTERVAL_MS: 10000,
|
|
14
|
-
POLL_MIN_INTERVAL_MS: 10,
|
|
15
|
-
POLL_MAX_INTERVAL_MS: 60000,
|
|
16
|
-
|
|
17
|
-
// 任务超时相关
|
|
18
|
-
TASK_TIMEOUT_DEFAULT: 30 * 60 * 1000, // 30分钟
|
|
19
|
-
TASK_TIMEOUT_MIN: 0, // 0表示不超时
|
|
20
|
-
TASK_TIMEOUT_MAX: 24 * 60 * 60 * 1000, // 24小时
|
|
21
|
-
|
|
22
|
-
// 重试相关
|
|
23
|
-
RETRY_BASE_DELAY: 5000, // 5秒
|
|
24
|
-
RETRY_MAX_DELAY: 300000, // 5分钟
|
|
25
|
-
RETRY_MAX_COUNT: 10,
|
|
26
|
-
|
|
27
|
-
// 并发相关
|
|
28
|
-
CONCURRENT_TASKS_DEFAULT: 10,
|
|
29
|
-
CONCURRENT_TASKS_MIN: 1,
|
|
30
|
-
CONCURRENT_TASKS_MAX: 100,
|
|
31
|
-
|
|
32
|
-
// 优先级相关
|
|
33
|
-
PRIORITY_MIN: 0,
|
|
34
|
-
PRIORITY_MAX: 100,
|
|
35
|
-
PRIORITY_DEFAULT: 0,
|
|
36
|
-
|
|
37
|
-
// 延迟相关
|
|
38
|
-
DELAY_MIN: 0,
|
|
39
|
-
DELAY_MAX: 86400, // 24小时
|
|
40
|
-
|
|
41
|
-
// 文件相关
|
|
42
|
-
SCRIPT_EXTENSION: '.js',
|
|
43
|
-
SCRIPT_NAME_DEFAULT: 'index',
|
|
44
|
-
|
|
45
|
-
// 签名相关
|
|
46
|
-
SIGNATURE_ALGORITHM: 'sha256',
|
|
47
|
-
SIGNATURE_MIN_LENGTH: 32,
|
|
48
|
-
|
|
49
|
-
// 状态相关
|
|
50
|
-
TASK_STATUSES: {
|
|
51
|
-
PENDING: 'pending',
|
|
52
|
-
RUNNING: 'running',
|
|
53
|
-
WAITING: 'waiting',
|
|
54
|
-
SUCCESS: 'success',
|
|
55
|
-
FAILED: 'failed',
|
|
56
|
-
CANCELED: 'canceled'
|
|
57
|
-
},
|
|
58
|
-
|
|
59
|
-
// 执行者类型
|
|
60
|
-
RUNNER_TYPES: {
|
|
61
|
-
SYSTEM: 'system',
|
|
62
|
-
MANUAL: 'manual'
|
|
63
|
-
},
|
|
64
|
-
|
|
65
|
-
// 时间范围
|
|
66
|
-
TIME_RANGES: {
|
|
67
|
-
'7d': { value: 7, unit: 'day', label: '近7天' },
|
|
68
|
-
'1m': { value: 1, unit: 'month', label: '近1个月' },
|
|
69
|
-
'3m': { value: 3, unit: 'month', label: '近3个月' },
|
|
70
|
-
'1y': { value: 1, unit: 'year', label: '近1年' }
|
|
71
|
-
},
|
|
72
|
-
|
|
73
|
-
// 统计相关
|
|
74
|
-
STATISTICS_ATTRIBUTES: ['total', 'success', 'failed', 'canceled', 'waitingTime', 'executionTime', 'totalTime'],
|
|
75
|
-
STATISTICS_PERIODS: ['h', 'd'],
|
|
76
|
-
|
|
77
|
-
// 数据库相关
|
|
78
|
-
DB_TABLE_PREFIX_DEFAULT: 't_',
|
|
79
|
-
DB_INDEXES: ['created_at', 'status', 'type', 'runner_type', ['type', 'status'], ['runner_type', 'status'], ['target_id', 'target_type', 'type'], ['parent_task_id'], ['priority']]
|
|
80
|
-
};
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* 默认配置
|
|
84
|
-
*/
|
|
85
|
-
const DEFAULT_CONFIG = {
|
|
86
|
-
// 数据库配置
|
|
87
|
-
dbTableNamePrefix: CONFIG_CONSTANTS.DB_TABLE_PREFIX_DEFAULT,
|
|
88
|
-
|
|
89
|
-
// API配置
|
|
90
|
-
prefix: '/api/task',
|
|
91
|
-
name: 'task',
|
|
92
|
-
|
|
93
|
-
// 并发配置
|
|
94
|
-
limit: CONFIG_CONSTANTS.CONCURRENT_TASKS_DEFAULT,
|
|
95
|
-
|
|
96
|
-
// 目录配置
|
|
97
|
-
dir: path.resolve(process.cwd(), 'libs', 'tasks'),
|
|
98
|
-
dirs: null,
|
|
99
|
-
|
|
100
|
-
// 定时任务配置
|
|
101
|
-
cronTime: '*/10 * * * *',
|
|
102
|
-
|
|
103
|
-
// 脚本配置
|
|
104
|
-
scriptName: CONFIG_CONSTANTS.SCRIPT_NAME_DEFAULT,
|
|
105
|
-
|
|
106
|
-
// 轮询配置
|
|
107
|
-
maxPollTimes: CONFIG_CONSTANTS.POLL_MAX_TIMES,
|
|
108
|
-
pollInterval: CONFIG_CONSTANTS.POLL_INTERVAL_MS,
|
|
109
|
-
|
|
110
|
-
// 超时配置
|
|
111
|
-
taskTimeout: CONFIG_CONSTANTS.TASK_TIMEOUT_DEFAULT,
|
|
112
|
-
|
|
113
|
-
// 重试配置
|
|
114
|
-
retryBaseDelay: CONFIG_CONSTANTS.RETRY_BASE_DELAY,
|
|
115
|
-
|
|
116
|
-
// 用户模型获取
|
|
117
|
-
getUserModel: () => {
|
|
118
|
-
throw new Error('getUserModel 必须在配置中提供');
|
|
119
|
-
},
|
|
120
|
-
|
|
121
|
-
// 认证获取
|
|
122
|
-
getAuthenticate: () => {
|
|
123
|
-
throw new Error('getAuthenticate 必须在配置中提供');
|
|
124
|
-
},
|
|
125
|
-
|
|
126
|
-
// 任务处理器
|
|
127
|
-
task: {},
|
|
128
|
-
|
|
129
|
-
// 任务错误统一处理(可选)
|
|
130
|
-
// 当任务执行失败时调用,接收参数: { task, error, type }
|
|
131
|
-
// - task: 任务对象
|
|
132
|
-
// - error: 错误信息
|
|
133
|
-
// - type: 错误类型(execution/timeout/callback/retry_exhausted)
|
|
134
|
-
errorHandler: null,
|
|
135
|
-
|
|
136
|
-
// 统计配置
|
|
137
|
-
statistics: {
|
|
138
|
-
enabled: true,
|
|
139
|
-
retentionDays: CONFIG_CONSTANTS.LOGS_RETENTION_DAYS
|
|
140
|
-
},
|
|
141
|
-
|
|
142
|
-
// 安全配置
|
|
143
|
-
security: {
|
|
144
|
-
enableSignature: true,
|
|
145
|
-
enablePathValidation: true,
|
|
146
|
-
enableInputValidation: true,
|
|
147
|
-
maxTaskSize: 1024 * 1024 // 1MB
|
|
148
|
-
}
|
|
149
|
-
};
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* 配置管理器
|
|
153
|
-
*/
|
|
154
|
-
class ConfigManager {
|
|
155
|
-
constructor(userConfig = {}) {
|
|
156
|
-
this.config = this.mergeConfig(DEFAULT_CONFIG, userConfig);
|
|
157
|
-
this.validateConfig();
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* 合并配置
|
|
162
|
-
* @param {Object} defaults - 默认配置
|
|
163
|
-
* @param {Object} userConfig - 用户配置
|
|
164
|
-
* @returns {Object} 合并后的配置
|
|
165
|
-
*/
|
|
166
|
-
mergeConfig(defaults, userConfig) {
|
|
167
|
-
// 深拷贝默认配置的嵌套对象,避免修改 DEFAULT_CONFIG
|
|
168
|
-
const merged = {};
|
|
169
|
-
Object.keys(defaults).forEach(key => {
|
|
170
|
-
const val = defaults[key];
|
|
171
|
-
if (typeof val === 'object' && !Array.isArray(val) && val !== null) {
|
|
172
|
-
merged[key] = { ...val };
|
|
173
|
-
} else if (Array.isArray(val)) {
|
|
174
|
-
merged[key] = [...val];
|
|
175
|
-
} else {
|
|
176
|
-
merged[key] = val;
|
|
177
|
-
}
|
|
178
|
-
});
|
|
179
|
-
|
|
180
|
-
// 处理 dirs 配置的向后兼容
|
|
181
|
-
if (!userConfig.dirs) {
|
|
182
|
-
merged.dirs = [merged.dir];
|
|
183
|
-
} else if (!userConfig.dirs.includes(merged.dir)) {
|
|
184
|
-
merged.dirs = [merged.dir, ...userConfig.dirs];
|
|
185
|
-
} else {
|
|
186
|
-
merged.dirs = [...userConfig.dirs];
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
// 合并其他配置
|
|
190
|
-
Object.keys(userConfig).forEach(key => {
|
|
191
|
-
if (key !== 'dirs') {
|
|
192
|
-
if (typeof userConfig[key] === 'object' && !Array.isArray(userConfig[key]) && userConfig[key] !== null) {
|
|
193
|
-
merged[key] = { ...defaults[key], ...userConfig[key] };
|
|
194
|
-
} else {
|
|
195
|
-
merged[key] = userConfig[key];
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
});
|
|
199
|
-
|
|
200
|
-
return merged;
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
/**
|
|
204
|
-
* 验证配置
|
|
205
|
-
* @throws {Error} 如果配置无效
|
|
206
|
-
*/
|
|
207
|
-
validateConfig() {
|
|
208
|
-
// 验证必需的配置项
|
|
209
|
-
if (!this.config.name || typeof this.config.name !== 'string') {
|
|
210
|
-
throw new Error('配置项 name 必须为非空字符串');
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
// 验证数值范围
|
|
214
|
-
if (this.config.limit < CONFIG_CONSTANTS.CONCURRENT_TASKS_MIN || this.config.limit > CONFIG_CONSTANTS.CONCURRENT_TASKS_MAX) {
|
|
215
|
-
throw new Error(`配置项 limit 必须在 ${CONFIG_CONSTANTS.CONCURRENT_TASKS_MIN} 到 ${CONFIG_CONSTANTS.CONCURRENT_TASKS_MAX} 之间`);
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
if (this.config.taskTimeout < CONFIG_CONSTANTS.TASK_TIMEOUT_MIN || this.config.taskTimeout > CONFIG_CONSTANTS.TASK_TIMEOUT_MAX) {
|
|
219
|
-
throw new Error(`配置项 taskTimeout 必须在 ${CONFIG_CONSTANTS.TASK_TIMEOUT_MIN} 到 ${CONFIG_CONSTANTS.TASK_TIMEOUT_MAX} 之间`);
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
// 验证目录配置
|
|
223
|
-
if (!Array.isArray(this.config.dirs) || this.config.dirs.length === 0) {
|
|
224
|
-
throw new Error('配置项 dirs 必须为非空数组');
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
// 验证函数类型
|
|
228
|
-
if (typeof this.config.getUserModel !== 'function') {
|
|
229
|
-
throw new Error('配置项 getUserModel 必须为函数');
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
if (typeof this.config.getAuthenticate !== 'function') {
|
|
233
|
-
throw new Error('配置项 getAuthenticate 必须为函数');
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
// 验证 errorHandler(可选,如果提供则必须为函数)
|
|
237
|
-
if (this.config.errorHandler !== null && typeof this.config.errorHandler !== 'function') {
|
|
238
|
-
throw new Error('配置项 errorHandler 必须为函数或 null');
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
/**
|
|
243
|
-
* 获取配置值
|
|
244
|
-
* @param {string} key - 配置键
|
|
245
|
-
* @param {*} defaultValue - 默认值
|
|
246
|
-
* @returns {*} 配置值
|
|
247
|
-
*/
|
|
248
|
-
get(key, defaultValue = undefined) {
|
|
249
|
-
const keys = key.split('.');
|
|
250
|
-
let value = this.config;
|
|
251
|
-
|
|
252
|
-
for (const k of keys) {
|
|
253
|
-
if (value && typeof value === 'object' && k in value) {
|
|
254
|
-
value = value[k];
|
|
255
|
-
} else {
|
|
256
|
-
return defaultValue;
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
return value;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
/**
|
|
264
|
-
* 设置配置值
|
|
265
|
-
* @param {string} key - 配置键
|
|
266
|
-
* @param {*} value - 配置值
|
|
267
|
-
*/
|
|
268
|
-
set(key, value) {
|
|
269
|
-
const keys = key.split('.');
|
|
270
|
-
let target = this.config;
|
|
271
|
-
|
|
272
|
-
for (let i = 0; i < keys.length - 1; i++) {
|
|
273
|
-
const k = keys[i];
|
|
274
|
-
if (!(k in target) || typeof target[k] !== 'object') {
|
|
275
|
-
target[k] = {};
|
|
276
|
-
}
|
|
277
|
-
target = target[k];
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
target[keys[keys.length - 1]] = value;
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
/**
|
|
284
|
-
* 获取完整配置
|
|
285
|
-
* @returns {Object} 完整配置对象
|
|
286
|
-
*/
|
|
287
|
-
getAll() {
|
|
288
|
-
return { ...this.config };
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
/**
|
|
292
|
-
* 获取常量
|
|
293
|
-
* @returns {Object} 常量对象
|
|
294
|
-
*/
|
|
295
|
-
getConstants() {
|
|
296
|
-
return { ...CONFIG_CONSTANTS };
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
// 创建单例实例
|
|
301
|
-
let configManagerInstance = null;
|
|
302
|
-
|
|
303
|
-
/**
|
|
304
|
-
* 获取配置管理器实例
|
|
305
|
-
* @param {Object} userConfig - 用户配置
|
|
306
|
-
* @returns {ConfigManager} 配置管理器实例
|
|
307
|
-
*/
|
|
308
|
-
function getConfigManager(userConfig = null) {
|
|
309
|
-
if (userConfig) {
|
|
310
|
-
configManagerInstance = new ConfigManager(userConfig);
|
|
311
|
-
}
|
|
312
|
-
return configManagerInstance;
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
// 测试用:重置单例
|
|
316
|
-
function _resetConfigManager() {
|
|
317
|
-
configManagerInstance = null;
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
module.exports = {
|
|
321
|
-
CONFIG_CONSTANTS,
|
|
322
|
-
DEFAULT_CONFIG,
|
|
323
|
-
ConfigManager,
|
|
324
|
-
getConfigManager,
|
|
325
|
-
_resetConfigManager
|
|
326
|
-
};
|
package/libs/utils/errors.js
DELETED
|
@@ -1,191 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 自定义错误类体系
|
|
3
|
-
* 提供结构化的错误处理机制
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
// 基础任务错误类
|
|
7
|
-
class TaskError extends Error {
|
|
8
|
-
constructor(code, message, details = {}) {
|
|
9
|
-
super(message);
|
|
10
|
-
this.name = 'TaskError';
|
|
11
|
-
this.code = code;
|
|
12
|
-
this.details = details;
|
|
13
|
-
this.timestamp = new Date().toISOString();
|
|
14
|
-
Error.captureStackTrace(this, this.constructor);
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
toJSON() {
|
|
18
|
-
return {
|
|
19
|
-
name: this.name,
|
|
20
|
-
code: this.code,
|
|
21
|
-
message: this.message,
|
|
22
|
-
details: this.details,
|
|
23
|
-
timestamp: this.timestamp
|
|
24
|
-
};
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// 任务不存在错误
|
|
29
|
-
class TaskNotFoundError extends TaskError {
|
|
30
|
-
constructor(taskId, details = {}) {
|
|
31
|
-
super('TASK_NOT_FOUND', `任务不存在: ${taskId}`, { taskId, ...details });
|
|
32
|
-
this.name = 'TaskNotFoundError';
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
// 任务状态错误
|
|
37
|
-
class TaskStatusError extends TaskError {
|
|
38
|
-
constructor(taskId, currentStatus, expectedStatus, details = {}) {
|
|
39
|
-
super(
|
|
40
|
-
'TASK_STATUS_ERROR',
|
|
41
|
-
`任务状态不允许此操作: 当前状态 ${currentStatus}, 期望状态 ${expectedStatus}`,
|
|
42
|
-
{ taskId, currentStatus, expectedStatus, ...details }
|
|
43
|
-
);
|
|
44
|
-
this.name = 'TaskStatusError';
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
// 任务超时错误
|
|
49
|
-
class TaskTimeoutError extends TaskError {
|
|
50
|
-
constructor(taskId, timeout, details = {}) {
|
|
51
|
-
super('TASK_TIMEOUT', `任务执行超时: ${timeout}ms`, { taskId, timeout, ...details });
|
|
52
|
-
this.name = 'TaskTimeoutError';
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// 任务验证错误
|
|
57
|
-
class TaskValidationError extends TaskError {
|
|
58
|
-
constructor(field, value, reason, details = {}) {
|
|
59
|
-
super(
|
|
60
|
-
'TASK_VALIDATION_ERROR',
|
|
61
|
-
`任务参数验证失败: ${field} = ${value}, 原因: ${reason}`,
|
|
62
|
-
{ field, value, reason, ...details }
|
|
63
|
-
);
|
|
64
|
-
this.name = 'TaskValidationError';
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
// 任务执行错误
|
|
69
|
-
class TaskExecutionError extends TaskError {
|
|
70
|
-
constructor(taskId, originalError, details = {}) {
|
|
71
|
-
super(
|
|
72
|
-
'TASK_EXECUTION_ERROR',
|
|
73
|
-
`任务执行失败: ${originalError.message}`,
|
|
74
|
-
{ taskId, originalError: originalError.message, ...details }
|
|
75
|
-
);
|
|
76
|
-
this.name = 'TaskExecutionError';
|
|
77
|
-
this.originalError = originalError;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// 安全错误
|
|
82
|
-
class SecurityError extends TaskError {
|
|
83
|
-
constructor(reason, details = {}) {
|
|
84
|
-
super('SECURITY_ERROR', `安全检查失败: ${reason}`, { reason, ...details });
|
|
85
|
-
this.name = 'SecurityError';
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// 配置错误
|
|
90
|
-
class ConfigurationError extends TaskError {
|
|
91
|
-
constructor(configKey, reason, details = {}) {
|
|
92
|
-
super('CONFIGURATION_ERROR', `配置错误: ${configKey} - ${reason}`, { configKey, reason, ...details });
|
|
93
|
-
this.name = 'ConfigurationError';
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// 数据库错误
|
|
98
|
-
class DatabaseError extends TaskError {
|
|
99
|
-
constructor(operation, originalError, details = {}) {
|
|
100
|
-
super(
|
|
101
|
-
'DATABASE_ERROR',
|
|
102
|
-
`数据库操作失败: ${operation}`,
|
|
103
|
-
{ operation, originalError: originalError.message, ...details }
|
|
104
|
-
);
|
|
105
|
-
this.name = 'DatabaseError';
|
|
106
|
-
this.originalError = originalError;
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
// 错误处理工具函数
|
|
111
|
-
class ErrorHandler {
|
|
112
|
-
/**
|
|
113
|
-
* 处理错误并返回适当的响应
|
|
114
|
-
* @param {Error} error - 错误对象
|
|
115
|
-
* @param {Object} logger - 日志记录器
|
|
116
|
-
* @returns {Object} 错误响应
|
|
117
|
-
*/
|
|
118
|
-
static handle(error, logger) {
|
|
119
|
-
if (error instanceof TaskError) {
|
|
120
|
-
// 自定义任务错误
|
|
121
|
-
logger.warn(`任务错误 [${error.code}]: ${error.message}`, error.details);
|
|
122
|
-
return {
|
|
123
|
-
success: false,
|
|
124
|
-
error: {
|
|
125
|
-
code: error.code,
|
|
126
|
-
message: error.message,
|
|
127
|
-
details: error.details
|
|
128
|
-
}
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
// 未知错误
|
|
133
|
-
logger.error('未知错误:', error);
|
|
134
|
-
return {
|
|
135
|
-
success: false,
|
|
136
|
-
error: {
|
|
137
|
-
code: 'UNKNOWN_ERROR',
|
|
138
|
-
message: '服务器内部错误',
|
|
139
|
-
details: process.env.NODE_ENV === 'development' ? { message: error.message } : {}
|
|
140
|
-
}
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
/**
|
|
145
|
-
* 异步包装器,自动处理错误
|
|
146
|
-
* @param {Function} fn - 异步函数
|
|
147
|
-
* @param {Object} logger - 日志记录器
|
|
148
|
-
* @returns {Function} 包装后的函数
|
|
149
|
-
*/
|
|
150
|
-
static asyncWrapper(fn, logger) {
|
|
151
|
-
return async (...args) => {
|
|
152
|
-
try {
|
|
153
|
-
return await fn(...args);
|
|
154
|
-
} catch (error) {
|
|
155
|
-
throw this.handle(error, logger);
|
|
156
|
-
}
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* 将错误转换为任务错误
|
|
162
|
-
* @param {Error} error - 原始错误
|
|
163
|
-
* @param {string} defaultCode - 默认错误代码
|
|
164
|
-
* @param {string} defaultMessage - 默认错误消息
|
|
165
|
-
* @returns {TaskError} 任务错误对象
|
|
166
|
-
*/
|
|
167
|
-
static toTaskError(error, defaultCode = 'UNKNOWN_ERROR', defaultMessage = '未知错误') {
|
|
168
|
-
if (error instanceof TaskError) {
|
|
169
|
-
return error;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
return new TaskError(
|
|
173
|
-
defaultCode,
|
|
174
|
-
defaultMessage,
|
|
175
|
-
{ originalError: error.message, stack: error.stack }
|
|
176
|
-
);
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
module.exports = {
|
|
181
|
-
TaskError,
|
|
182
|
-
TaskNotFoundError,
|
|
183
|
-
TaskStatusError,
|
|
184
|
-
TaskTimeoutError,
|
|
185
|
-
TaskValidationError,
|
|
186
|
-
TaskExecutionError,
|
|
187
|
-
SecurityError,
|
|
188
|
-
ConfigurationError,
|
|
189
|
-
DatabaseError,
|
|
190
|
-
ErrorHandler
|
|
191
|
-
};
|