@taicode/common-server 3.7.4 → 3.7.7

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 (62) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +9 -10
  3. package/output/context/index.d.ts +0 -6
  4. package/output/context/index.d.ts.map +0 -1
  5. package/output/context/index.js +0 -14
  6. package/output/context/index.test.d.ts +0 -2
  7. package/output/context/index.test.d.ts.map +0 -1
  8. package/output/context/index.test.js +0 -14
  9. package/output/index.d.ts +0 -5
  10. package/output/index.d.ts.map +0 -1
  11. package/output/index.js +0 -5
  12. package/output/rate-limiter/index.d.ts +0 -4
  13. package/output/rate-limiter/index.d.ts.map +0 -1
  14. package/output/rate-limiter/index.js +0 -3
  15. package/output/rate-limiter/memory-store.d.ts +0 -12
  16. package/output/rate-limiter/memory-store.d.ts.map +0 -1
  17. package/output/rate-limiter/memory-store.js +0 -46
  18. package/output/rate-limiter/rate-limiter.d.ts +0 -17
  19. package/output/rate-limiter/rate-limiter.d.ts.map +0 -1
  20. package/output/rate-limiter/rate-limiter.js +0 -64
  21. package/output/rate-limiter/types.d.ts +0 -27
  22. package/output/rate-limiter/types.d.ts.map +0 -1
  23. package/output/rate-limiter/types.js +0 -1
  24. package/output/redis-queue/index.d.ts +0 -8
  25. package/output/redis-queue/index.d.ts.map +0 -1
  26. package/output/redis-queue/index.js +0 -6
  27. package/output/redis-queue/redis-queue-batch-consumer.d.ts +0 -97
  28. package/output/redis-queue/redis-queue-batch-consumer.d.ts.map +0 -1
  29. package/output/redis-queue/redis-queue-batch-consumer.js +0 -341
  30. package/output/redis-queue/redis-queue-batch-consumer.test.d.ts +0 -26
  31. package/output/redis-queue/redis-queue-batch-consumer.test.d.ts.map +0 -1
  32. package/output/redis-queue/redis-queue-batch-consumer.test.js +0 -341
  33. package/output/redis-queue/redis-queue-common.d.ts +0 -73
  34. package/output/redis-queue/redis-queue-common.d.ts.map +0 -1
  35. package/output/redis-queue/redis-queue-common.js +0 -303
  36. package/output/redis-queue/redis-queue-common.test.d.ts +0 -19
  37. package/output/redis-queue/redis-queue-common.test.d.ts.map +0 -1
  38. package/output/redis-queue/redis-queue-common.test.js +0 -585
  39. package/output/redis-queue/redis-queue-consumer.d.ts +0 -95
  40. package/output/redis-queue/redis-queue-consumer.d.ts.map +0 -1
  41. package/output/redis-queue/redis-queue-consumer.js +0 -327
  42. package/output/redis-queue/redis-queue-consumer.test.d.ts +0 -26
  43. package/output/redis-queue/redis-queue-consumer.test.d.ts.map +0 -1
  44. package/output/redis-queue/redis-queue-consumer.test.js +0 -316
  45. package/output/redis-queue/redis-queue-provider.d.ts +0 -69
  46. package/output/redis-queue/redis-queue-provider.d.ts.map +0 -1
  47. package/output/redis-queue/redis-queue-provider.js +0 -205
  48. package/output/redis-queue/redis-queue-provider.test.d.ts +0 -28
  49. package/output/redis-queue/redis-queue-provider.test.d.ts.map +0 -1
  50. package/output/redis-queue/redis-queue-provider.test.js +0 -149
  51. package/output/redis-queue/test-helpers.d.ts +0 -112
  52. package/output/redis-queue/test-helpers.d.ts.map +0 -1
  53. package/output/redis-queue/test-helpers.js +0 -242
  54. package/output/redis-queue/test-helpers.test.d.ts +0 -28
  55. package/output/redis-queue/test-helpers.test.d.ts.map +0 -1
  56. package/output/redis-queue/test-helpers.test.js +0 -572
  57. package/output/redis-queue/types.d.ts +0 -146
  58. package/output/redis-queue/types.d.ts.map +0 -1
  59. package/output/redis-queue/types.js +0 -1
  60. package/output/schema/index.d.ts +0 -177
  61. package/output/schema/index.d.ts.map +0 -1
  62. package/output/schema/index.js +0 -180
