@taicode/common-server 1.0.12 → 1.0.13
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/output/index.d.ts +1 -0
- package/output/index.d.ts.map +1 -1
- package/output/index.js +1 -0
- package/output/redis-queue/index.d.ts +1 -0
- package/output/redis-queue/index.d.ts.map +1 -1
- package/output/redis-queue/redis-batch-consumer.d.ts +4 -9
- package/output/redis-queue/redis-batch-consumer.d.ts.map +1 -1
- package/output/redis-queue/redis-batch-consumer.js +3 -55
- package/output/redis-queue/redis-batch-consumer.test.d.ts +5 -0
- package/output/redis-queue/redis-batch-consumer.test.d.ts.map +1 -1
- package/output/redis-queue/redis-queue-common.d.ts +15 -3
- package/output/redis-queue/redis-queue-common.d.ts.map +1 -1
- package/output/redis-queue/redis-queue-common.js +80 -0
- package/output/redis-queue/redis-queue-common.test.d.ts +17 -0
- package/output/redis-queue/redis-queue-common.test.d.ts.map +1 -1
- package/output/redis-queue/redis-queue-common.test.js +11 -11
- package/output/redis-queue/redis-queue-consumer.d.ts +6 -27
- package/output/redis-queue/redis-queue-consumer.d.ts.map +1 -1
- package/output/redis-queue/redis-queue-consumer.js +23 -187
- package/output/redis-queue/redis-queue-consumer.test.d.ts +5 -0
- package/output/redis-queue/redis-queue-consumer.test.d.ts.map +1 -1
- package/output/redis-queue/redis-queue-provider.d.ts +14 -15
- package/output/redis-queue/redis-queue-provider.d.ts.map +1 -1
- package/output/redis-queue/redis-queue-provider.js +8 -9
- package/output/redis-queue/redis-queue-provider.test.d.ts +5 -0
- package/output/redis-queue/redis-queue-provider.test.d.ts.map +1 -1
- package/output/redis-queue/types.d.ts +47 -9
- package/output/redis-queue/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/output/logger/logger.d.ts +0 -33
- package/output/logger/logger.d.ts.map +0 -1
- package/output/logger/logger.js +0 -65
- package/output/logger/logger.test.d.ts +0 -2
- package/output/logger/logger.test.d.ts.map +0 -1
- package/output/logger/logger.test.js +0 -87
- package/output/redis-queue/batch-consumer.d.ts +0 -107
- package/output/redis-queue/batch-consumer.d.ts.map +0 -1
- package/output/redis-queue/batch-consumer.js +0 -492
- package/output/redis-queue/batch-consumer.test.d.ts +0 -2
- package/output/redis-queue/batch-consumer.test.d.ts.map +0 -1
- package/output/redis-queue/batch-consumer.test.js +0 -216
- package/output/redis-queue/batch-redis-queue.d.ts +0 -136
- package/output/redis-queue/batch-redis-queue.d.ts.map +0 -1
- package/output/redis-queue/batch-redis-queue.js +0 -583
- package/output/redis-queue/batch-redis-queue.test.d.ts +0 -2
- package/output/redis-queue/batch-redis-queue.test.d.ts.map +0 -1
- package/output/redis-queue/batch-redis-queue.test.js +0 -243
- package/output/redis-queue/redis-queue.d.ts +0 -129
- package/output/redis-queue/redis-queue.d.ts.map +0 -1
- package/output/redis-queue/redis-queue.js +0 -557
- package/output/redis-queue/redis-queue.test.d.ts +0 -2
- package/output/redis-queue/redis-queue.test.d.ts.map +0 -1
- package/output/redis-queue/redis-queue.test.js +0 -234
- package/output/redis-queue/registry.d.ts +0 -57
- package/output/redis-queue/registry.d.ts.map +0 -1
- package/output/redis-queue/registry.js +0 -30
|
@@ -1,557 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { createClient } from 'redis';
|
|
3
|
-
import { catchIt } from '@taicode/common-base';
|
|
4
|
-
/**
|
|
5
|
-
* 通用任务队列类(泛型)
|
|
6
|
-
*
|
|
7
|
-
* 提供基于 Redis 的任务队列功能,支持:
|
|
8
|
-
* - 任务入队和持久化
|
|
9
|
-
* - 自动重试机制
|
|
10
|
-
* - 任务状态追踪
|
|
11
|
-
* - 分布式消费
|
|
12
|
-
*
|
|
13
|
-
* @template T 任务数据类型
|
|
14
|
-
*
|
|
15
|
-
* @example
|
|
16
|
-
* ```ts
|
|
17
|
-
* interface EmailTask {
|
|
18
|
-
* to: string
|
|
19
|
-
* subject: string
|
|
20
|
-
* }
|
|
21
|
-
*
|
|
22
|
-
* const queue = new RedisQueue<EmailTask>({
|
|
23
|
-
* redisUrl: 'redis://localhost:6379',
|
|
24
|
-
* queueKey: 'email-queue',
|
|
25
|
-
* concurrency: 5,
|
|
26
|
-
* handler: async (data) => {
|
|
27
|
-
* await sendEmail(data.to, data.subject)
|
|
28
|
-
* return catchIt(() => {})
|
|
29
|
-
* }
|
|
30
|
-
* })
|
|
31
|
-
*
|
|
32
|
-
* // 连接 Redis(自动启动消费者)
|
|
33
|
-
* await queue.connect()
|
|
34
|
-
*
|
|
35
|
-
* // 入队任务(自动开始处理)
|
|
36
|
-
* await queue.enqueue({ to: 'user@example.com', subject: 'Hello' })
|
|
37
|
-
*
|
|
38
|
-
* // 获取队列统计信息(O(1) 时间复杂度)
|
|
39
|
-
* const stats = await queue.statistics()
|
|
40
|
-
* console.log(stats) // { pending: 5, processing: 2, completed: 2, failed: 1 }
|
|
41
|
-
* ```
|
|
42
|
-
*/
|
|
43
|
-
export class RedisQueue {
|
|
44
|
-
consumerRunning = false;
|
|
45
|
-
redis = null;
|
|
46
|
-
consumerInterval = null;
|
|
47
|
-
recoveryInterval = null;
|
|
48
|
-
processingTasks = 0; // 当前正在处理的任务数
|
|
49
|
-
config;
|
|
50
|
-
handler;
|
|
51
|
-
// 不同状态队列的键名
|
|
52
|
-
failedQueue;
|
|
53
|
-
pendingQueue;
|
|
54
|
-
processingQueue;
|
|
55
|
-
completedQueue;
|
|
56
|
-
constructor(config) {
|
|
57
|
-
// 验证必填参数
|
|
58
|
-
if (!config.redisUrl && !config.redisClient) {
|
|
59
|
-
throw new Error('[TaskQueue] Either redisUrl or redisClient is required');
|
|
60
|
-
}
|
|
61
|
-
if (config.redisUrl && config.redisClient) {
|
|
62
|
-
throw new Error('[TaskQueue] Cannot specify both redisUrl and redisClient');
|
|
63
|
-
}
|
|
64
|
-
if (!config.queueKey) {
|
|
65
|
-
throw new Error('[TaskQueue] queueKey is required');
|
|
66
|
-
}
|
|
67
|
-
if (config.queueKey.length < 6) {
|
|
68
|
-
throw new Error('[TaskQueue] queueKey must be at least 6 characters long');
|
|
69
|
-
}
|
|
70
|
-
if (!config.handler) {
|
|
71
|
-
throw new Error('[TaskQueue] handler is required');
|
|
72
|
-
}
|
|
73
|
-
this.handler = config.handler;
|
|
74
|
-
this.config = {
|
|
75
|
-
queueKey: config.queueKey,
|
|
76
|
-
redisUrl: config.redisUrl,
|
|
77
|
-
redisClient: config.redisClient,
|
|
78
|
-
cleanupDelay: config.cleanupDelay || 86400, // 24 hours
|
|
79
|
-
maxRetries: config.maxRetries || 3,
|
|
80
|
-
concurrency: config.concurrency || 1,
|
|
81
|
-
consumerInterval: config.consumerInterval || 1000,
|
|
82
|
-
processingDelay: config.processingDelay || 0, // 默认立即执行
|
|
83
|
-
processingTimeout: config.processingTimeout || 60000, // 60 seconds
|
|
84
|
-
};
|
|
85
|
-
// 初始化不同状态队列的键名
|
|
86
|
-
this.failedQueue = `${config.queueKey}:failed`;
|
|
87
|
-
this.pendingQueue = `${config.queueKey}:pending`;
|
|
88
|
-
this.completedQueue = `${config.queueKey}:completed`;
|
|
89
|
-
this.processingQueue = `${config.queueKey}:processing`;
|
|
90
|
-
// 使用外部客户端或创建新客户端
|
|
91
|
-
if (config.redisClient) {
|
|
92
|
-
this.redis = config.redisClient;
|
|
93
|
-
}
|
|
94
|
-
else {
|
|
95
|
-
this.redis = createClient({ url: this.config.redisUrl });
|
|
96
|
-
// 添加错误处理
|
|
97
|
-
this.redis.on('error', (err) => {
|
|
98
|
-
console.error('[TaskQueue] Redis Client Error:', err);
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
/**
|
|
103
|
-
* 连接 Redis 并自动启动消费者
|
|
104
|
-
*/
|
|
105
|
-
async connect() {
|
|
106
|
-
if (this.redis && !this.redis.isOpen) {
|
|
107
|
-
await this.redis.connect().catch((error) => {
|
|
108
|
-
console.error('[TaskQueue] Failed to connect to Redis:', error);
|
|
109
|
-
throw error;
|
|
110
|
-
});
|
|
111
|
-
// 连接成功后启动消费者和恢复机制
|
|
112
|
-
this.startConsumer();
|
|
113
|
-
this.startRecovery();
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
/**
|
|
117
|
-
* 断开 Redis 连接并停止消费者
|
|
118
|
-
*/
|
|
119
|
-
disconnect() {
|
|
120
|
-
this.stopConsumer();
|
|
121
|
-
this.stopRecovery();
|
|
122
|
-
if (this.redis && this.redis.isOpen) {
|
|
123
|
-
this.redis.disconnect().catch((error) => {
|
|
124
|
-
console.error('[TaskQueue] Failed to disconnect:', error);
|
|
125
|
-
});
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
async enqueue(data) {
|
|
129
|
-
if (!this.redis) {
|
|
130
|
-
console.warn('[TaskQueue] Redis not available, skipping task enqueue');
|
|
131
|
-
return Array.isArray(data) ? [] : '';
|
|
132
|
-
}
|
|
133
|
-
// 统一处理为数组
|
|
134
|
-
const dataList = Array.isArray(data) ? data : [data];
|
|
135
|
-
const taskIds = [];
|
|
136
|
-
// 使用 Lua 脚本确保幂等入队的原子性
|
|
137
|
-
const enqueueScript = `
|
|
138
|
-
local taskKey = KEYS[1]
|
|
139
|
-
local pendingQueue = KEYS[2]
|
|
140
|
-
local taskData = ARGV[1]
|
|
141
|
-
local ttl = tonumber(ARGV[2])
|
|
142
|
-
local taskId = ARGV[3]
|
|
143
|
-
|
|
144
|
-
-- 检查任务是否已存在
|
|
145
|
-
local exists = redis.call('EXISTS', taskKey)
|
|
146
|
-
if exists == 1 then
|
|
147
|
-
return 0 -- 任务已存在,跳过
|
|
148
|
-
end
|
|
149
|
-
|
|
150
|
-
-- 原子化操作: 创建任务 + 推入队列
|
|
151
|
-
redis.call('SETEX', taskKey, ttl, taskData)
|
|
152
|
-
redis.call('RPUSH', pendingQueue, taskId)
|
|
153
|
-
return 1 -- 成功创建
|
|
154
|
-
`;
|
|
155
|
-
for (const item of dataList) {
|
|
156
|
-
// 检查 data 中是否包含自定义 id
|
|
157
|
-
const customId = item.id;
|
|
158
|
-
const taskId = customId || randomUUID();
|
|
159
|
-
const taskKey = `${this.config.queueKey}:task:${taskId}`;
|
|
160
|
-
const task = {
|
|
161
|
-
id: taskId,
|
|
162
|
-
data: item,
|
|
163
|
-
retryCount: 0,
|
|
164
|
-
maxRetries: this.config.maxRetries,
|
|
165
|
-
createdTime: new Date().toISOString(),
|
|
166
|
-
status: 'pending',
|
|
167
|
-
...(this.config.processingDelay > 0 && { delayUntil: Date.now() + this.config.processingDelay }),
|
|
168
|
-
};
|
|
169
|
-
// 使用 Lua 脚本原子化入队
|
|
170
|
-
const result = await this.redis.eval(enqueueScript, {
|
|
171
|
-
keys: [taskKey, this.pendingQueue],
|
|
172
|
-
arguments: [JSON.stringify(task), this.config.cleanupDelay.toString(), taskId],
|
|
173
|
-
});
|
|
174
|
-
if (result === 0) {
|
|
175
|
-
console.log(`[TaskQueue] Task already exists, skipping: ${taskId}`);
|
|
176
|
-
}
|
|
177
|
-
else {
|
|
178
|
-
console.log(`[TaskQueue] Enqueued task: ${task.id}`);
|
|
179
|
-
}
|
|
180
|
-
taskIds.push(taskId);
|
|
181
|
-
}
|
|
182
|
-
// 返回单个 ID 或 ID 数组
|
|
183
|
-
return Array.isArray(data) ? taskIds : taskIds[0];
|
|
184
|
-
}
|
|
185
|
-
/**
|
|
186
|
-
* 获取任务详情
|
|
187
|
-
*/
|
|
188
|
-
async getTask(taskId) {
|
|
189
|
-
if (!this.redis)
|
|
190
|
-
return null;
|
|
191
|
-
const taskKey = `${this.config.queueKey}:task:${taskId}`;
|
|
192
|
-
const taskData = await this.redis.get(taskKey);
|
|
193
|
-
if (!taskData)
|
|
194
|
-
return null;
|
|
195
|
-
return JSON.parse(taskData);
|
|
196
|
-
}
|
|
197
|
-
/**
|
|
198
|
-
* 更新任务状态并移动到对应队列(原子操作)
|
|
199
|
-
*/
|
|
200
|
-
async applyStatus(taskId, oldStatus, newStatus) {
|
|
201
|
-
if (!this.redis)
|
|
202
|
-
return;
|
|
203
|
-
const task = await this.getTask(taskId);
|
|
204
|
-
if (!task)
|
|
205
|
-
return;
|
|
206
|
-
task.status = newStatus;
|
|
207
|
-
const taskKey = `${this.config.queueKey}:task:${taskId}`;
|
|
208
|
-
const oldQueue = this.getQueueByStatus(oldStatus);
|
|
209
|
-
const newQueue = this.getQueueByStatus(newStatus);
|
|
210
|
-
if (oldQueue !== newQueue) {
|
|
211
|
-
// 使用 Lua 脚本确保原子性:更新任务 + 移动队列
|
|
212
|
-
const script = `
|
|
213
|
-
redis.call('SETEX', KEYS[1], ARGV[1], ARGV[2])
|
|
214
|
-
redis.call('LREM', KEYS[2], 0, ARGV[3])
|
|
215
|
-
redis.call('RPUSH', KEYS[3], ARGV[3])
|
|
216
|
-
return 1
|
|
217
|
-
`;
|
|
218
|
-
await this.redis.eval(script, {
|
|
219
|
-
keys: [taskKey, oldQueue, newQueue],
|
|
220
|
-
arguments: [this.config.cleanupDelay.toString(), JSON.stringify(task), taskId],
|
|
221
|
-
});
|
|
222
|
-
}
|
|
223
|
-
else {
|
|
224
|
-
// 只更新任务数据
|
|
225
|
-
await this.redis.setEx(taskKey, this.config.cleanupDelay, JSON.stringify(task));
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
/**
|
|
229
|
-
* 根据状态获取对应的队列键
|
|
230
|
-
*/
|
|
231
|
-
getQueueByStatus(status) {
|
|
232
|
-
switch (status) {
|
|
233
|
-
case 'pending': return this.pendingQueue;
|
|
234
|
-
case 'processing': return this.processingQueue;
|
|
235
|
-
case 'completed': return this.completedQueue;
|
|
236
|
-
case 'failed': return this.failedQueue;
|
|
237
|
-
default: return this.pendingQueue;
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
/**
|
|
241
|
-
* 恢复超时的任务
|
|
242
|
-
* 检查 processing 队列中的任务,将超时的任务重试或标记为失败
|
|
243
|
-
*/
|
|
244
|
-
async recoverStalledTasks() {
|
|
245
|
-
if (!this.redis)
|
|
246
|
-
return;
|
|
247
|
-
try {
|
|
248
|
-
const processingTaskIds = await this.redis.lRange(this.processingQueue, 0, -1);
|
|
249
|
-
if (processingTaskIds.length === 0) {
|
|
250
|
-
return;
|
|
251
|
-
}
|
|
252
|
-
const now = Date.now();
|
|
253
|
-
let recoveredCount = 0;
|
|
254
|
-
for (const taskId of processingTaskIds) {
|
|
255
|
-
const task = await this.getTask(taskId);
|
|
256
|
-
if (!task) {
|
|
257
|
-
// 任务不存在,从队列中移除
|
|
258
|
-
await this.redis.lRem(this.processingQueue, 0, taskId);
|
|
259
|
-
continue;
|
|
260
|
-
}
|
|
261
|
-
// 检查是否超时
|
|
262
|
-
const processingTime = now - (task.processingStartTime || now);
|
|
263
|
-
if (processingTime > this.config.processingTimeout) {
|
|
264
|
-
console.log(`[TaskQueue] Task timeout: ${taskId} (processing time: ${processingTime}ms)`);
|
|
265
|
-
const taskKey = `${this.config.queueKey}:task:${taskId}`;
|
|
266
|
-
// 检查是否还可以重试
|
|
267
|
-
if (task.retryCount < task.maxRetries) {
|
|
268
|
-
// 重试:放回 pending 队列
|
|
269
|
-
task.status = 'pending';
|
|
270
|
-
task.retryCount++;
|
|
271
|
-
task.processingStartTime = undefined;
|
|
272
|
-
// 使用 Lua 脚本确保原子性
|
|
273
|
-
const script = `
|
|
274
|
-
redis.call('SETEX', KEYS[1], ARGV[1], ARGV[2])
|
|
275
|
-
redis.call('LREM', KEYS[2], 0, ARGV[3])
|
|
276
|
-
redis.call('RPUSH', KEYS[3], ARGV[3])
|
|
277
|
-
return 1
|
|
278
|
-
`;
|
|
279
|
-
await this.redis.eval(script, {
|
|
280
|
-
keys: [taskKey, this.processingQueue, this.pendingQueue],
|
|
281
|
-
arguments: [this.config.cleanupDelay.toString(), JSON.stringify(task), taskId],
|
|
282
|
-
});
|
|
283
|
-
console.log(`[TaskQueue] Task ${taskId} will retry (${task.retryCount}/${task.maxRetries})`);
|
|
284
|
-
}
|
|
285
|
-
else {
|
|
286
|
-
// 已达到最大重试次数,标记为失败
|
|
287
|
-
task.status = 'failed';
|
|
288
|
-
task.processingStartTime = undefined;
|
|
289
|
-
// 使用 Lua 脚本确保原子性
|
|
290
|
-
const script = `
|
|
291
|
-
redis.call('SETEX', KEYS[1], ARGV[1], ARGV[2])
|
|
292
|
-
redis.call('LREM', KEYS[2], 0, ARGV[3])
|
|
293
|
-
redis.call('RPUSH', KEYS[3], ARGV[3])
|
|
294
|
-
return 1
|
|
295
|
-
`;
|
|
296
|
-
await this.redis.eval(script, {
|
|
297
|
-
keys: [taskKey, this.processingQueue, this.failedQueue],
|
|
298
|
-
arguments: [this.config.cleanupDelay.toString(), JSON.stringify(task), taskId],
|
|
299
|
-
});
|
|
300
|
-
console.error(`[TaskQueue] Task ${taskId} failed after timeout`);
|
|
301
|
-
}
|
|
302
|
-
recoveredCount++;
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
if (recoveredCount > 0) {
|
|
306
|
-
console.log(`[TaskQueue] Recovered ${recoveredCount} timeout tasks`);
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
catch (error) {
|
|
310
|
-
console.error('[TaskQueue] Failed to recover stalled tasks:', error);
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
/**
|
|
314
|
-
* 处理单个任务
|
|
315
|
-
*/
|
|
316
|
-
async processTask(taskId) {
|
|
317
|
-
this.processingTasks++;
|
|
318
|
-
try {
|
|
319
|
-
const task = await this.getTask(taskId);
|
|
320
|
-
if (!task) {
|
|
321
|
-
console.warn(`[TaskQueue] Task not found: ${taskId}`);
|
|
322
|
-
return;
|
|
323
|
-
}
|
|
324
|
-
// 任务应该是 pending 状态(Lua 脚本已确保延迟检查)
|
|
325
|
-
if (task.status !== 'pending') {
|
|
326
|
-
console.log(`[TaskQueue] Task ${taskId} has invalid status (${task.status}), marking as failed`);
|
|
327
|
-
await this.applyStatus(taskId, task.status, 'failed');
|
|
328
|
-
return;
|
|
329
|
-
}
|
|
330
|
-
try {
|
|
331
|
-
// 任务已在 processing 队列中(由 Lua 脚本完成),只需更新状态和开始时间
|
|
332
|
-
task.status = 'processing';
|
|
333
|
-
task.processingStartTime = Date.now();
|
|
334
|
-
const taskKey = `${this.config.queueKey}:task:${taskId}`;
|
|
335
|
-
await this.redis.setEx(taskKey, this.config.cleanupDelay, JSON.stringify(task));
|
|
336
|
-
// 执行任务处理器
|
|
337
|
-
await this.handler(task.data);
|
|
338
|
-
// 更新状态为完成
|
|
339
|
-
await this.applyStatus(taskId, 'processing', 'completed');
|
|
340
|
-
console.log(`[TaskQueue] Task completed: ${taskId}`);
|
|
341
|
-
}
|
|
342
|
-
catch (error) {
|
|
343
|
-
console.error(`[TaskQueue] Task failed: ${taskId}`, error);
|
|
344
|
-
// 检查是否需要重试
|
|
345
|
-
if (task.retryCount < task.maxRetries) {
|
|
346
|
-
task.retryCount++;
|
|
347
|
-
task.status = 'pending';
|
|
348
|
-
task.processingStartTime = undefined;
|
|
349
|
-
const taskKey = `${this.config.queueKey}:task:${taskId}`;
|
|
350
|
-
// 使用 Lua 脚本确保原子性
|
|
351
|
-
const script = `
|
|
352
|
-
redis.call('SETEX', KEYS[1], ARGV[1], ARGV[2])
|
|
353
|
-
redis.call('LREM', KEYS[2], 0, ARGV[3])
|
|
354
|
-
redis.call('RPUSH', KEYS[3], ARGV[3])
|
|
355
|
-
return 1
|
|
356
|
-
`;
|
|
357
|
-
await this.redis.eval(script, {
|
|
358
|
-
keys: [taskKey, this.processingQueue, this.pendingQueue],
|
|
359
|
-
arguments: [this.config.cleanupDelay.toString(), JSON.stringify(task), taskId],
|
|
360
|
-
});
|
|
361
|
-
console.log(`[TaskQueue] Task ${taskId} will retry (${task.retryCount}/${task.maxRetries})`);
|
|
362
|
-
}
|
|
363
|
-
else {
|
|
364
|
-
task.status = 'failed';
|
|
365
|
-
task.processingStartTime = undefined;
|
|
366
|
-
const taskKey = `${this.config.queueKey}:task:${taskId}`;
|
|
367
|
-
// 使用 Lua 脚本确保原子性
|
|
368
|
-
const script = `
|
|
369
|
-
redis.call('SETEX', KEYS[1], ARGV[1], ARGV[2])
|
|
370
|
-
redis.call('LREM', KEYS[2], 0, ARGV[3])
|
|
371
|
-
redis.call('RPUSH', KEYS[3], ARGV[3])
|
|
372
|
-
return 1
|
|
373
|
-
`;
|
|
374
|
-
await this.redis.eval(script, {
|
|
375
|
-
keys: [taskKey, this.processingQueue, this.failedQueue],
|
|
376
|
-
arguments: [this.config.cleanupDelay.toString(), JSON.stringify(task), taskId],
|
|
377
|
-
});
|
|
378
|
-
console.error(`[TaskQueue] Task ${taskId} failed after ${task.maxRetries} retries`);
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
finally {
|
|
383
|
-
this.processingTasks--;
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
/**
|
|
387
|
-
* 启动恢复机制(内部方法,自动调用)
|
|
388
|
-
*/
|
|
389
|
-
startRecovery() {
|
|
390
|
-
if (this.recoveryInterval || !this.redis) {
|
|
391
|
-
return;
|
|
392
|
-
}
|
|
393
|
-
// 立即执行一次恢复
|
|
394
|
-
this.recoverStalledTasks().catch(error => {
|
|
395
|
-
console.error('[TaskQueue] Initial recovery error:', error);
|
|
396
|
-
});
|
|
397
|
-
// 定期检查(每 10 秒检查一次)
|
|
398
|
-
this.recoveryInterval = setInterval(() => {
|
|
399
|
-
this.recoverStalledTasks().catch(error => {
|
|
400
|
-
console.error('[TaskQueue] Recovery error:', error);
|
|
401
|
-
});
|
|
402
|
-
}, 10000);
|
|
403
|
-
console.log('[TaskQueue] Recovery mechanism started');
|
|
404
|
-
}
|
|
405
|
-
/**
|
|
406
|
-
* 停止恢复机制(内部方法,自动调用)
|
|
407
|
-
*/
|
|
408
|
-
stopRecovery() {
|
|
409
|
-
if (this.recoveryInterval) {
|
|
410
|
-
clearInterval(this.recoveryInterval);
|
|
411
|
-
this.recoveryInterval = null;
|
|
412
|
-
console.log('[TaskQueue] Recovery mechanism stopped');
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
/**
|
|
416
|
-
* 启动消费者(内部方法,自动调用)
|
|
417
|
-
*/
|
|
418
|
-
startConsumer() {
|
|
419
|
-
if (this.consumerRunning || !this.redis) {
|
|
420
|
-
return;
|
|
421
|
-
}
|
|
422
|
-
this.consumerRunning = true;
|
|
423
|
-
console.log(`[TaskQueue] Consumer started with concurrency: ${this.config.concurrency}`);
|
|
424
|
-
// Lua 脚本: 原子化从 pending 取出任务并移到 processing(只取已到延迟时间的任务)
|
|
425
|
-
const popAndMoveScript = `
|
|
426
|
-
local pendingQueue = KEYS[1]
|
|
427
|
-
local processingQueue = KEYS[2]
|
|
428
|
-
local queueKeyPrefix = KEYS[3]
|
|
429
|
-
local count = tonumber(ARGV[1])
|
|
430
|
-
local currentTime = tonumber(ARGV[2])
|
|
431
|
-
|
|
432
|
-
local taskIds = {}
|
|
433
|
-
local checkedCount = 0
|
|
434
|
-
local maxCheck = count * 3 -- 最多检查 count*3 个任务,避免无限循环
|
|
435
|
-
|
|
436
|
-
while #taskIds < count and checkedCount < maxCheck do
|
|
437
|
-
local taskId = redis.call('LPOP', pendingQueue)
|
|
438
|
-
if not taskId then
|
|
439
|
-
break
|
|
440
|
-
end
|
|
441
|
-
|
|
442
|
-
checkedCount = checkedCount + 1
|
|
443
|
-
|
|
444
|
-
-- 获取任务详情检查延迟时间
|
|
445
|
-
local taskKey = queueKeyPrefix .. ':task:' .. taskId
|
|
446
|
-
local taskData = redis.call('GET', taskKey)
|
|
447
|
-
|
|
448
|
-
if taskData then
|
|
449
|
-
local task = cjson.decode(taskData)
|
|
450
|
-
local delayUntil = task.delayUntil
|
|
451
|
-
|
|
452
|
-
-- 如果没有延迟或已到延迟时间,则移到 processing
|
|
453
|
-
if not delayUntil or delayUntil <= currentTime then
|
|
454
|
-
redis.call('RPUSH', processingQueue, taskId)
|
|
455
|
-
table.insert(taskIds, taskId)
|
|
456
|
-
else
|
|
457
|
-
-- 未到延迟时间,放回队列尾部
|
|
458
|
-
redis.call('RPUSH', pendingQueue, taskId)
|
|
459
|
-
end
|
|
460
|
-
end
|
|
461
|
-
end
|
|
462
|
-
|
|
463
|
-
return taskIds
|
|
464
|
-
`;
|
|
465
|
-
this.consumerInterval = setInterval(async () => {
|
|
466
|
-
try {
|
|
467
|
-
// 检查当前是否有可用的并发槽位
|
|
468
|
-
const availableSlots = this.config.concurrency - this.processingTasks;
|
|
469
|
-
if (availableSlots <= 0) {
|
|
470
|
-
return; // 已达到并发限制,等待下一次轮询
|
|
471
|
-
}
|
|
472
|
-
// 使用 Lua 脚本原子化取出任务并移到 processing 队列
|
|
473
|
-
const taskIds = await this.redis.eval(popAndMoveScript, {
|
|
474
|
-
keys: [this.pendingQueue, this.processingQueue, this.config.queueKey],
|
|
475
|
-
arguments: [availableSlots.toString(), Date.now().toString()],
|
|
476
|
-
});
|
|
477
|
-
// 并发处理所有任务(不等待完成)
|
|
478
|
-
taskIds.forEach(taskId => {
|
|
479
|
-
this.processTask(taskId).catch(error => {
|
|
480
|
-
console.error(`[TaskQueue] Unhandled error in processTask: ${taskId}`, error);
|
|
481
|
-
});
|
|
482
|
-
});
|
|
483
|
-
}
|
|
484
|
-
catch (error) {
|
|
485
|
-
console.error('[TaskQueue] Consumer error:', error);
|
|
486
|
-
}
|
|
487
|
-
}, this.config.consumerInterval);
|
|
488
|
-
}
|
|
489
|
-
/**
|
|
490
|
-
* 停止消费者(内部方法,自动调用)
|
|
491
|
-
*/
|
|
492
|
-
stopConsumer() {
|
|
493
|
-
if (this.consumerInterval) {
|
|
494
|
-
clearInterval(this.consumerInterval);
|
|
495
|
-
this.consumerInterval = null;
|
|
496
|
-
}
|
|
497
|
-
this.consumerRunning = false;
|
|
498
|
-
console.log('[TaskQueue] Consumer stopped');
|
|
499
|
-
}
|
|
500
|
-
/**
|
|
501
|
-
* 获取队列统计信息
|
|
502
|
-
* 返回队列中各种状态任务的详细数量
|
|
503
|
-
*
|
|
504
|
-
* 使用分离队列设计,O(1) 时间复杂度
|
|
505
|
-
*/
|
|
506
|
-
async statistics() {
|
|
507
|
-
if (!this.redis) {
|
|
508
|
-
return {
|
|
509
|
-
failed: 0,
|
|
510
|
-
pending: 0,
|
|
511
|
-
completed: 0,
|
|
512
|
-
processing: 0,
|
|
513
|
-
};
|
|
514
|
-
}
|
|
515
|
-
// 并行获取各队列长度,O(1) 时间复杂度
|
|
516
|
-
const [pending, processing, completed, failed] = await Promise.all([
|
|
517
|
-
this.redis.lLen(this.pendingQueue),
|
|
518
|
-
this.redis.lLen(this.processingQueue),
|
|
519
|
-
this.redis.lLen(this.completedQueue),
|
|
520
|
-
this.redis.lLen(this.failedQueue),
|
|
521
|
-
]);
|
|
522
|
-
return {
|
|
523
|
-
pending,
|
|
524
|
-
processing,
|
|
525
|
-
completed,
|
|
526
|
-
failed,
|
|
527
|
-
};
|
|
528
|
-
}
|
|
529
|
-
/**
|
|
530
|
-
* 清空所有队列
|
|
531
|
-
*/
|
|
532
|
-
async clear() {
|
|
533
|
-
if (!this.redis)
|
|
534
|
-
return;
|
|
535
|
-
// 使用 Lua 脚本原子化清空所有队列
|
|
536
|
-
const clearScript = `
|
|
537
|
-
redis.call('DEL', KEYS[1])
|
|
538
|
-
redis.call('DEL', KEYS[2])
|
|
539
|
-
redis.call('DEL', KEYS[3])
|
|
540
|
-
redis.call('DEL', KEYS[4])
|
|
541
|
-
return 1
|
|
542
|
-
`;
|
|
543
|
-
await this.redis.eval(clearScript, {
|
|
544
|
-
keys: [this.failedQueue, this.pendingQueue, this.completedQueue, this.processingQueue],
|
|
545
|
-
arguments: [],
|
|
546
|
-
});
|
|
547
|
-
}
|
|
548
|
-
/**
|
|
549
|
-
* 健康检查
|
|
550
|
-
*/
|
|
551
|
-
async health() {
|
|
552
|
-
if (!this.redis)
|
|
553
|
-
return false;
|
|
554
|
-
const result = await catchIt(() => this.redis.ping());
|
|
555
|
-
return !result.isError() && result.value === 'PONG';
|
|
556
|
-
}
|
|
557
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"redis-queue.test.d.ts","sourceRoot":"","sources":["../../source/redis-queue/redis-queue.test.ts"],"names":[],"mappings":""}
|