@taicode/common-server 3.7.7 → 3.7.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.
Files changed (61) hide show
  1. package/output/context/index.d.ts +6 -0
  2. package/output/context/index.d.ts.map +1 -0
  3. package/output/context/index.js +14 -0
  4. package/output/context/index.test.d.ts +2 -0
  5. package/output/context/index.test.d.ts.map +1 -0
  6. package/output/context/index.test.js +14 -0
  7. package/output/index.d.ts +5 -0
  8. package/output/index.d.ts.map +1 -0
  9. package/output/index.js +5 -0
  10. package/output/rate-limiter/index.d.ts +4 -0
  11. package/output/rate-limiter/index.d.ts.map +1 -0
  12. package/output/rate-limiter/index.js +3 -0
  13. package/output/rate-limiter/memory-store.d.ts +12 -0
  14. package/output/rate-limiter/memory-store.d.ts.map +1 -0
  15. package/output/rate-limiter/memory-store.js +46 -0
  16. package/output/rate-limiter/rate-limiter.d.ts +17 -0
  17. package/output/rate-limiter/rate-limiter.d.ts.map +1 -0
  18. package/output/rate-limiter/rate-limiter.js +64 -0
  19. package/output/rate-limiter/types.d.ts +27 -0
  20. package/output/rate-limiter/types.d.ts.map +1 -0
  21. package/output/rate-limiter/types.js +1 -0
  22. package/output/redis-queue/index.d.ts +8 -0
  23. package/output/redis-queue/index.d.ts.map +1 -0
  24. package/output/redis-queue/index.js +6 -0
  25. package/output/redis-queue/redis-queue-batch-consumer.d.ts +97 -0
  26. package/output/redis-queue/redis-queue-batch-consumer.d.ts.map +1 -0
  27. package/output/redis-queue/redis-queue-batch-consumer.js +341 -0
  28. package/output/redis-queue/redis-queue-batch-consumer.test.d.ts +26 -0
  29. package/output/redis-queue/redis-queue-batch-consumer.test.d.ts.map +1 -0
  30. package/output/redis-queue/redis-queue-batch-consumer.test.js +341 -0
  31. package/output/redis-queue/redis-queue-common.d.ts +73 -0
  32. package/output/redis-queue/redis-queue-common.d.ts.map +1 -0
  33. package/output/redis-queue/redis-queue-common.js +303 -0
  34. package/output/redis-queue/redis-queue-common.test.d.ts +19 -0
  35. package/output/redis-queue/redis-queue-common.test.d.ts.map +1 -0
  36. package/output/redis-queue/redis-queue-common.test.js +585 -0
  37. package/output/redis-queue/redis-queue-consumer.d.ts +95 -0
  38. package/output/redis-queue/redis-queue-consumer.d.ts.map +1 -0
  39. package/output/redis-queue/redis-queue-consumer.js +327 -0
  40. package/output/redis-queue/redis-queue-consumer.test.d.ts +26 -0
  41. package/output/redis-queue/redis-queue-consumer.test.d.ts.map +1 -0
  42. package/output/redis-queue/redis-queue-consumer.test.js +316 -0
  43. package/output/redis-queue/redis-queue-provider.d.ts +69 -0
  44. package/output/redis-queue/redis-queue-provider.d.ts.map +1 -0
  45. package/output/redis-queue/redis-queue-provider.js +205 -0
  46. package/output/redis-queue/redis-queue-provider.test.d.ts +28 -0
  47. package/output/redis-queue/redis-queue-provider.test.d.ts.map +1 -0
  48. package/output/redis-queue/redis-queue-provider.test.js +149 -0
  49. package/output/redis-queue/test-helpers.d.ts +112 -0
  50. package/output/redis-queue/test-helpers.d.ts.map +1 -0
  51. package/output/redis-queue/test-helpers.js +242 -0
  52. package/output/redis-queue/test-helpers.test.d.ts +28 -0
  53. package/output/redis-queue/test-helpers.test.d.ts.map +1 -0
  54. package/output/redis-queue/test-helpers.test.js +572 -0
  55. package/output/redis-queue/types.d.ts +146 -0
  56. package/output/redis-queue/types.d.ts.map +1 -0
  57. package/output/redis-queue/types.js +1 -0
  58. package/output/schema/index.d.ts +177 -0
  59. package/output/schema/index.d.ts.map +1 -0
  60. package/output/schema/index.js +180 -0
  61. package/package.json +2 -2