@@ -1,341 +0,0 @@
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 RedisQueueBatchConsumer('email-queue', {
16
- * redisUrl: 'redis://localhost:6379',
17
- * batchSize: 50,
18
- * handler: async (dataList) => {
19
- * await sendEmailsBatch(dataList.map(d => d.to))
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 RedisQueueBatchConsumer<MyRegistry, 'order-queue'>(
30
- * 'order-queue',
31
- * {
32
- * redisUrl: 'redis://localhost:6379',
33
- * batchSize: 50,
34
- * handler: async (dataList) => {
35
- * const total = dataList.reduce((sum, d) => sum + d.amount, 0)
36
- * logger.info('Total amount:', total)
37
- * return catchIt(() => {})
38
- * }
39
- * }
40
- * )
41
- *
42
- * await consumer.connect() // 自动开始消费
43
- *
44
- * // 获取统计信息
45
- * const stats = await consumer.statistics()
46
- *
47
- * // 停止消费
48
- * consumer.disconnect()
49
- * ```
50
- */
51
- export class RedisQueueBatchConsumer extends RedisQueueCommon {
52
- consumerRunning = false;
53
- consumerInterval = null;
54
- recoveryInterval = null;
55
- processingBatches = 0; // 当前正在处理的批次数
56
- processingPromises = new Set(); // 跟踪所有正在处理的批次
57
- config;
58
- constructor(queueKey, config) {
59
- // 验证必填参数
60
- if (!config.handler) {
61
- throw new Error('[RedisQueueBatchConsumer] handler is required');
62
- }
63
- // 调用父类构造函数
64
- super(queueKey, {
65
- redisUrl: config.redisUrl,
66
- redisClient: config.redisClient,
67
- cleanupDelay: config.cleanupDelay ?? 86400,
68
- });
69
- this.config = {
70
- handler: config.handler,
71
- batchSize: config.batchSize ?? 10,
72
- maxRetries: config.maxRetries ?? 3,
73
- concurrency: config.concurrency ?? 1,
74
- consumerInterval: config.consumerInterval ?? 1000,
75
- processingTimeout: config.processingTimeout ?? 60000, // 60 seconds
76
- };
77
- }
78
- getLogPrefix() {
79
- return 'RedisQueueBatchConsumer';
80
- }
81
- /**
82
- * 连接 Redis 并自动启动消费者
83
- */
84
- async connect() {
85
- await super.connect();
86
- // 连接成功后启动消费者和恢复机制
87
- this.startConsumer();
88
- this.startRecovery();
89
- }
90
- /**
91
- * 断开 Redis 连接并停止消费者
92
- * 会等待所有正在处理的批次完成后再断开连接
93
- */
94
- async disconnect() {
95
- // 先停止消费者和恢复机制,不再接受新任务
96
- this.stopConsumer();
97
- this.stopRecovery();
98
- // 等待所有正在处理的批次完成
99
- if (this.processingPromises.size > 0) {
100
- logger.info(`[RedisQueueBatchConsumer] Waiting for ${this.processingPromises.size} batches to complete...`);
101
- await Promise.allSettled(this.processingPromises);
102
- logger.info(`[RedisQueueBatchConsumer] All batches completed`);
103
- }
104
- // 最后断开 Redis 连接
105
- super.disconnect();
106
- }
107
- /**
108
- * 批量处理任务
109
- */
110
- async processBatch(taskIds) {
111
- this.processingBatches++;
112
- // 创建一个 Promise 来跟踪这个批次的处理过程
113
- const batchPromise = (async () => {
114
- try {
115
- // 获取所有任务
116
- const tasks = await Promise.all(taskIds.map(id => this.getTask(id)));
117
- const validTasks = tasks.filter((task) => task !== null);
118
- if (validTasks.length === 0) {
119
- logger.warn(`[RedisQueueBatchConsumer] No valid tasks found in batch`);
120
- return;
121
- }
122
- // 过滤出有效的待处理任务
123
- const tasksToProcess = [];
124
- for (const task of validTasks) {
125
- // 检查状态
126
- if (task.status !== 'pending') {
127
- logger.info(`[RedisQueueBatchConsumer] Task ${task.id} has invalid status (${task.status}), marking as failed`);
128
- await this.applyStatus(task.id, task.status, 'failed');
129
- continue;
130
- }
131
- tasksToProcess.push(task);
132
- }
133
- if (tasksToProcess.length === 0) {
134
- return;
135
- }
136
- try {
137
- // 任务已在 processing 队列中(由 Lua 脚本完成),只需更新状态和开始时间
138
- const taskIdList = tasksToProcess.map(t => t.id);
139
- const now = Date.now();
140
- await Promise.all(tasksToProcess.map(task => {
141
- task.status = 'processing';
142
- task.processingStartTime = now;
143
- const taskKey = `${this.queueKey}:task:${task.id}`;
144
- return this.redis.setEx(taskKey, this.cleanupDelay, JSON.stringify(task));
145
- }));
146
- // 批量处理所有任务
147
- const dataList = tasksToProcess.map(t => t.data);
148
- await this.config.handler(dataList);
149
- // 批量更新状态为完成
150
- const updatedCount = await this.applyStatusBatch(taskIdList, 'processing', 'completed');
151
- logger.info(`[RedisQueueBatchConsumer] Batch completed: ${updatedCount} tasks`);
152
- }
153
- catch (error) {
154
- logger.error(`[RedisQueueBatchConsumer] Batch failed:`, error);
155
- // 批量重试或失败
156
- for (const task of tasksToProcess) {
157
- if (task.retryCount < task.maxRetries) {
158
- task.retryCount++;
159
- task.status = 'pending';
160
- task.processingStartTime = undefined;
161
- const taskKey = `${this.queueKey}:task:${task.id}`;
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.pendingQueue],
170
- arguments: [this.cleanupDelay.toString(), JSON.stringify(task), task.id],
171
- });
172
- logger.info(`[RedisQueueBatchConsumer] Task ${task.id} will retry (${task.retryCount}/${task.maxRetries})`);
173
- }
174
- else {
175
- task.status = 'failed';
176
- task.processingStartTime = undefined;
177
- const taskKey = `${this.queueKey}:task:${task.id}`;
178
- const script = `
179
- redis.call('SETEX', KEYS[1], ARGV[1], ARGV[2])
180
- redis.call('LREM', KEYS[2], 0, ARGV[3])
181
- redis.call('RPUSH', KEYS[3], ARGV[3])
182
- return 1
183
- `;
184
- await this.redis.eval(script, {
185
- keys: [taskKey, this.processingQueue, this.failedQueue],
186
- arguments: [this.cleanupDelay.toString(), JSON.stringify(task), task.id],
187
- });
188
- logger.error(`[RedisQueueBatchConsumer] Task ${task.id} failed after ${task.maxRetries} retries`);
189
- }
190
- }
191
- }
192
- }
193
- finally {
194
- this.processingBatches--;
195
- }
196
- })();
197
- // 将批次 Promise 添加到集合中
198
- this.processingPromises.add(batchPromise);
199
- // 批次完成后从集合中移除
200
- batchPromise.finally(() => {
201
- this.processingPromises.delete(batchPromise);
202
- });
203
- // 返回批次 Promise
204
- return batchPromise;
205
- }
206
- /**
207
- * 启动恢复机制
208
- */
209
- startRecovery() {
210
- if (this.recoveryInterval || !this.redis) {
211
- return;
212
- }
213
- // 立即执行一次恢复
214
- this.recoverStalled(this.config.processingTimeout).catch(error => {
215
- logger.error('[RedisQueueBatchConsumer] Initial recovery error:', error);
216
- });
217
- // 定期检查(每 10 秒检查一次)
218
- this.recoveryInterval = setInterval(() => {
219
- this.recoverStalled(this.config.processingTimeout).catch(error => {
220
- logger.error('[RedisQueueBatchConsumer] Recovery error:', error);
221
- });
222
- }, 10000);
223
- logger.info('[RedisQueueBatchConsumer] Recovery mechanism started');
224
- }
225
- /**
226
- * 停止恢复机制
227
- */
228
- stopRecovery() {
229
- if (this.recoveryInterval) {
230
- clearInterval(this.recoveryInterval);
231
- this.recoveryInterval = null;
232
- logger.info('[RedisQueueBatchConsumer] Recovery mechanism stopped');
233
- }
234
- }
235
- /**
236
- * 启动消费者
237
- */
238
- startConsumer() {
239
- if (this.consumerRunning || !this.redis) {
240
- return;
241
- }
242
- this.consumerRunning = true;
243
- logger.info(`[RedisQueueBatchConsumer] Consumer started with batchSize: ${this.config.batchSize}, concurrency: ${this.config.concurrency}`);
244
- // Lua 脚本: 批量原子化从 pending 取出任务并移到 processing
245
- const popAndMoveBatchScript = `
246
- local pendingQueue = KEYS[1]
247
- local processingQueue = KEYS[2]
248
- local queueKeyPrefix = KEYS[3]
249
- local count = tonumber(ARGV[1])
250
- local currentTime = tonumber(ARGV[2])
251
-
252
- local taskIds = {}
253
- local checkedCount = 0
254
- local maxCheck = count * 3
255
-
256
- while #taskIds < count and checkedCount < maxCheck do
257
- local taskId = redis.call('LPOP', pendingQueue)
258
- if not taskId then
259
- break
260
- end
261
-
262
- checkedCount = checkedCount + 1
263
-
264
- local taskKey = queueKeyPrefix .. ':task:' .. taskId
265
- local taskData = redis.call('GET', taskKey)
266
-
267
- if taskData then
268
- local task = cjson.decode(taskData)
269
- local delayUntil = task.delayUntil
270
-
271
- if not delayUntil or delayUntil <= currentTime then
272
- redis.call('RPUSH', processingQueue, taskId)
273
- table.insert(taskIds, taskId)
274
- else
275
- redis.call('RPUSH', pendingQueue, taskId)
276
- end
277
- end
278
- end
279
-
280
- return taskIds
281
- `;
282
- this.consumerInterval = setInterval(async () => {
283
- try {
284
- // 检查当前是否有可用的并发槽位
285
- const availableSlots = this.config.concurrency - this.processingBatches;
286
- if (availableSlots <= 0) {
287
- return; // 已达到并发限制
288
- }
289
- // 批量取出任务
290
- const taskIds = await this.redis.eval(popAndMoveBatchScript, {
291
- keys: [this.pendingQueue, this.processingQueue, this.queueKey],
292
- arguments: [this.config.batchSize.toString(), Date.now().toString()],
293
- });
294
- if (taskIds.length > 0) {
295
- // 处理这批任务(不等待完成)
296
- this.processBatch(taskIds).catch(error => {
297
- logger.error(`[RedisQueueBatchConsumer] Unhandled error in processBatch:`, error);
298
- });
299
- }
300
- }
301
- catch (error) {
302
- logger.error('[RedisQueueBatchConsumer] Consumer error:', error);
303
- }
304
- }, this.config.consumerInterval);
305
- }
306
- /**
307
- * 停止消费者
308
- */
309
- stopConsumer() {
310
- if (this.consumerInterval) {
311
- clearInterval(this.consumerInterval);
312
- this.consumerInterval = null;
313
- }
314
- this.consumerRunning = false;
315
- logger.info('[RedisQueueBatchConsumer] Consumer stopped');
316
- }
317
- /**
318
- * 获取队列统计信息(O(1) 时间复杂度)
319
- */
320
- async statistics() {
321
- if (!this.redis) {
322
- return { pending: 0, processing: 0, completed: 0, failed: 0 };
323
- }
324
- const [pending, processing, completed, failed] = await Promise.all([
325
- this.redis.lLen(this.pendingQueue),
326
- this.redis.lLen(this.processingQueue),
327
- this.redis.lLen(this.completedQueue),
328
- this.redis.lLen(this.failedQueue),
329
- ]);
330
- return { pending, processing, completed, failed };
331
- }
332
- /**
333
- * 健康检查
334
- */
335
- async health() {
336
- if (!this.redis)
337
- return false;
338
- const result = await catchIt(() => this.redis.ping());
339
- return !result.isError() && result.value === 'PONG';
340
- }
341
- }
@@ -1,26 +0,0 @@
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:batch:${string}`]: TestTaskData;
23
- }
24
- }
25
- export {};
26
- //# sourceMappingURL=redis-queue-batch-consumer.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"redis-queue-batch-consumer.test.d.ts","sourceRoot":"","sources":["../../source/redis-queue/redis-queue-batch-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"}