@taicode/common-server 3.7.5 → 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.
- package/LICENSE +21 -0
- package/package.json +9 -10
- package/output/context/index.d.ts +0 -6
- package/output/context/index.d.ts.map +0 -1
- package/output/context/index.js +0 -14
- package/output/context/index.test.d.ts +0 -2
- package/output/context/index.test.d.ts.map +0 -1
- package/output/context/index.test.js +0 -14
- package/output/index.d.ts +0 -5
- package/output/index.d.ts.map +0 -1
- package/output/index.js +0 -5
- package/output/rate-limiter/index.d.ts +0 -4
- package/output/rate-limiter/index.d.ts.map +0 -1
- package/output/rate-limiter/index.js +0 -3
- package/output/rate-limiter/memory-store.d.ts +0 -12
- package/output/rate-limiter/memory-store.d.ts.map +0 -1
- package/output/rate-limiter/memory-store.js +0 -46
- package/output/rate-limiter/rate-limiter.d.ts +0 -17
- package/output/rate-limiter/rate-limiter.d.ts.map +0 -1
- package/output/rate-limiter/rate-limiter.js +0 -64
- package/output/rate-limiter/types.d.ts +0 -27
- package/output/rate-limiter/types.d.ts.map +0 -1
- package/output/rate-limiter/types.js +0 -1
- package/output/redis-queue/index.d.ts +0 -8
- package/output/redis-queue/index.d.ts.map +0 -1
- package/output/redis-queue/index.js +0 -6
- package/output/redis-queue/redis-queue-batch-consumer.d.ts +0 -97
- package/output/redis-queue/redis-queue-batch-consumer.d.ts.map +0 -1
- package/output/redis-queue/redis-queue-batch-consumer.js +0 -341
- package/output/redis-queue/redis-queue-batch-consumer.test.d.ts +0 -26
- package/output/redis-queue/redis-queue-batch-consumer.test.d.ts.map +0 -1
- package/output/redis-queue/redis-queue-batch-consumer.test.js +0 -341
- package/output/redis-queue/redis-queue-common.d.ts +0 -73
- package/output/redis-queue/redis-queue-common.d.ts.map +0 -1
- package/output/redis-queue/redis-queue-common.js +0 -303
- package/output/redis-queue/redis-queue-common.test.d.ts +0 -19
- package/output/redis-queue/redis-queue-common.test.d.ts.map +0 -1
- package/output/redis-queue/redis-queue-common.test.js +0 -585
- package/output/redis-queue/redis-queue-consumer.d.ts +0 -95
- package/output/redis-queue/redis-queue-consumer.d.ts.map +0 -1
- package/output/redis-queue/redis-queue-consumer.js +0 -327
- package/output/redis-queue/redis-queue-consumer.test.d.ts +0 -26
- package/output/redis-queue/redis-queue-consumer.test.d.ts.map +0 -1
- package/output/redis-queue/redis-queue-consumer.test.js +0 -316
- package/output/redis-queue/redis-queue-provider.d.ts +0 -69
- package/output/redis-queue/redis-queue-provider.d.ts.map +0 -1
- package/output/redis-queue/redis-queue-provider.js +0 -205
- package/output/redis-queue/redis-queue-provider.test.d.ts +0 -28
- package/output/redis-queue/redis-queue-provider.test.d.ts.map +0 -1
- package/output/redis-queue/redis-queue-provider.test.js +0 -149
- package/output/redis-queue/test-helpers.d.ts +0 -112
- package/output/redis-queue/test-helpers.d.ts.map +0 -1
- package/output/redis-queue/test-helpers.js +0 -242
- package/output/redis-queue/test-helpers.test.d.ts +0 -28
- package/output/redis-queue/test-helpers.test.d.ts.map +0 -1
- package/output/redis-queue/test-helpers.test.js +0 -572
- package/output/redis-queue/types.d.ts +0 -146
- package/output/redis-queue/types.d.ts.map +0 -1
- package/output/redis-queue/types.js +0 -1
- package/output/schema/index.d.ts +0 -177
- package/output/schema/index.d.ts.map +0 -1
- package/output/schema/index.js +0 -180
|
@@ -1,303 +0,0 @@
|
|
|
1
|
-
import { createClient } from 'redis';
|
|
2
|
-
import { logger } from '@taicode/common-base';
|
|
3
|
-
/**
|
|
4
|
-
* Redis 队列基础类
|
|
5
|
-
* 封装 Provider 和 Consumer 的公共逻辑
|
|
6
|
-
*/
|
|
7
|
-
export class RedisQueueCommon {
|
|
8
|
-
redis = null;
|
|
9
|
-
isExternalRedis = false; // 是否使用外部传入的 Redis 客户端
|
|
10
|
-
queueKey;
|
|
11
|
-
redisUrl;
|
|
12
|
-
cleanupDelay;
|
|
13
|
-
// 不同状态队列的键名
|
|
14
|
-
failedQueue;
|
|
15
|
-
pendingQueue;
|
|
16
|
-
processingQueue;
|
|
17
|
-
completedQueue;
|
|
18
|
-
constructor(queueKey, config = {}) {
|
|
19
|
-
// 验证必填参数
|
|
20
|
-
if (!config.redisUrl && !config.redisClient) {
|
|
21
|
-
throw new Error('[RedisQueue] Either redisUrl or redisClient is required');
|
|
22
|
-
}
|
|
23
|
-
if (config.redisUrl && config.redisClient) {
|
|
24
|
-
throw new Error('[RedisQueue] Cannot specify both redisUrl and redisClient');
|
|
25
|
-
}
|
|
26
|
-
if (!queueKey) {
|
|
27
|
-
throw new Error('[RedisQueue] queueKey is required');
|
|
28
|
-
}
|
|
29
|
-
if (queueKey.length < 6) {
|
|
30
|
-
throw new Error('[RedisQueue] queueKey must be at least 6 characters long');
|
|
31
|
-
}
|
|
32
|
-
this.redisUrl = config.redisUrl;
|
|
33
|
-
this.queueKey = queueKey;
|
|
34
|
-
this.cleanupDelay = config.cleanupDelay ?? 86400; // 24 hours
|
|
35
|
-
// 初始化不同状态队列的键名
|
|
36
|
-
this.failedQueue = `${queueKey}:failed`;
|
|
37
|
-
this.pendingQueue = `${queueKey}:pending`;
|
|
38
|
-
this.completedQueue = `${queueKey}:completed`;
|
|
39
|
-
this.processingQueue = `${queueKey}:processing`;
|
|
40
|
-
// 使用外部客户端或创建新客户端
|
|
41
|
-
if (config.redisClient) {
|
|
42
|
-
this.redis = config.redisClient;
|
|
43
|
-
this.isExternalRedis = true;
|
|
44
|
-
}
|
|
45
|
-
else {
|
|
46
|
-
this.redis = createClient({ url: this.redisUrl });
|
|
47
|
-
this.isExternalRedis = false;
|
|
48
|
-
// 添加错误处理
|
|
49
|
-
this.redis.on('error', (err) => {
|
|
50
|
-
logger.error(`[${this.getLogPrefix()}] Redis Client Error:`, err);
|
|
51
|
-
});
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* 连接 Redis
|
|
56
|
-
*/
|
|
57
|
-
async connect() {
|
|
58
|
-
if (this.redis && !this.redis.isOpen) {
|
|
59
|
-
await this.redis.connect().catch((error) => {
|
|
60
|
-
logger.error(`[${this.getLogPrefix()}] Failed to connect to Redis:`, error);
|
|
61
|
-
throw error;
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* 断开 Redis 连接
|
|
67
|
-
*/
|
|
68
|
-
disconnect() {
|
|
69
|
-
// 如果是外部传入的客户端,不主动断开连接
|
|
70
|
-
if (this.isExternalRedis) {
|
|
71
|
-
return;
|
|
72
|
-
}
|
|
73
|
-
if (this.redis && this.redis.isOpen) {
|
|
74
|
-
this.redis.disconnect().catch((error) => {
|
|
75
|
-
logger.error(`[${this.getLogPrefix()}] Failed to disconnect:`, error);
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* 获取任务详情
|
|
81
|
-
*/
|
|
82
|
-
async getTask(taskId) {
|
|
83
|
-
if (!this.redis || !this.redis.isOpen)
|
|
84
|
-
return null;
|
|
85
|
-
const taskKey = `${this.queueKey}:task:${taskId}`;
|
|
86
|
-
const taskData = await this.redis.get(taskKey);
|
|
87
|
-
if (!taskData)
|
|
88
|
-
return null;
|
|
89
|
-
return JSON.parse(taskData);
|
|
90
|
-
}
|
|
91
|
-
/**
|
|
92
|
-
* 根据状态获取对应的队列键
|
|
93
|
-
*/
|
|
94
|
-
getQueueByStatus(status) {
|
|
95
|
-
switch (status) {
|
|
96
|
-
case 'pending': return this.pendingQueue;
|
|
97
|
-
case 'processing': return this.processingQueue;
|
|
98
|
-
case 'completed': return this.completedQueue;
|
|
99
|
-
case 'failed': return this.failedQueue;
|
|
100
|
-
default: return this.pendingQueue;
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
/**
|
|
104
|
-
* 更新任务状态并移动到对应队列(原子操作)
|
|
105
|
-
*/
|
|
106
|
-
async applyStatus(taskId, oldStatus, newStatus) {
|
|
107
|
-
if (!this.redis || !this.redis.isOpen)
|
|
108
|
-
return;
|
|
109
|
-
const task = await this.getTask(taskId);
|
|
110
|
-
if (!task)
|
|
111
|
-
return;
|
|
112
|
-
task.status = newStatus;
|
|
113
|
-
const taskKey = `${this.queueKey}:task:${taskId}`;
|
|
114
|
-
const oldQueue = this.getQueueByStatus(oldStatus);
|
|
115
|
-
const newQueue = this.getQueueByStatus(newStatus);
|
|
116
|
-
if (oldQueue !== newQueue) {
|
|
117
|
-
// 使用 Lua 脚本确保原子性:更新任务 + 移动队列
|
|
118
|
-
const script = `
|
|
119
|
-
local taskKey = KEYS[1]
|
|
120
|
-
local oldQueue = KEYS[2]
|
|
121
|
-
local newQueue = KEYS[3]
|
|
122
|
-
local ttl = tonumber(ARGV[1])
|
|
123
|
-
local taskData = ARGV[2]
|
|
124
|
-
local taskId = ARGV[3]
|
|
125
|
-
|
|
126
|
-
redis.call('SETEX', taskKey, ttl, taskData)
|
|
127
|
-
redis.call('LREM', oldQueue, 0, taskId)
|
|
128
|
-
redis.call('RPUSH', newQueue, taskId)
|
|
129
|
-
return 1
|
|
130
|
-
`;
|
|
131
|
-
await this.redis.eval(script, {
|
|
132
|
-
keys: [taskKey, oldQueue, newQueue],
|
|
133
|
-
arguments: [this.cleanupDelay.toString(), JSON.stringify(task), taskId],
|
|
134
|
-
});
|
|
135
|
-
}
|
|
136
|
-
else {
|
|
137
|
-
// 只更新任务数据
|
|
138
|
-
await this.redis.setEx(taskKey, this.cleanupDelay, JSON.stringify(task));
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
/**
|
|
142
|
-
* 批量更新任务状态(使用 Lua 脚本保证原子性)
|
|
143
|
-
* 注意: 此方法会在 Lua 脚本中读取任务数据,不需要提前获取
|
|
144
|
-
*/
|
|
145
|
-
async applyStatusBatch(taskIds, oldStatus, newStatus) {
|
|
146
|
-
if (!this.redis || !this.redis.isOpen || taskIds.length === 0)
|
|
147
|
-
return 0;
|
|
148
|
-
const oldQueue = this.getQueueByStatus(oldStatus);
|
|
149
|
-
const newQueue = this.getQueueByStatus(newStatus);
|
|
150
|
-
// 使用 Lua 脚本批量更新状态并移动队列
|
|
151
|
-
const batchUpdateScript = `
|
|
152
|
-
local oldQueue = KEYS[1]
|
|
153
|
-
local newQueue = KEYS[2]
|
|
154
|
-
local queueKeyPrefix = ARGV[1]
|
|
155
|
-
local ttl = tonumber(ARGV[2])
|
|
156
|
-
local newStatus = ARGV[3]
|
|
157
|
-
local updatedCount = 0
|
|
158
|
-
|
|
159
|
-
-- ARGV[4], ARGV[5], ARGV[6]... 是 taskId
|
|
160
|
-
for i = 4, #ARGV do
|
|
161
|
-
local taskId = ARGV[i]
|
|
162
|
-
local taskKey = queueKeyPrefix .. ':task:' .. taskId
|
|
163
|
-
local existingData = redis.call('GET', taskKey)
|
|
164
|
-
|
|
165
|
-
if existingData then
|
|
166
|
-
-- 读取现有任务并更新状态
|
|
167
|
-
local task = cjson.decode(existingData)
|
|
168
|
-
task.status = newStatus
|
|
169
|
-
redis.call('SETEX', taskKey, ttl, cjson.encode(task))
|
|
170
|
-
|
|
171
|
-
-- 如果队列不同,移动任务
|
|
172
|
-
if oldQueue ~= newQueue then
|
|
173
|
-
redis.call('LREM', oldQueue, 0, taskId)
|
|
174
|
-
redis.call('RPUSH', newQueue, taskId)
|
|
175
|
-
end
|
|
176
|
-
|
|
177
|
-
updatedCount = updatedCount + 1
|
|
178
|
-
end
|
|
179
|
-
end
|
|
180
|
-
|
|
181
|
-
return updatedCount
|
|
182
|
-
`;
|
|
183
|
-
const result = await this.redis.eval(batchUpdateScript, {
|
|
184
|
-
keys: [oldQueue, newQueue],
|
|
185
|
-
arguments: [
|
|
186
|
-
this.queueKey,
|
|
187
|
-
this.cleanupDelay.toString(),
|
|
188
|
-
newStatus,
|
|
189
|
-
...taskIds,
|
|
190
|
-
],
|
|
191
|
-
});
|
|
192
|
-
return result;
|
|
193
|
-
}
|
|
194
|
-
/**
|
|
195
|
-
* 获取队列统计信息(O(1) 时间复杂度)
|
|
196
|
-
*/
|
|
197
|
-
async statistics() {
|
|
198
|
-
if (!this.redis || !this.redis.isOpen) {
|
|
199
|
-
return { pending: 0, processing: 0, completed: 0, failed: 0 };
|
|
200
|
-
}
|
|
201
|
-
const [pending, processing, completed, failed] = await Promise.all([
|
|
202
|
-
this.redis.lLen(this.pendingQueue),
|
|
203
|
-
this.redis.lLen(this.processingQueue),
|
|
204
|
-
this.redis.lLen(this.completedQueue),
|
|
205
|
-
this.redis.lLen(this.failedQueue),
|
|
206
|
-
]);
|
|
207
|
-
return { pending, processing, completed, failed };
|
|
208
|
-
}
|
|
209
|
-
/**
|
|
210
|
-
* 健康检查
|
|
211
|
-
*/
|
|
212
|
-
async health() {
|
|
213
|
-
if (!this.redis || !this.redis.isOpen)
|
|
214
|
-
return false;
|
|
215
|
-
try {
|
|
216
|
-
await this.redis.ping();
|
|
217
|
-
return true;
|
|
218
|
-
}
|
|
219
|
-
catch {
|
|
220
|
-
return false;
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
/**
|
|
224
|
-
* 恢复超时的任务
|
|
225
|
-
* 检查 processing 队列中的任务,将超时的任务直接标记为失败
|
|
226
|
-
* 使用 Lua 脚本批量处理以提高性能和原子性
|
|
227
|
-
*
|
|
228
|
-
* @param processingTimeout 处理超时时间(毫秒)
|
|
229
|
-
* @returns 恢复的任务统计 {timeoutFailed: number, cleaned: number}
|
|
230
|
-
*/
|
|
231
|
-
async recoverStalled(processingTimeout) {
|
|
232
|
-
if (!this.redis || !this.redis.isOpen) {
|
|
233
|
-
return { timeoutFailed: 0, cleaned: 0 };
|
|
234
|
-
}
|
|
235
|
-
try {
|
|
236
|
-
const processingTaskIds = await this.redis.lRange(this.processingQueue, 0, -1);
|
|
237
|
-
if (processingTaskIds.length === 0) {
|
|
238
|
-
return { timeoutFailed: 0, cleaned: 0 };
|
|
239
|
-
}
|
|
240
|
-
// 使用 Lua 脚本批量恢复超时任务
|
|
241
|
-
const batchRecoveryScript = `
|
|
242
|
-
local processingQueue = KEYS[1]
|
|
243
|
-
local pendingQueue = KEYS[2]
|
|
244
|
-
local failedQueue = KEYS[3]
|
|
245
|
-
local queueKeyPrefix = ARGV[1]
|
|
246
|
-
local ttl = tonumber(ARGV[2])
|
|
247
|
-
local processingTimeout = tonumber(ARGV[3])
|
|
248
|
-
local now = tonumber(ARGV[4])
|
|
249
|
-
|
|
250
|
-
local retryCount = 0
|
|
251
|
-
local failedCount = 0
|
|
252
|
-
local cleanupCount = 0
|
|
253
|
-
|
|
254
|
-
-- ARGV[5], ARGV[6], ARGV[7]... 是 taskId
|
|
255
|
-
for i = 5, #ARGV do
|
|
256
|
-
local taskId = ARGV[i]
|
|
257
|
-
local taskKey = queueKeyPrefix .. ':task:' .. taskId
|
|
258
|
-
local taskData = redis.call('GET', taskKey)
|
|
259
|
-
|
|
260
|
-
if not taskData then
|
|
261
|
-
-- 任务不存在,从队列中清理
|
|
262
|
-
redis.call('LREM', processingQueue, 0, taskId)
|
|
263
|
-
cleanupCount = cleanupCount + 1
|
|
264
|
-
else
|
|
265
|
-
local task = cjson.decode(taskData)
|
|
266
|
-
local processingTime = now - (task.processingStartTime or now)
|
|
267
|
-
|
|
268
|
-
-- 检查是否超时
|
|
269
|
-
if processingTime > processingTimeout then
|
|
270
|
-
-- 超时直接标记为失败
|
|
271
|
-
task.status = 'failed'
|
|
272
|
-
task.processingStartTime = nil
|
|
273
|
-
|
|
274
|
-
redis.call('SETEX', taskKey, ttl, cjson.encode(task))
|
|
275
|
-
redis.call('LREM', processingQueue, 0, taskId)
|
|
276
|
-
redis.call('RPUSH', failedQueue, taskId)
|
|
277
|
-
failedCount = failedCount + 1
|
|
278
|
-
end
|
|
279
|
-
end
|
|
280
|
-
end
|
|
281
|
-
|
|
282
|
-
return {retryCount, failedCount, cleanupCount}
|
|
283
|
-
`;
|
|
284
|
-
const result = await this.redis.eval(batchRecoveryScript, {
|
|
285
|
-
keys: [this.processingQueue, this.pendingQueue, this.failedQueue],
|
|
286
|
-
arguments: [
|
|
287
|
-
this.queueKey,
|
|
288
|
-
this.cleanupDelay.toString(),
|
|
289
|
-
processingTimeout.toString(),
|
|
290
|
-
Date.now().toString(),
|
|
291
|
-
...processingTaskIds,
|
|
292
|
-
],
|
|
293
|
-
});
|
|
294
|
-
const [, failedCount, cleanupCount] = result;
|
|
295
|
-
return { timeoutFailed: failedCount, cleaned: cleanupCount };
|
|
296
|
-
}
|
|
297
|
-
catch (error) {
|
|
298
|
-
const logPrefix = this.getLogPrefix();
|
|
299
|
-
logger.error(`[${logPrefix}] Failed to recover stalled tasks:`, error);
|
|
300
|
-
return { timeoutFailed: 0, cleaned: 0 };
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
}
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
declare module './types.js' {
|
|
2
|
-
interface RedisQueueRegistry {
|
|
3
|
-
'test-queue': Record<string, any>;
|
|
4
|
-
'test-queue-error': Record<string, any>;
|
|
5
|
-
'short': Record<string, any>;
|
|
6
|
-
'valid-key': Record<string, any>;
|
|
7
|
-
'test-default': Record<string, any>;
|
|
8
|
-
'test-custom': Record<string, any>;
|
|
9
|
-
'': Record<string, any>;
|
|
10
|
-
'my-queue': Record<string, any>;
|
|
11
|
-
'test-error': Record<string, any>;
|
|
12
|
-
'test-bad': Record<string, any>;
|
|
13
|
-
'queue-one': Record<string, any>;
|
|
14
|
-
'queue-two': Record<string, any>;
|
|
15
|
-
[key: `test:reconnect:${number}`]: Record<string, any>;
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
export {};
|
|
19
|
-
//# sourceMappingURL=redis-queue-common.test.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"redis-queue-common.test.d.ts","sourceRoot":"","sources":["../../source/redis-queue/redis-queue-common.test.ts"],"names":[],"mappings":"AAOA,OAAO,QAAQ,YAAY,CAAC;IAC1B,UAAU,kBAAkB;QAC1B,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;QACjC,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;QACvC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;QAC5B,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;QAChC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;QACnC,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;QAClC,EAAE,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;QACvB,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;QAC/B,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;QACjC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;QAC/B,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;QAChC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;QAChC,CAAC,GAAG,EAAE,kBAAkB,MAAM,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;KACvD;CACF"}
|