@@ -0,0 +1,327 @@
1
+ import { catchIt } from '@taicode/common-base';
2
+ import { logger } from '@taicode/common-base';
3
+ import { RedisQueueCommon } from './redis-queue-common.js';
4
+ /**
5
+ * Redis 队列消费者
6
+ *
7
+ * 只负责消费任务,不包含入队逻辑
8
+ *
9
+ * @template R Registry 类型,默认为 RedisQueueRegistry
10
+ * @template K 队列键名类型
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * // 方式 1: 使用默认 RedisQueueRegistry
15
+ * const consumer = new RedisQueueConsumer('email-queue', {
16
+ * redisUrl: 'redis://localhost:6379',
17
+ * concurrency: 5,
18
+ * handler: async (data) => {
19
+ * await sendEmail(data.to, data.subject)
20
+ * return catchIt(() => {})
21
+ * }
22
+ * })
23
+ *
24
+ * // 方式 2: 使用自定义 Registry
25
+ * interface MyRegistry {
26
+ * 'order-queue': { orderId: string; amount: number }
27
+ * }
28
+ *
29
+ * const consumer = new RedisQueueConsumer<MyRegistry, 'order-queue'>(
30
+ * 'order-queue',
31
+ * {
32
+ * redisUrl: 'redis://localhost:6379',
33
+ * handler: async (data) => {
34
+ * logger.info(data.orderId, data.amount)
35
+ * return catchIt(() => {})
36
+ * }
37
+ * }
38
+ * )
39
+ *
40
+ * await consumer.connect() // 自动开始消费
41
+ *
42
+ * // 获取统计信息
43
+ * const stats = await consumer.statistics()
44
+ *
45
+ * // 停止消费
46
+ * consumer.disconnect()
47
+ * ```
48
+ */
49
+ export class RedisQueueConsumer extends RedisQueueCommon {
50
+ consumerRunning = false;
51
+ consumerInterval = null;
52
+ recoveryInterval = null;
53
+ processingTasks = 0; // 当前正在处理的任务数
54
+ processingPromises = new Set(); // 跟踪所有正在处理的任务
55
+ config;
56
+ constructor(queueKey, config) {
57
+ // 验证必填参数
58
+ if (!config.handler) {
59
+ throw new Error('[RedisQueueConsumer] handler is required');
60
+ }
61
+ // 调用父类构造函数
62
+ super(queueKey, {
63
+ redisUrl: config.redisUrl,
64
+ redisClient: config.redisClient,
65
+ cleanupDelay: config.cleanupDelay ?? 86400,
66
+ });
67
+ this.config = {
68
+ handler: config.handler,
69
+ maxRetries: config.maxRetries ?? 3,
70
+ concurrency: config.concurrency ?? 1,
71
+ consumerInterval: config.consumerInterval ?? 1000,
72
+ processingTimeout: config.processingTimeout ?? 60000,
73
+ cleanupDelay: config.cleanupDelay ?? 86400,
74
+ };
75
+ }
76
+ getLogPrefix() {
77
+ return 'RedisQueueConsumer';
78
+ }
79
+ /**
80
+ * 连接 Redis 并自动启动消费者
81
+ */
82
+ async connect() {
83
+ await super.connect();
84
+ // 连接成功后启动消费者和恢复机制
85
+ this.startConsumer();
86
+ this.startRecovery();
87
+ }
88
+ /**
89
+ * 断开 Redis 连接并停止消费者
90
+ * 会等待所有正在处理的任务完成后再断开连接
91
+ */
92
+ async disconnect() {
93
+ // 先停止消费者和恢复机制,不再接受新任务
94
+ this.stopConsumer();
95
+ this.stopRecovery();
96
+ // 等待所有正在处理的任务完成
97
+ if (this.processingPromises.size > 0) {
98
+ logger.info(`[RedisQueueConsumer] Waiting for ${this.processingPromises.size} tasks to complete...`);
99
+ await Promise.allSettled(this.processingPromises);
100
+ logger.info(`[RedisQueueConsumer] All tasks completed`);
101
+ }
102
+ // 最后断开 Redis 连接
103
+ super.disconnect();
104
+ }
105
+ /**
106
+ * 处理单个任务
107
+ */
108
+ async processTask(taskId) {
109
+ this.processingTasks++;
110
+ // 创建一个 Promise 来跟踪这个任务的处理过程
111
+ const taskPromise = (async () => {
112
+ try {
113
+ const task = await this.getTask(taskId);
114
+ if (!task) {
115
+ logger.warn(`[RedisQueueConsumer] Task not found: ${taskId}`);
116
+ return;
117
+ }
118
+ // 任务应该是 pending 状态(Lua 脚本已确保延迟检查)
119
+ if (task.status !== 'pending') {
120
+ logger.info(`[RedisQueueConsumer] Task ${taskId} has invalid status (${task.status}), marking as failed`);
121
+ await this.applyStatus(taskId, task.status, 'failed');
122
+ return;
123
+ }
124
+ try {
125
+ // 任务已在 processing 队列中(由 Lua 脚本完成),只需更新状态和开始时间
126
+ task.status = 'processing';
127
+ task.processingStartTime = Date.now();
128
+ const taskKey = `${this.queueKey}:task:${taskId}`;
129
+ await this.redis.setEx(taskKey, this.config.cleanupDelay, JSON.stringify(task));
130
+ // 执行任务处理器
131
+ await this.config.handler(task.data);
132
+ // 更新状态为完成
133
+ await this.applyStatus(taskId, 'processing', 'completed');
134
+ logger.info(`[RedisQueueConsumer] Task completed: ${taskId}`);
135
+ }
136
+ catch (error) {
137
+ logger.error(`[RedisQueueConsumer] Task failed: ${taskId}`, error);
138
+ // 检查是否需要重试
139
+ if (task.retryCount < task.maxRetries) {
140
+ task.retryCount++;
141
+ task.status = 'pending';
142
+ task.processingStartTime = undefined;
143
+ const taskKey = `${this.queueKey}:task:${taskId}`;
144
+ // 使用 Lua 脚本确保原子性
145
+ const script = `
146
+ redis.call('SETEX', KEYS[1], ARGV[1], ARGV[2])
147
+ redis.call('LREM', KEYS[2], 0, ARGV[3])
148
+ redis.call('RPUSH', KEYS[3], ARGV[3])
149
+ return 1
150
+ `;
151
+ await this.redis.eval(script, {
152
+ keys: [taskKey, this.processingQueue, this.pendingQueue],
153
+ arguments: [this.config.cleanupDelay.toString(), JSON.stringify(task), taskId],
154
+ });
155
+ logger.info(`[RedisQueueConsumer] Task ${taskId} will retry (${task.retryCount}/${task.maxRetries})`);
156
+ }
157
+ else {
158
+ task.status = 'failed';
159
+ task.processingStartTime = undefined;
160
+ const taskKey = `${this.queueKey}:task:${taskId}`;
161
+ // 使用 Lua 脚本确保原子性
162
+ const script = `
163
+ redis.call('SETEX', KEYS[1], ARGV[1], ARGV[2])
164
+ redis.call('LREM', KEYS[2], 0, ARGV[3])
165
+ redis.call('RPUSH', KEYS[3], ARGV[3])
166
+ return 1
167
+ `;
168
+ await this.redis.eval(script, {
169
+ keys: [taskKey, this.processingQueue, this.failedQueue],
170
+ arguments: [this.config.cleanupDelay.toString(), JSON.stringify(task), taskId],
171
+ });
172
+ logger.error(`[RedisQueueConsumer] Task ${taskId} failed after ${task.maxRetries} retries`);
173
+ }
174
+ }
175
+ }
176
+ finally {
177
+ this.processingTasks--;
178
+ }
179
+ })();
180
+ // 将任务 Promise 添加到集合中
181
+ this.processingPromises.add(taskPromise);
182
+ // 任务完成后从集合中移除
183
+ taskPromise.finally(() => {
184
+ this.processingPromises.delete(taskPromise);
185
+ });
186
+ // 返回任务 Promise
187
+ return taskPromise;
188
+ }
189
+ /**
190
+ * 启动恢复机制(内部方法,自动调用)
191
+ */
192
+ startRecovery() {
193
+ if (this.recoveryInterval || !this.redis) {
194
+ return;
195
+ }
196
+ // 立即执行一次恢复
197
+ this.recoverStalled(this.config.processingTimeout).catch(error => {
198
+ logger.error('[RedisQueueConsumer] Initial recovery error:', error);
199
+ });
200
+ // 定期检查(每 10 秒检查一次)
201
+ this.recoveryInterval = setInterval(() => {
202
+ this.recoverStalled(this.config.processingTimeout).catch(error => {
203
+ logger.error('[RedisQueueConsumer] Recovery error:', error);
204
+ });
205
+ }, 10000);
206
+ logger.info('[RedisQueueConsumer] Recovery mechanism started');
207
+ }
208
+ /**
209
+ * 停止恢复机制(内部方法,自动调用)
210
+ */
211
+ stopRecovery() {
212
+ if (this.recoveryInterval) {
213
+ clearInterval(this.recoveryInterval);
214
+ this.recoveryInterval = null;
215
+ logger.info('[RedisQueueConsumer] Recovery mechanism stopped');
216
+ }
217
+ }
218
+ /**
219
+ * 启动消费者(内部方法,自动调用)
220
+ */
221
+ startConsumer() {
222
+ if (this.consumerRunning || !this.redis) {
223
+ return;
224
+ }
225
+ this.consumerRunning = true;
226
+ logger.info(`[RedisQueueConsumer] Consumer started with concurrency: ${this.config.concurrency}`);
227
+ // Lua 脚本: 原子化从 pending 取出任务并移到 processing(只取已到延迟时间的任务)
228
+ const popAndMoveScript = `
229
+ local pendingQueue = KEYS[1]
230
+ local processingQueue = KEYS[2]
231
+ local queueKeyPrefix = KEYS[3]
232
+ local count = tonumber(ARGV[1])
233
+ local currentTime = tonumber(ARGV[2])
234
+
235
+ local taskIds = {}
236
+ local checkedCount = 0
237
+ local maxCheck = count * 3 -- 最多检查 count*3 个任务,避免无限循环
238
+
239
+ while #taskIds < count and checkedCount < maxCheck do
240
+ local taskId = redis.call('LPOP', pendingQueue)
241
+ if not taskId then
242
+ break
243
+ end
244
+
245
+ checkedCount = checkedCount + 1
246
+
247
+ -- 获取任务详情检查延迟时间
248
+ local taskKey = queueKeyPrefix .. ':task:' .. taskId
249
+ local taskData = redis.call('GET', taskKey)
250
+
251
+ if taskData then
252
+ local task = cjson.decode(taskData)
253
+ local delayUntil = task.delayUntil
254
+
255
+ -- 如果没有延迟或已到延迟时间,则移到 processing
256
+ if not delayUntil or delayUntil <= currentTime then
257
+ redis.call('RPUSH', processingQueue, taskId)
258
+ table.insert(taskIds, taskId)
259
+ else
260
+ -- 未到延迟时间,放回队列尾部
261
+ redis.call('RPUSH', pendingQueue, taskId)
262
+ end
263
+ end
264
+ end
265
+
266
+ return taskIds
267
+ `;
268
+ this.consumerInterval = setInterval(async () => {
269
+ try {
270
+ // 检查当前是否有可用的并发槽位
271
+ const availableSlots = this.config.concurrency - this.processingTasks;
272
+ if (availableSlots <= 0) {
273
+ return; // 已达到并发限制,等待下一次轮询
274
+ }
275
+ // 使用 Lua 脚本原子化取出任务并移到 processing 队列
276
+ const taskIds = await this.redis.eval(popAndMoveScript, {
277
+ keys: [this.pendingQueue, this.processingQueue, this.queueKey],
278
+ arguments: [availableSlots.toString(), Date.now().toString()],
279
+ });
280
+ // 并发处理所有任务(不等待完成)
281
+ taskIds.forEach(taskId => {
282
+ this.processTask(taskId).catch(error => {
283
+ logger.error(`[RedisQueueConsumer] Unhandled error in processTask: ${taskId}`, error);
284
+ });
285
+ });
286
+ }
287
+ catch (error) {
288
+ logger.error('[RedisQueueConsumer] Consumer error:', error);
289
+ }
290
+ }, this.config.consumerInterval);
291
+ }
292
+ /**
293
+ * 停止消费者(内部方法,自动调用)
294
+ */
295
+ stopConsumer() {
296
+ if (this.consumerInterval) {
297
+ clearInterval(this.consumerInterval);
298
+ this.consumerInterval = null;
299
+ }
300
+ this.consumerRunning = false;
301
+ logger.info('[RedisQueueConsumer] Consumer stopped');
302
+ }
303
+ /**
304
+ * 获取队列统计信息(O(1) 时间复杂度)
305
+ */
306
+ async statistics() {
307
+ if (!this.redis) {
308
+ return { pending: 0, processing: 0, completed: 0, failed: 0 };
309
+ }
310
+ const [pending, processing, completed, failed] = await Promise.all([
311
+ this.redis.lLen(this.pendingQueue),
312
+ this.redis.lLen(this.processingQueue),
313
+ this.redis.lLen(this.completedQueue),
314
+ this.redis.lLen(this.failedQueue),
315
+ ]);
316
+ return { pending, processing, completed, failed };
317
+ }
318
+ /**
319
+ * 健康检查
320
+ */
321
+ async health() {
322
+ if (!this.redis)
323
+ return false;
324
+ const result = await catchIt(() => this.redis.ping());
325
+ return !result.isError() && result.value === 'PONG';
326
+ }
327
+ }
@@ -0,0 +1,26 @@
1
+ type TestTaskData = {
2
+ id?: string;
3
+ value?: number | string;
4
+ test?: boolean | string;
5
+ index?: number;
6
+ payload?: string;
7
+ order?: number;
8
+ taskId?: number;
9
+ message?: string;
10
+ name?: string;
11
+ shouldFail?: boolean;
12
+ step?: number;
13
+ real?: boolean;
14
+ nested?: {
15
+ value: number;
16
+ };
17
+ example?: string;
18
+ data?: any;
19
+ };
20
+ declare module './types.js' {
21
+ interface RedisQueueRegistry {
22
+ [key: `test:queue:${string}`]: TestTaskData;
23
+ }
24
+ }
25
+ export {};
26
+ //# sourceMappingURL=redis-queue-consumer.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis-queue-consumer.test.d.ts","sourceRoot":"","sources":["../../source/redis-queue/redis-queue-consumer.test.ts"],"names":[],"mappings":"AAQA,KAAK,YAAY,GAAG;IAClB,EAAE,CAAC,EAAE,MAAM,CAAA;IACX,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;IACvB,IAAI,CAAC,EAAE,OAAO,GAAG,MAAM,CAAA;IACvB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,OAAO,CAAA;IACd,MAAM,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,CAAA;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,IAAI,CAAC,EAAE,GAAG,CAAA;CACX,CAAA;AAGD,OAAO,QAAQ,YAAY,CAAC;IAC1B,UAAU,kBAAkB;QAC1B,CAAC,GAAG,EAAE,cAAc,MAAM,EAAE,GAAG,YAAY,CAAA;KAC5C;CACF"}
@@ -0,0 +1,316 @@
1
+ import { describe, it, expect, afterEach } from 'vitest';
2
+ import { catchIt } from '@taicode/common-base';
3
+ import { RedisQueueProvider } from './redis-queue-provider.js';
4
+ import { RedisQueueConsumer } from './redis-queue-consumer.js';
5
+ import { dispatchQueueTask, waitQueueCompletion, clearQueue, getQueueTasks } from './test-helpers.js';
6
+ const REDIS_URL = process.env.REDIS_URL || 'redis://localhost:6379';
7
+ describe('RedisQueueConsumer', () => {
8
+ const providers = [];
9
+ const consumers = [];
10
+ afterEach(async () => {
11
+ for (const consumer of consumers) {
12
+ await clearQueue(consumer);
13
+ await consumer.disconnect();
14
+ }
15
+ for (const provider of providers) {
16
+ provider.disconnect();
17
+ }
18
+ providers.length = 0;
19
+ consumers.length = 0;
20
+ });
21
+ const createQueue = (handler, options) => {
22
+ const uniqueKey = `test:queue:${Date.now()}:${Math.random()}`;
23
+ const provider = new RedisQueueProvider(uniqueKey, {
24
+ redisUrl: REDIS_URL,
25
+ });
26
+ const consumer = new RedisQueueConsumer(uniqueKey, {
27
+ redisUrl: REDIS_URL,
28
+ consumerInterval: 100,
29
+ maxRetries: 2,
30
+ ...options,
31
+ handler,
32
+ });
33
+ providers.push(provider);
34
+ consumers.push(consumer);
35
+ return { provider, consumer };
36
+ };
37
+ describe('连接管理', () => {
38
+ it('应该成功连接到 Redis', async () => {
39
+ const { consumer } = createQueue(async () => catchIt(() => { }));
40
+ await consumer.connect();
41
+ const health = await consumer.health();
42
+ expect(health).toBe(true);
43
+ });
44
+ it('连接后应该自动启动消费者', async () => {
45
+ let processed = false;
46
+ const { provider, consumer } = createQueue(async () => {
47
+ processed = true;
48
+ return catchIt(() => { });
49
+ });
50
+ await provider.connect();
51
+ await consumer.connect();
52
+ await provider.enqueue({ test: true });
53
+ await new Promise(resolve => setTimeout(resolve, 300));
54
+ expect(processed).toBe(true);
55
+ });
56
+ });
57
+ describe('任务处理', () => {
58
+ it('应该成功处理任务', async () => {
59
+ const processedData = [];
60
+ const { provider, consumer } = createQueue(async (data) => {
61
+ processedData.push(data);
62
+ return catchIt(() => { });
63
+ });
64
+ await provider.connect();
65
+ await consumer.connect();
66
+ await provider.enqueue({ value: 'test' });
67
+ await new Promise(resolve => setTimeout(resolve, 500));
68
+ expect(processedData).toHaveLength(1);
69
+ expect(processedData[0]).toEqual({ value: 'test' });
70
+ const stats = await consumer.statistics();
71
+ expect(stats.completed).toBe(1);
72
+ });
73
+ it('应该能够使用 dispatchQueueTask 立即处理任务', async () => {
74
+ const processedData = [];
75
+ const { provider, consumer } = createQueue(async (data) => {
76
+ processedData.push(data);
77
+ return catchIt(() => { });
78
+ });
79
+ await provider.connect();
80
+ await consumer.connect();
81
+ const taskIds = await provider.enqueue([{ value: 1 }, { value: 2 }, { value: 3 }]);
82
+ // 使用 dispatchQueueTask 立即处理任务
83
+ await dispatchQueueTask(consumer, taskIds);
84
+ expect(processedData).toHaveLength(3);
85
+ expect(processedData.map(d => d.value)).toEqual([1, 2, 3]);
86
+ const stats = await consumer.statistics();
87
+ expect(stats.completed).toBe(3);
88
+ });
89
+ it('应该按 FIFO 顺序处理任务', async () => {
90
+ const processOrder = [];
91
+ const { provider, consumer } = createQueue(async (data) => {
92
+ if (data.order !== undefined) {
93
+ processOrder.push(data.order);
94
+ }
95
+ return catchIt(() => { });
96
+ });
97
+ await provider.connect();
98
+ await consumer.connect();
99
+ await provider.enqueue([{ order: 1 }, { order: 2 }, { order: 3 }]);
100
+ await new Promise(resolve => setTimeout(resolve, 1000));
101
+ expect(processOrder).toEqual([1, 2, 3]);
102
+ });
103
+ it('应该能够使用 waitQueueCompletion 等待队列完成', async () => {
104
+ const { provider, consumer } = createQueue(async () => {
105
+ await new Promise(resolve => setTimeout(resolve, 100));
106
+ return catchIt(() => { });
107
+ });
108
+ await provider.connect();
109
+ await consumer.connect();
110
+ await provider.enqueue([{ test: 1 }, { test: 2 }, { test: 3 }]);
111
+ // 等待所有任务完成
112
+ await waitQueueCompletion(consumer, stats => stats.pending === 0 && stats.processing === 0 && stats.completed === 3);
113
+ const stats = await consumer.statistics();
114
+ expect(stats.completed).toBe(3);
115
+ });
116
+ it('应该能够使用 getQueueTasks 获取任务详情', async () => {
117
+ const { provider, consumer } = createQueue(async () => catchIt(() => { }));
118
+ await provider.connect();
119
+ await consumer.connect();
120
+ await provider.enqueue([{ name: 'task1' }, { name: 'task2' }]);
121
+ // 获取待处理任务
122
+ const pendingTasks = await getQueueTasks(provider, 'pending');
123
+ expect(pendingTasks).toHaveLength(2);
124
+ expect(pendingTasks.map(t => t.data.name).sort()).toEqual(['task1', 'task2']);
125
+ // 等待任务完成
126
+ await waitQueueCompletion(consumer, stats => stats.completed === 2);
127
+ // 获取已完成任务
128
+ const completedTasks = await getQueueTasks(provider, 'completed');
129
+ expect(completedTasks).toHaveLength(2);
130
+ expect(completedTasks.every(t => t.status === 'completed')).toBe(true);
131
+ });
132
+ });
133
+ describe('重试机制', () => {
134
+ it('失败的任务应该自动重试', async () => {
135
+ let attemptCount = 0;
136
+ const { provider, consumer } = createQueue(async () => {
137
+ attemptCount++;
138
+ throw new Error('Task failed');
139
+ }, { maxRetries: 2 });
140
+ await provider.connect();
141
+ await consumer.connect();
142
+ const taskId = await provider.enqueue({ test: 1 });
143
+ await new Promise(resolve => setTimeout(resolve, 3000));
144
+ // 最多 1 次初始 + 2 次重试 = 3 次,但允许恢复机制导致的额外尝试
145
+ expect(attemptCount).toBeGreaterThanOrEqual(3);
146
+ expect(attemptCount).toBeLessThanOrEqual(4);
147
+ const stats = await consumer.statistics();
148
+ expect(stats.failed).toBe(1);
149
+ });
150
+ });
151
+ describe('消费者管理', () => {
152
+ it('断开连接后消费者应该停止', async () => {
153
+ let processCount = 0;
154
+ const { provider, consumer } = createQueue(async () => {
155
+ processCount++;
156
+ return catchIt(() => { });
157
+ });
158
+ await provider.connect();
159
+ await consumer.connect();
160
+ await provider.enqueue({ test: 1 });
161
+ await new Promise(resolve => setTimeout(resolve, 300));
162
+ expect(processCount).toBe(1);
163
+ await consumer.disconnect();
164
+ await provider.connect();
165
+ await provider.enqueue({ test: 2 });
166
+ await new Promise(resolve => setTimeout(resolve, 300));
167
+ expect(processCount).toBe(1); // 没有增加
168
+ });
169
+ it('disconnect 应该等待正在处理的任务完成', async () => {
170
+ const processedTasks = [];
171
+ let processingTask = null;
172
+ const { provider, consumer } = createQueue(async (data) => {
173
+ processingTask = data.taskId || 0;
174
+ await new Promise(resolve => setTimeout(resolve, 500)); // 模拟长时间处理
175
+ processedTasks.push(data.taskId || 0);
176
+ processingTask = null;
177
+ return catchIt(() => { });
178
+ });
179
+ await provider.connect();
180
+ await consumer.connect();
181
+ // 添加一个任务
182
+ await provider.enqueue({ taskId: 1 });
183
+ // 等待任务开始处理
184
+ await new Promise(resolve => setTimeout(resolve, 200));
185
+ expect(processingTask).toBe(1);
186
+ expect(processedTasks).toHaveLength(0);
187
+ // 调用 disconnect,应该等待任务完成
188
+ const disconnectPromise = consumer.disconnect();
189
+ // 此时任务应该还在处理中
190
+ expect(processingTask).toBe(1);
191
+ // 等待 disconnect 完成
192
+ await disconnectPromise;
193
+ // disconnect 完成后,任务应该已经处理完成
194
+ expect(processingTask).toBe(null);
195
+ expect(processedTasks).toHaveLength(1);
196
+ expect(processedTasks[0]).toBe(1);
197
+ });
198
+ });
199
+ describe('队列统计', () => {
200
+ it('应该正确返回队列统计信息', async () => {
201
+ const { provider, consumer } = createQueue(async () => {
202
+ await new Promise(resolve => setTimeout(resolve, 100));
203
+ return catchIt(() => { });
204
+ });
205
+ await provider.connect();
206
+ await consumer.connect();
207
+ await provider.enqueue([{ data: 1 }, { data: 2 }, { data: 3 }]);
208
+ await new Promise(resolve => setTimeout(resolve, 50));
209
+ const stats = await consumer.statistics();
210
+ expect(stats.pending + stats.processing).toBeGreaterThan(0);
211
+ });
212
+ });
213
+ describe('并发处理', () => {
214
+ it('应该支持并发处理多个任务', async () => {
215
+ const processing = [];
216
+ const completed = [];
217
+ const { provider, consumer } = createQueue(async (data) => {
218
+ if (data.taskId !== undefined) {
219
+ processing.push(data.taskId);
220
+ }
221
+ await new Promise(resolve => setTimeout(resolve, 200));
222
+ if (data.taskId !== undefined) {
223
+ completed.push(data.taskId);
224
+ }
225
+ return catchIt(() => { });
226
+ }, { concurrency: 3 });
227
+ await provider.connect();
228
+ await consumer.connect();
229
+ await provider.enqueue([
230
+ { taskId: 1 }, { taskId: 2 }, { taskId: 3 }, { taskId: 4 }, { taskId: 5 },
231
+ ]);
232
+ await new Promise(resolve => setTimeout(resolve, 250));
233
+ expect(processing.length).toBeGreaterThanOrEqual(2);
234
+ await new Promise(resolve => setTimeout(resolve, 1500));
235
+ expect(completed.length).toBe(5);
236
+ });
237
+ });
238
+ describe('幂等性', () => {
239
+ it('应该支持在 data 中指定 id 来实现幂等性', async () => {
240
+ let processCount = 0;
241
+ const { provider, consumer } = createQueue(async () => {
242
+ processCount++;
243
+ return catchIt(() => { });
244
+ });
245
+ await provider.connect();
246
+ await consumer.connect();
247
+ await provider.enqueue({ id: 'unique-1', value: 1 });
248
+ await provider.enqueue({ id: 'unique-1', value: 2 });
249
+ await provider.enqueue({ id: 'unique-2', value: 3 });
250
+ await new Promise(resolve => setTimeout(resolve, 1000));
251
+ expect(processCount).toBe(2); // 只处理 unique-1 和 unique-2
252
+ });
253
+ });
254
+ describe('延迟处理', () => {
255
+ it('应该支持延迟处理任务', async () => {
256
+ const startTime = Date.now();
257
+ let processTime = 0;
258
+ const { provider, consumer } = createQueue(async () => {
259
+ processTime = Date.now() - startTime;
260
+ return catchIt(() => { });
261
+ });
262
+ await provider.connect();
263
+ await consumer.connect();
264
+ await provider.enqueue({ test: true });
265
+ await new Promise(resolve => setTimeout(resolve, 1000));
266
+ expect(processTime).toBeGreaterThan(0);
267
+ });
268
+ });
269
+ describe('超时恢复', () => {
270
+ it('超时的任务应该直接标记为失败', { timeout: 15000 }, async () => {
271
+ let processCount = 0;
272
+ const { provider, consumer } = createQueue(async () => {
273
+ processCount++;
274
+ // 模拟处理卡住,永远不完成 (但超时机制会检测到)
275
+ await new Promise(resolve => setTimeout(resolve, 20000));
276
+ return catchIt(() => { });
277
+ }, {
278
+ processingTimeout: 500, // 500ms 超时
279
+ consumerInterval: 100,
280
+ });
281
+ await provider.connect();
282
+ await consumer.connect();
283
+ await provider.enqueue({ value: 1 });
284
+ // 等待任务被处理和超时恢复 (需要等待至少2个恢复周期: 10秒)
285
+ await new Promise(resolve => setTimeout(resolve, 12000));
286
+ const stats = await consumer.statistics();
287
+ // 超时后直接标记为失败,不应该重试
288
+ expect(stats.failed).toBe(1);
289
+ expect(stats.pending).toBe(0);
290
+ expect(stats.processing).toBe(0);
291
+ expect(stats.completed).toBe(0);
292
+ // 应该只处理一次,不会重试
293
+ expect(processCount).toBe(1);
294
+ });
295
+ it('未超时的失败任务应该正常重试', async () => {
296
+ let attemptCount = 0;
297
+ const { provider, consumer } = createQueue(async () => {
298
+ attemptCount++;
299
+ throw new Error('Task failed');
300
+ }, {
301
+ maxRetries: 3,
302
+ processingTimeout: 5000, // 5秒超时,足够长不会触发
303
+ consumerInterval: 100,
304
+ });
305
+ await provider.connect();
306
+ await consumer.connect();
307
+ await provider.enqueue({ value: 1 });
308
+ // 等待所有重试完成
309
+ await new Promise(resolve => setTimeout(resolve, 3000));
310
+ const stats = await consumer.statistics();
311
+ // 应该重试 3 次后失败
312
+ expect(stats.failed).toBe(1);
313
+ expect(attemptCount).toBe(4); // 初始 1 次 + 3 次重试
314
+ });
315
+ });
316
+ });