@guren/server 2.10.0 → 2.11.0
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/dist/DocsViewerServiceProvider-qFCaeiUv.js +77 -0
- package/dist/Hash-CzrwKeDp.js +133 -0
- package/dist/HttpException-BkS3euNG.js +161 -0
- package/dist/Job-BVT813DO.js +441 -0
- package/dist/McpServiceProvider-BoAN-UcD.js +367 -0
- package/dist/MessageSigner-Bd25ZJAV.js +93 -0
- package/dist/Random-DbIJ22KQ.js +191 -0
- package/dist/address-D0Iq-XIH.js +20 -0
- package/dist/auth/index.js +2 -122
- package/dist/auth-C7sVmYgc.js +1954 -0
- package/dist/authorization/index.js +2 -38
- package/dist/authorization-Dbcuc5ZK.js +610 -0
- package/dist/broadcasting/index.js +2 -26
- package/dist/broadcasting-Dw-FhyjN.js +1055 -0
- package/dist/cache/index.js +2 -17
- package/dist/cache/types.d.ts +4 -4
- package/dist/cache-BYnZf2FR.js +812 -0
- package/dist/client-Dd7vLcqp.js +27 -0
- package/dist/console/Output.d.ts +18 -18
- package/dist/encryption/index.js +5 -96
- package/dist/encryption-fOWQaKqX.js +250 -0
- package/dist/endpoint-D-20PiHY.js +46 -0
- package/dist/endpoint-D6GIqOpe.js +31 -0
- package/dist/errors-quJOkkCn.js +81 -0
- package/dist/events/index.js +2 -28
- package/dist/events-aIH_bWRx.js +410 -0
- package/dist/health/index.js +2 -24
- package/dist/health-VWdWXRwh.js +345 -0
- package/dist/hot-disposables-WsTX2ySN.js +281 -0
- package/dist/hot-reload/testing.d.ts +1 -1
- package/dist/http/resources/Resource.d.ts +23 -3
- package/dist/i18n/index.js +2 -30
- package/dist/i18n-mcWi7LCd.js +617 -0
- package/dist/index.js +7515 -7276
- package/dist/lambda/index.js +114 -71
- package/dist/logging/index.js +2 -24
- package/dist/logging-CPaRMuPP.js +518 -0
- package/dist/loopback-guard-D0Kc7-xc.js +224 -0
- package/dist/mail/index.js +2 -27
- package/dist/mail-DfEfSQEr.js +699 -0
- package/dist/mcp/index.js +2 -10
- package/dist/notifications/index.js +2 -33
- package/dist/notifications-BGqmUNZ8.js +759 -0
- package/dist/queue/index.js +3 -42
- package/dist/queue-CXrRK85G.js +948 -0
- package/dist/redis/index.js +672 -642
- package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
- package/dist/runtime/index.js +472 -616
- package/dist/scheduling/index.js +2 -29
- package/dist/scheduling-CPiEdtQd.js +839 -0
- package/dist/storage/index.js +2 -15
- package/dist/storage-tWHMv2H_.js +841 -0
- package/dist/support/expiry.js +69 -12
- package/dist/trim-slashes-ZJ_VsY5s.js +25 -0
- package/dist/vite/index.js +118 -181
- package/dist/vite/plugin.d.ts +1 -1
- package/dist/vite-dev-server-BSJkduhZ.js +131 -0
- package/package.json +6 -5
- package/dist/DocsViewerServiceProvider-RUYDFBMW.js +0 -75
- package/dist/McpServiceProvider-SL7DUZ4G.js +0 -8
- package/dist/chunk-2SC566CD.js +0 -376
- package/dist/chunk-2V3YID4H.js +0 -20
- package/dist/chunk-3KV5X2FL.js +0 -31
- package/dist/chunk-63SKW5PS.js +0 -457
- package/dist/chunk-6J6B5KOB.js +0 -425
- package/dist/chunk-A5JJ7XTH.js +0 -24
- package/dist/chunk-AZOYI43J.js +0 -18
- package/dist/chunk-B5E5VBDI.js +0 -115
- package/dist/chunk-DAQKYKLH.js +0 -182
- package/dist/chunk-DRNPVBAA.js +0 -1002
- package/dist/chunk-EI5GYMAT.js +0 -853
- package/dist/chunk-H3B23O6T.js +0 -271
- package/dist/chunk-HPET6XY5.js +0 -853
- package/dist/chunk-HR2KZ3WL.js +0 -616
- package/dist/chunk-IOTWFHZU.js +0 -558
- package/dist/chunk-K6CUBJX6.js +0 -642
- package/dist/chunk-KTNJG7R7.js +0 -911
- package/dist/chunk-LAJQCSSF.js +0 -355
- package/dist/chunk-LHR6OHI7.js +0 -189
- package/dist/chunk-N7PLD7MB.js +0 -729
- package/dist/chunk-Q2P6YLRR.js +0 -24
- package/dist/chunk-QQKTH5KX.js +0 -114
- package/dist/chunk-SFQP6O52.js +0 -126
- package/dist/chunk-SQR7277M.js +0 -911
- package/dist/chunk-T2FFUU6J.js +0 -484
- package/dist/chunk-TVV5YNEC.js +0 -1842
- package/dist/chunk-UY3AZSYL.js +0 -14
- package/dist/chunk-V4DNC2ER.js +0 -114
- package/dist/chunk-VSA3QY5Q.js +0 -274
- package/dist/chunk-YSOJKAAU.js +0 -427
- package/dist/errors-PUNHAFL2.js +0 -34
|
@@ -0,0 +1,948 @@
|
|
|
1
|
+
import { c as setQueueDriver, r as getJob } from "./Job-BVT813DO.js";
|
|
2
|
+
//#region src/queue/drivers/MemoryDriver.ts
|
|
3
|
+
/**
|
|
4
|
+
* In-memory queue driver for development and testing.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```ts
|
|
8
|
+
* import { MemoryDriver, setQueueDriver } from '@guren/server/queue'
|
|
9
|
+
*
|
|
10
|
+
* const driver = new MemoryDriver()
|
|
11
|
+
* setQueueDriver(driver)
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
var MemoryDriver = class {
|
|
15
|
+
jobs = /* @__PURE__ */ new Map();
|
|
16
|
+
failedJobs = /* @__PURE__ */ new Map();
|
|
17
|
+
/**
|
|
18
|
+
* Push a job onto the queue.
|
|
19
|
+
*/
|
|
20
|
+
async push(job) {
|
|
21
|
+
this.jobs.set(job.id, { ...job });
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Pop the next available job from the queue.
|
|
25
|
+
*/
|
|
26
|
+
async pop(queue) {
|
|
27
|
+
const now = /* @__PURE__ */ new Date();
|
|
28
|
+
for (const [id, job] of this.jobs) if (job.queue === queue && job.availableAt <= now && job.reservedAt === null) {
|
|
29
|
+
job.reservedAt = now;
|
|
30
|
+
return { ...job };
|
|
31
|
+
}
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Release a job back onto the queue.
|
|
36
|
+
*/
|
|
37
|
+
async release(job, delayMs = 0) {
|
|
38
|
+
const existing = this.jobs.get(job.id);
|
|
39
|
+
if (existing) {
|
|
40
|
+
existing.reservedAt = null;
|
|
41
|
+
existing.availableAt = new Date(Date.now() + delayMs);
|
|
42
|
+
existing.attempts = job.attempts;
|
|
43
|
+
if (job.lastError) existing.lastError = job.lastError;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Delete a job from the queue.
|
|
48
|
+
*/
|
|
49
|
+
async delete(jobId) {
|
|
50
|
+
this.jobs.delete(jobId);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Mark a job as failed.
|
|
54
|
+
*/
|
|
55
|
+
async fail(job, error) {
|
|
56
|
+
const failedJob = {
|
|
57
|
+
...job,
|
|
58
|
+
failedAt: /* @__PURE__ */ new Date(),
|
|
59
|
+
error: error.message,
|
|
60
|
+
stack: error.stack
|
|
61
|
+
};
|
|
62
|
+
this.failedJobs.set(job.id, failedJob);
|
|
63
|
+
this.jobs.delete(job.id);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Get the number of jobs in a queue.
|
|
67
|
+
*/
|
|
68
|
+
async size(queue) {
|
|
69
|
+
let count = 0;
|
|
70
|
+
for (const job of this.jobs.values()) if (job.queue === queue && job.reservedAt === null) count++;
|
|
71
|
+
return count;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Get failed jobs.
|
|
75
|
+
*/
|
|
76
|
+
async getFailedJobs(queue) {
|
|
77
|
+
const jobs = [];
|
|
78
|
+
for (const job of this.failedJobs.values()) if (!queue || job.queue === queue) jobs.push({ ...job });
|
|
79
|
+
return jobs.sort((a, b) => b.failedAt.getTime() - a.failedAt.getTime());
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Retry a failed job.
|
|
83
|
+
*/
|
|
84
|
+
async retryFailedJob(jobId) {
|
|
85
|
+
const failedJob = this.failedJobs.get(jobId);
|
|
86
|
+
if (!failedJob) throw new Error(`Failed job not found: ${jobId}`);
|
|
87
|
+
const job = {
|
|
88
|
+
id: failedJob.id,
|
|
89
|
+
name: failedJob.name,
|
|
90
|
+
payload: failedJob.payload,
|
|
91
|
+
queue: failedJob.queue,
|
|
92
|
+
attempts: 0,
|
|
93
|
+
maxAttempts: failedJob.maxAttempts,
|
|
94
|
+
availableAt: /* @__PURE__ */ new Date(),
|
|
95
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
96
|
+
reservedAt: null
|
|
97
|
+
};
|
|
98
|
+
this.jobs.set(job.id, job);
|
|
99
|
+
this.failedJobs.delete(jobId);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Delete a failed job.
|
|
103
|
+
*/
|
|
104
|
+
async deleteFailedJob(jobId) {
|
|
105
|
+
this.failedJobs.delete(jobId);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Clear all jobs (for testing).
|
|
109
|
+
*/
|
|
110
|
+
async clear() {
|
|
111
|
+
this.jobs.clear();
|
|
112
|
+
this.failedJobs.clear();
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Get all pending jobs (for testing/debugging).
|
|
116
|
+
*/
|
|
117
|
+
getPendingJobs(queue) {
|
|
118
|
+
const jobs = [];
|
|
119
|
+
for (const job of this.jobs.values()) if (!queue || job.queue === queue) jobs.push({ ...job });
|
|
120
|
+
return jobs;
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
//#endregion
|
|
124
|
+
//#region src/queue/drivers/SyncDriver.ts
|
|
125
|
+
/**
|
|
126
|
+
* Synchronous queue driver: jobs execute immediately in the dispatching
|
|
127
|
+
* process, no worker required. This is the development default — dispatch
|
|
128
|
+
* semantics stay identical to a real queue, but failures surface right away
|
|
129
|
+
* and nothing needs a second process.
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* ```ts
|
|
133
|
+
* const queue = createQueueManager({
|
|
134
|
+
* default: 'sync',
|
|
135
|
+
* drivers: { sync: () => new SyncDriver() },
|
|
136
|
+
* })
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
var SyncDriver = class {
|
|
140
|
+
failedJobs = /* @__PURE__ */ new Map();
|
|
141
|
+
async push(job) {
|
|
142
|
+
const JobClass = getJob(job.name);
|
|
143
|
+
if (!JobClass) throw new Error(`SyncDriver: job class "${job.name}" is not registered. Call registerJob() with the class whose jobName (or class name) is "${job.name}".`);
|
|
144
|
+
job.attempts += 1;
|
|
145
|
+
try {
|
|
146
|
+
await new JobClass().handle(job.payload);
|
|
147
|
+
} catch (error) {
|
|
148
|
+
await this.fail(job, error instanceof Error ? error : new Error(String(error)));
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
async pop() {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
async release(job) {
|
|
156
|
+
await this.push(job);
|
|
157
|
+
}
|
|
158
|
+
async delete() {}
|
|
159
|
+
async fail(job, error) {
|
|
160
|
+
this.failedJobs.set(job.id, {
|
|
161
|
+
...job,
|
|
162
|
+
failedAt: /* @__PURE__ */ new Date(),
|
|
163
|
+
error: error.message,
|
|
164
|
+
stack: error.stack
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
async size() {
|
|
168
|
+
return 0;
|
|
169
|
+
}
|
|
170
|
+
async getFailedJobs(queue) {
|
|
171
|
+
const failed = [...this.failedJobs.values()];
|
|
172
|
+
return queue ? failed.filter((job) => job.queue === queue) : failed;
|
|
173
|
+
}
|
|
174
|
+
async retryFailedJob(jobId) {
|
|
175
|
+
const failed = this.failedJobs.get(jobId);
|
|
176
|
+
if (!failed) throw new Error(`SyncDriver: failed job "${jobId}" not found.`);
|
|
177
|
+
this.failedJobs.delete(jobId);
|
|
178
|
+
const { failedAt: _failedAt, error: _error, stack: _stack, ...job } = failed;
|
|
179
|
+
await this.push({
|
|
180
|
+
...job,
|
|
181
|
+
reservedAt: null
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
async deleteFailedJob(jobId) {
|
|
185
|
+
this.failedJobs.delete(jobId);
|
|
186
|
+
}
|
|
187
|
+
async clear() {
|
|
188
|
+
this.failedJobs.clear();
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
//#endregion
|
|
192
|
+
//#region src/queue/drivers/RedisDriver.ts
|
|
193
|
+
/**
|
|
194
|
+
* Redis-backed queue driver for production.
|
|
195
|
+
*
|
|
196
|
+
* Uses the following Redis structures:
|
|
197
|
+
* - `{prefix}{queue}:pending` - Sorted Set (score = availableAt timestamp)
|
|
198
|
+
* - `{prefix}{queue}:reserved` - Sorted Set (score = timeout timestamp)
|
|
199
|
+
* - `{prefix}{queue}:failed` - List of failed job IDs
|
|
200
|
+
* - `{prefix}job:{id}` - Hash containing job data
|
|
201
|
+
*
|
|
202
|
+
* @example
|
|
203
|
+
* ```ts
|
|
204
|
+
* import { createRedisClient } from '@guren/server/redis'
|
|
205
|
+
* import { RedisDriver, setQueueDriver } from '@guren/server/queue'
|
|
206
|
+
*
|
|
207
|
+
* const redis = createRedisClient({ url: process.env.REDIS_URL })
|
|
208
|
+
* const driver = new RedisDriver(redis)
|
|
209
|
+
* setQueueDriver(driver)
|
|
210
|
+
* ```
|
|
211
|
+
*/
|
|
212
|
+
var RedisDriver = class {
|
|
213
|
+
redis;
|
|
214
|
+
prefix;
|
|
215
|
+
visibilityTimeout;
|
|
216
|
+
constructor(redis, options = {}) {
|
|
217
|
+
this.redis = redis;
|
|
218
|
+
this.prefix = options.prefix ?? "queue:";
|
|
219
|
+
this.visibilityTimeout = options.visibilityTimeout ?? 6e4;
|
|
220
|
+
}
|
|
221
|
+
pendingKey(queue) {
|
|
222
|
+
return `${this.prefix}${queue}:pending`;
|
|
223
|
+
}
|
|
224
|
+
reservedKey(queue) {
|
|
225
|
+
return `${this.prefix}${queue}:reserved`;
|
|
226
|
+
}
|
|
227
|
+
failedKey(queue) {
|
|
228
|
+
return `${this.prefix}${queue}:failed`;
|
|
229
|
+
}
|
|
230
|
+
jobKey(id) {
|
|
231
|
+
return `${this.prefix}job:${id}`;
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Push a job onto the queue.
|
|
235
|
+
*/
|
|
236
|
+
async push(job) {
|
|
237
|
+
const jobData = {
|
|
238
|
+
id: job.id,
|
|
239
|
+
name: job.name,
|
|
240
|
+
payload: JSON.stringify(job.payload),
|
|
241
|
+
queue: job.queue,
|
|
242
|
+
attempts: String(job.attempts),
|
|
243
|
+
maxAttempts: String(job.maxAttempts),
|
|
244
|
+
availableAt: job.availableAt.toISOString(),
|
|
245
|
+
createdAt: job.createdAt.toISOString()
|
|
246
|
+
};
|
|
247
|
+
const pipeline = this.redis.pipeline();
|
|
248
|
+
pipeline.hset(this.jobKey(job.id), jobData);
|
|
249
|
+
pipeline.zadd(this.pendingKey(job.queue), job.availableAt.getTime(), job.id);
|
|
250
|
+
await pipeline.exec();
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Pop the next available job from the queue.
|
|
254
|
+
*/
|
|
255
|
+
async pop(queue) {
|
|
256
|
+
const now = Date.now();
|
|
257
|
+
await this.releaseTimedOutJobs(queue);
|
|
258
|
+
const jobIds = await this.redis.zrangebyscore(this.pendingKey(queue), "-inf", now, "LIMIT", 0, 1);
|
|
259
|
+
if (jobIds.length === 0) return null;
|
|
260
|
+
const jobId = jobIds[0];
|
|
261
|
+
if (await this.redis.zrem(this.pendingKey(queue), jobId) === 0) return null;
|
|
262
|
+
const timeout = now + this.visibilityTimeout;
|
|
263
|
+
await this.redis.zadd(this.reservedKey(queue), timeout, jobId);
|
|
264
|
+
await this.redis.hset(this.jobKey(jobId), "reservedAt", (/* @__PURE__ */ new Date()).toISOString());
|
|
265
|
+
const jobData = await this.redis.hgetall(this.jobKey(jobId));
|
|
266
|
+
if (!jobData || !jobData.id) {
|
|
267
|
+
await this.redis.zrem(this.reservedKey(queue), jobId);
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
return this.parseJobData(jobData);
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Release jobs that have exceeded visibility timeout.
|
|
274
|
+
*/
|
|
275
|
+
async releaseTimedOutJobs(queue) {
|
|
276
|
+
const now = Date.now();
|
|
277
|
+
const timedOutIds = await this.redis.zrangebyscore(this.reservedKey(queue), "-inf", now);
|
|
278
|
+
for (const jobId of timedOutIds) if (await this.redis.zrem(this.reservedKey(queue), jobId) > 0) {
|
|
279
|
+
await this.redis.zadd(this.pendingKey(queue), now, jobId);
|
|
280
|
+
await this.redis.hdel(this.jobKey(jobId), "reservedAt");
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Release a job back onto the queue.
|
|
285
|
+
*/
|
|
286
|
+
async release(job, delayMs = 0) {
|
|
287
|
+
const availableAt = Date.now() + delayMs;
|
|
288
|
+
await this.redis.zrem(this.reservedKey(job.queue), job.id);
|
|
289
|
+
const updates = {
|
|
290
|
+
attempts: String(job.attempts),
|
|
291
|
+
availableAt: new Date(availableAt).toISOString()
|
|
292
|
+
};
|
|
293
|
+
if (job.lastError) updates.lastError = job.lastError;
|
|
294
|
+
await this.redis.hset(this.jobKey(job.id), updates);
|
|
295
|
+
await this.redis.hdel(this.jobKey(job.id), "reservedAt");
|
|
296
|
+
await this.redis.zadd(this.pendingKey(job.queue), availableAt, job.id);
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Delete a job from the queue.
|
|
300
|
+
*/
|
|
301
|
+
async delete(jobId) {
|
|
302
|
+
const jobData = await this.redis.hgetall(this.jobKey(jobId));
|
|
303
|
+
if (jobData && jobData.queue) {
|
|
304
|
+
const pipeline = this.redis.pipeline();
|
|
305
|
+
pipeline.zrem(this.pendingKey(jobData.queue), jobId);
|
|
306
|
+
pipeline.zrem(this.reservedKey(jobData.queue), jobId);
|
|
307
|
+
pipeline.del(this.jobKey(jobId));
|
|
308
|
+
await pipeline.exec();
|
|
309
|
+
} else await this.redis.del(this.jobKey(jobId));
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Mark a job as failed.
|
|
313
|
+
*/
|
|
314
|
+
async fail(job, error) {
|
|
315
|
+
const failedData = {
|
|
316
|
+
failedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
317
|
+
error: error.message,
|
|
318
|
+
stack: error.stack ?? ""
|
|
319
|
+
};
|
|
320
|
+
await this.redis.hset(this.jobKey(job.id), failedData);
|
|
321
|
+
const pipeline = this.redis.pipeline();
|
|
322
|
+
pipeline.zrem(this.reservedKey(job.queue), job.id);
|
|
323
|
+
pipeline.lpush(this.failedKey(job.queue), job.id);
|
|
324
|
+
await pipeline.exec();
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Get the number of jobs in a queue.
|
|
328
|
+
*/
|
|
329
|
+
async size(queue) {
|
|
330
|
+
return this.redis.zcard(this.pendingKey(queue));
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Get failed jobs.
|
|
334
|
+
*/
|
|
335
|
+
async getFailedJobs(queue) {
|
|
336
|
+
const jobs = [];
|
|
337
|
+
if (queue) jobs.push(...await this.getFailedJobsForQueue(queue));
|
|
338
|
+
else {
|
|
339
|
+
const pattern = `${this.prefix}*:failed`;
|
|
340
|
+
let cursor = "0";
|
|
341
|
+
const queueKeys = [];
|
|
342
|
+
do {
|
|
343
|
+
const [newCursor, keys] = await this.redis.scan(cursor, "MATCH", pattern, "COUNT", 100);
|
|
344
|
+
cursor = newCursor;
|
|
345
|
+
queueKeys.push(...keys);
|
|
346
|
+
} while (cursor !== "0");
|
|
347
|
+
for (const key of queueKeys) {
|
|
348
|
+
const queueName = key.replace(this.prefix, "").replace(":failed", "");
|
|
349
|
+
jobs.push(...await this.getFailedJobsForQueue(queueName));
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return jobs.sort((a, b) => b.failedAt.getTime() - a.failedAt.getTime());
|
|
353
|
+
}
|
|
354
|
+
async getFailedJobsForQueue(queue) {
|
|
355
|
+
const jobIds = await this.redis.lrange(this.failedKey(queue), 0, -1);
|
|
356
|
+
const jobs = [];
|
|
357
|
+
for (const jobId of jobIds) {
|
|
358
|
+
const jobData = await this.redis.hgetall(this.jobKey(jobId));
|
|
359
|
+
if (jobData && jobData.id) {
|
|
360
|
+
const job = this.parseJobData(jobData);
|
|
361
|
+
jobs.push({
|
|
362
|
+
...job,
|
|
363
|
+
failedAt: new Date(jobData.failedAt || Date.now()),
|
|
364
|
+
error: jobData.error || "Unknown error",
|
|
365
|
+
stack: jobData.stack
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return jobs;
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Retry a failed job.
|
|
373
|
+
*/
|
|
374
|
+
async retryFailedJob(jobId) {
|
|
375
|
+
const jobData = await this.redis.hgetall(this.jobKey(jobId));
|
|
376
|
+
if (!jobData || !jobData.queue) throw new Error(`Failed job not found: ${jobId}`);
|
|
377
|
+
const queue = jobData.queue;
|
|
378
|
+
await this.redis.lrem(this.failedKey(queue), 1, jobId);
|
|
379
|
+
const now = /* @__PURE__ */ new Date();
|
|
380
|
+
await this.redis.hset(this.jobKey(jobId), {
|
|
381
|
+
attempts: "0",
|
|
382
|
+
availableAt: now.toISOString(),
|
|
383
|
+
createdAt: now.toISOString()
|
|
384
|
+
});
|
|
385
|
+
await this.redis.hdel(this.jobKey(jobId), "reservedAt", "failedAt", "error", "stack", "lastError");
|
|
386
|
+
await this.redis.zadd(this.pendingKey(queue), now.getTime(), jobId);
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Delete a failed job.
|
|
390
|
+
*/
|
|
391
|
+
async deleteFailedJob(jobId) {
|
|
392
|
+
const jobData = await this.redis.hgetall(this.jobKey(jobId));
|
|
393
|
+
if (jobData && jobData.queue) await this.redis.lrem(this.failedKey(jobData.queue), 1, jobId);
|
|
394
|
+
await this.redis.del(this.jobKey(jobId));
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Clear all jobs (for testing).
|
|
398
|
+
*/
|
|
399
|
+
async clear() {
|
|
400
|
+
const pattern = this.prefix + "*";
|
|
401
|
+
let cursor = "0";
|
|
402
|
+
const keys = [];
|
|
403
|
+
do {
|
|
404
|
+
const [newCursor, foundKeys] = await this.redis.scan(cursor, "MATCH", pattern, "COUNT", 100);
|
|
405
|
+
cursor = newCursor;
|
|
406
|
+
keys.push(...foundKeys);
|
|
407
|
+
} while (cursor !== "0");
|
|
408
|
+
if (keys.length > 0) await this.redis.del(...keys);
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Parse job data from Redis hash.
|
|
412
|
+
*/
|
|
413
|
+
parseJobData(data) {
|
|
414
|
+
return {
|
|
415
|
+
id: data.id,
|
|
416
|
+
name: data.name,
|
|
417
|
+
payload: JSON.parse(data.payload || "{}"),
|
|
418
|
+
queue: data.queue,
|
|
419
|
+
attempts: parseInt(data.attempts || "0", 10),
|
|
420
|
+
maxAttempts: parseInt(data.maxAttempts || "3", 10),
|
|
421
|
+
availableAt: new Date(data.availableAt),
|
|
422
|
+
createdAt: new Date(data.createdAt),
|
|
423
|
+
reservedAt: data.reservedAt ? new Date(data.reservedAt) : null,
|
|
424
|
+
lastError: data.lastError
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
};
|
|
428
|
+
//#endregion
|
|
429
|
+
//#region src/queue/drivers/SqsDriver.ts
|
|
430
|
+
/**
|
|
431
|
+
* Create an SqsAdapter from an @aws-sdk/client-sqs SQSClient.
|
|
432
|
+
*
|
|
433
|
+
* @example
|
|
434
|
+
* ```ts
|
|
435
|
+
* import { SQSClient } from '@aws-sdk/client-sqs'
|
|
436
|
+
* import { createSqsAdapter, SqsDriver } from '@guren/server/queue'
|
|
437
|
+
*
|
|
438
|
+
* const client = new SQSClient({ region: 'ap-northeast-1' })
|
|
439
|
+
* const adapter = createSqsAdapter(client)
|
|
440
|
+
* const driver = new SqsDriver(adapter, { queueUrl: '...' })
|
|
441
|
+
* ```
|
|
442
|
+
*/
|
|
443
|
+
function createSqsAdapter(client) {
|
|
444
|
+
return {
|
|
445
|
+
async sendMessage(params) {
|
|
446
|
+
const { SendMessageCommand } = await importSqs();
|
|
447
|
+
const input = {
|
|
448
|
+
QueueUrl: params.queueUrl,
|
|
449
|
+
MessageBody: params.messageBody,
|
|
450
|
+
DelaySeconds: params.delaySeconds
|
|
451
|
+
};
|
|
452
|
+
if (params.messageGroupId) {
|
|
453
|
+
input.MessageGroupId = params.messageGroupId;
|
|
454
|
+
input.MessageDeduplicationId = params.messageDeduplicationId;
|
|
455
|
+
}
|
|
456
|
+
await client.send(new SendMessageCommand(input));
|
|
457
|
+
},
|
|
458
|
+
async receiveMessage(params) {
|
|
459
|
+
const { ReceiveMessageCommand } = await importSqs();
|
|
460
|
+
const msg = (await client.send(new ReceiveMessageCommand({
|
|
461
|
+
QueueUrl: params.queueUrl,
|
|
462
|
+
MaxNumberOfMessages: 1,
|
|
463
|
+
WaitTimeSeconds: params.waitTimeSeconds ?? 5
|
|
464
|
+
}))).Messages?.[0];
|
|
465
|
+
if (!msg?.Body || !msg.ReceiptHandle) return null;
|
|
466
|
+
return {
|
|
467
|
+
body: msg.Body,
|
|
468
|
+
receiptHandle: msg.ReceiptHandle
|
|
469
|
+
};
|
|
470
|
+
},
|
|
471
|
+
async changeMessageVisibility(params) {
|
|
472
|
+
const { ChangeMessageVisibilityCommand } = await importSqs();
|
|
473
|
+
await client.send(new ChangeMessageVisibilityCommand({
|
|
474
|
+
QueueUrl: params.queueUrl,
|
|
475
|
+
ReceiptHandle: params.receiptHandle,
|
|
476
|
+
VisibilityTimeout: params.visibilityTimeout
|
|
477
|
+
}));
|
|
478
|
+
},
|
|
479
|
+
async getApproximateMessageCount(queueUrl) {
|
|
480
|
+
const { GetQueueAttributesCommand } = await importSqs();
|
|
481
|
+
const result = await client.send(new GetQueueAttributesCommand({
|
|
482
|
+
QueueUrl: queueUrl,
|
|
483
|
+
AttributeNames: ["ApproximateNumberOfMessages"]
|
|
484
|
+
}));
|
|
485
|
+
return parseInt(result.Attributes?.ApproximateNumberOfMessages ?? "0", 10);
|
|
486
|
+
}
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
const SQS_MODULE = "@aws-sdk/client-sqs";
|
|
490
|
+
async function importSqs() {
|
|
491
|
+
try {
|
|
492
|
+
return await import(SQS_MODULE);
|
|
493
|
+
} catch {
|
|
494
|
+
throw new Error(`Missing optional dependency "${SQS_MODULE}". Install @aws-sdk/client-sqs to use the SQS driver or createSqsAdapter.`);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* AWS SQS queue driver for serverless deployments.
|
|
499
|
+
*
|
|
500
|
+
* @example
|
|
501
|
+
* ```ts
|
|
502
|
+
* import { SQSClient } from '@aws-sdk/client-sqs'
|
|
503
|
+
* import { createSqsAdapter, SqsDriver, setQueueDriver } from '@guren/server/queue'
|
|
504
|
+
*
|
|
505
|
+
* const adapter = createSqsAdapter(new SQSClient({ region: 'ap-northeast-1' }))
|
|
506
|
+
* const driver = new SqsDriver(adapter, { queueUrl: process.env.SQS_QUEUE_URL! })
|
|
507
|
+
* setQueueDriver(driver)
|
|
508
|
+
*
|
|
509
|
+
* // Dispatch jobs as usual
|
|
510
|
+
* await SendEmailJob.dispatch({ to: 'user@example.com' })
|
|
511
|
+
* ```
|
|
512
|
+
*/
|
|
513
|
+
var SqsDriver = class {
|
|
514
|
+
adapter;
|
|
515
|
+
options;
|
|
516
|
+
failedJobs = /* @__PURE__ */ new Map();
|
|
517
|
+
receiptHandles = /* @__PURE__ */ new Map();
|
|
518
|
+
constructor(adapter, options) {
|
|
519
|
+
this.adapter = adapter;
|
|
520
|
+
this.options = options;
|
|
521
|
+
}
|
|
522
|
+
async push(job) {
|
|
523
|
+
const delaySeconds = Math.min(900, Math.max(0, Math.floor((job.availableAt.getTime() - Date.now()) / 1e3)));
|
|
524
|
+
await this.adapter.sendMessage({
|
|
525
|
+
queueUrl: this.resolveQueueUrl(job.queue),
|
|
526
|
+
messageBody: JSON.stringify(job),
|
|
527
|
+
delaySeconds,
|
|
528
|
+
messageGroupId: this.options.messageGroupId,
|
|
529
|
+
messageDeduplicationId: this.options.messageGroupId ? job.id : void 0
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
async pop(queue) {
|
|
533
|
+
const result = await this.adapter.receiveMessage({ queueUrl: this.resolveQueueUrl(queue) });
|
|
534
|
+
if (!result) return null;
|
|
535
|
+
const job = deserializeJob(result.body);
|
|
536
|
+
this.receiptHandles.set(job.id, result.receiptHandle);
|
|
537
|
+
job.reservedAt = /* @__PURE__ */ new Date();
|
|
538
|
+
return job;
|
|
539
|
+
}
|
|
540
|
+
async release(job, delayMs = 0) {
|
|
541
|
+
const receiptHandle = this.receiptHandles.get(job.id);
|
|
542
|
+
if (receiptHandle) {
|
|
543
|
+
await this.adapter.changeMessageVisibility({
|
|
544
|
+
queueUrl: this.resolveQueueUrl(job.queue),
|
|
545
|
+
receiptHandle,
|
|
546
|
+
visibilityTimeout: Math.ceil(delayMs / 1e3)
|
|
547
|
+
});
|
|
548
|
+
this.receiptHandles.delete(job.id);
|
|
549
|
+
} else {
|
|
550
|
+
job.reservedAt = null;
|
|
551
|
+
job.availableAt = new Date(Date.now() + delayMs);
|
|
552
|
+
await this.push(job);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
async delete(jobId) {
|
|
556
|
+
this.receiptHandles.delete(jobId);
|
|
557
|
+
}
|
|
558
|
+
async fail(job, error) {
|
|
559
|
+
const failedJob = {
|
|
560
|
+
...job,
|
|
561
|
+
failedAt: /* @__PURE__ */ new Date(),
|
|
562
|
+
error: error.message,
|
|
563
|
+
stack: error.stack
|
|
564
|
+
};
|
|
565
|
+
this.failedJobs.set(job.id, failedJob);
|
|
566
|
+
this.receiptHandles.delete(job.id);
|
|
567
|
+
}
|
|
568
|
+
async size(queue) {
|
|
569
|
+
return this.adapter.getApproximateMessageCount(this.resolveQueueUrl(queue));
|
|
570
|
+
}
|
|
571
|
+
async getFailedJobs(queue) {
|
|
572
|
+
const jobs = [];
|
|
573
|
+
for (const job of this.failedJobs.values()) if (!queue || job.queue === queue) jobs.push({ ...job });
|
|
574
|
+
return jobs.sort((a, b) => b.failedAt.getTime() - a.failedAt.getTime());
|
|
575
|
+
}
|
|
576
|
+
async retryFailedJob(jobId) {
|
|
577
|
+
const failedJob = this.failedJobs.get(jobId);
|
|
578
|
+
if (!failedJob) throw new Error(`Failed job not found: ${jobId}`);
|
|
579
|
+
const job = {
|
|
580
|
+
id: failedJob.id,
|
|
581
|
+
name: failedJob.name,
|
|
582
|
+
payload: failedJob.payload,
|
|
583
|
+
queue: failedJob.queue,
|
|
584
|
+
attempts: 0,
|
|
585
|
+
maxAttempts: failedJob.maxAttempts,
|
|
586
|
+
availableAt: /* @__PURE__ */ new Date(),
|
|
587
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
588
|
+
reservedAt: null
|
|
589
|
+
};
|
|
590
|
+
await this.push(job);
|
|
591
|
+
this.failedJobs.delete(jobId);
|
|
592
|
+
}
|
|
593
|
+
async deleteFailedJob(jobId) {
|
|
594
|
+
this.failedJobs.delete(jobId);
|
|
595
|
+
}
|
|
596
|
+
async clear() {
|
|
597
|
+
this.failedJobs.clear();
|
|
598
|
+
this.receiptHandles.clear();
|
|
599
|
+
}
|
|
600
|
+
resolveQueueUrl(queue) {
|
|
601
|
+
return this.options.queueUrls?.[queue] ?? this.options.queueUrl;
|
|
602
|
+
}
|
|
603
|
+
};
|
|
604
|
+
/**
|
|
605
|
+
* Deserialize a JSON string into a QueuedJob, restoring Date objects.
|
|
606
|
+
*/
|
|
607
|
+
function deserializeJob(body) {
|
|
608
|
+
const raw = JSON.parse(body);
|
|
609
|
+
return {
|
|
610
|
+
...raw,
|
|
611
|
+
availableAt: new Date(raw.availableAt),
|
|
612
|
+
createdAt: new Date(raw.createdAt),
|
|
613
|
+
reservedAt: raw.reservedAt ? new Date(raw.reservedAt) : null
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
//#endregion
|
|
617
|
+
//#region src/queue/Worker.ts
|
|
618
|
+
/**
|
|
619
|
+
* Queue worker that processes jobs.
|
|
620
|
+
*
|
|
621
|
+
* @example
|
|
622
|
+
* ```ts
|
|
623
|
+
* import { Worker, MemoryDriver, setQueueDriver } from '@guren/server/queue'
|
|
624
|
+
*
|
|
625
|
+
* const driver = new MemoryDriver()
|
|
626
|
+
* setQueueDriver(driver)
|
|
627
|
+
*
|
|
628
|
+
* const worker = new Worker(driver, {
|
|
629
|
+
* queues: ['default', 'emails'],
|
|
630
|
+
* sleep: 1000,
|
|
631
|
+
* })
|
|
632
|
+
*
|
|
633
|
+
* // Start processing
|
|
634
|
+
* await worker.start()
|
|
635
|
+
*
|
|
636
|
+
* // Stop gracefully
|
|
637
|
+
* await worker.stop()
|
|
638
|
+
* ```
|
|
639
|
+
*/
|
|
640
|
+
var Worker = class {
|
|
641
|
+
driver;
|
|
642
|
+
options;
|
|
643
|
+
events;
|
|
644
|
+
running = false;
|
|
645
|
+
shouldStop = false;
|
|
646
|
+
processedJobs = 0;
|
|
647
|
+
queues;
|
|
648
|
+
sleep;
|
|
649
|
+
maxJobs;
|
|
650
|
+
timeout;
|
|
651
|
+
stopWhenEmpty;
|
|
652
|
+
currentJob = null;
|
|
653
|
+
constructor(driver, options = {}, events = {}) {
|
|
654
|
+
this.driver = driver;
|
|
655
|
+
this.options = options;
|
|
656
|
+
this.events = events;
|
|
657
|
+
this.queues = options.queues ?? ["default"];
|
|
658
|
+
this.sleep = options.sleep ?? 1e3;
|
|
659
|
+
this.maxJobs = options.maxJobs ?? 0;
|
|
660
|
+
this.timeout = options.timeout ?? 6e4;
|
|
661
|
+
this.stopWhenEmpty = options.stopWhenEmpty ?? false;
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Start the worker.
|
|
665
|
+
*/
|
|
666
|
+
async start() {
|
|
667
|
+
if (this.running) return;
|
|
668
|
+
this.running = true;
|
|
669
|
+
this.shouldStop = false;
|
|
670
|
+
this.processedJobs = 0;
|
|
671
|
+
this.events.workerStarted?.();
|
|
672
|
+
while (!this.shouldStop) {
|
|
673
|
+
if (this.maxJobs > 0 && this.processedJobs >= this.maxJobs) break;
|
|
674
|
+
const job = await this.getNextJob();
|
|
675
|
+
if (job) {
|
|
676
|
+
await this.processJob(job);
|
|
677
|
+
this.processedJobs++;
|
|
678
|
+
} else {
|
|
679
|
+
if (this.stopWhenEmpty) break;
|
|
680
|
+
await this.sleepMs(this.sleep);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
this.running = false;
|
|
684
|
+
this.events.workerStopped?.();
|
|
685
|
+
}
|
|
686
|
+
/**
|
|
687
|
+
* Stop the worker gracefully.
|
|
688
|
+
*/
|
|
689
|
+
async stop() {
|
|
690
|
+
this.shouldStop = true;
|
|
691
|
+
const startWait = Date.now();
|
|
692
|
+
while (this.running && this.currentJob && Date.now() - startWait < this.timeout) await this.sleepMs(100);
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* Check if the worker is running.
|
|
696
|
+
*/
|
|
697
|
+
isRunning() {
|
|
698
|
+
return this.running;
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* Get the number of processed jobs.
|
|
702
|
+
*/
|
|
703
|
+
getProcessedJobsCount() {
|
|
704
|
+
return this.processedJobs;
|
|
705
|
+
}
|
|
706
|
+
/**
|
|
707
|
+
* Get the next available job from the queues.
|
|
708
|
+
*/
|
|
709
|
+
async getNextJob() {
|
|
710
|
+
for (const queue of this.queues) {
|
|
711
|
+
const job = await this.driver.pop(queue);
|
|
712
|
+
if (job) return job;
|
|
713
|
+
}
|
|
714
|
+
return null;
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* Process a single job.
|
|
718
|
+
*/
|
|
719
|
+
async processJob(job) {
|
|
720
|
+
this.currentJob = job;
|
|
721
|
+
job.attempts++;
|
|
722
|
+
const JobClass = getJob(job.name);
|
|
723
|
+
if (!JobClass) {
|
|
724
|
+
console.error(`Job class not found: ${job.name}`);
|
|
725
|
+
await this.driver.fail(job, /* @__PURE__ */ new Error(`Job class not found: ${job.name}`));
|
|
726
|
+
this.currentJob = null;
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
try {
|
|
730
|
+
const instance = new JobClass();
|
|
731
|
+
await this.executeWithTimeout(async () => instance.handle(job.payload), this.timeout);
|
|
732
|
+
await this.driver.delete(job.id);
|
|
733
|
+
this.events.jobProcessed?.(job);
|
|
734
|
+
} catch (error) {
|
|
735
|
+
await this.handleFailedJob(job, error, JobClass);
|
|
736
|
+
} finally {
|
|
737
|
+
this.currentJob = null;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Handle a failed job.
|
|
742
|
+
*/
|
|
743
|
+
async handleFailedJob(job, error, JobClass) {
|
|
744
|
+
const willRetry = job.attempts < job.maxAttempts;
|
|
745
|
+
if (willRetry) {
|
|
746
|
+
const delay = JobClass.calculateRetryDelay(job.attempts);
|
|
747
|
+
job.lastError = error.message;
|
|
748
|
+
await this.driver.release(job, delay);
|
|
749
|
+
} else {
|
|
750
|
+
await this.driver.fail(job, error);
|
|
751
|
+
try {
|
|
752
|
+
const instance = new JobClass();
|
|
753
|
+
if (instance.failed) await instance.failed(job.payload, error);
|
|
754
|
+
} catch (failedError) {
|
|
755
|
+
console.error(`Error in job.failed() handler:`, failedError);
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
console.error(JSON.stringify({
|
|
759
|
+
level: "error",
|
|
760
|
+
msg: `Job failed: ${job.name}`,
|
|
761
|
+
job: job.name,
|
|
762
|
+
queue: job.queue ?? "default",
|
|
763
|
+
attempt: job.attempts,
|
|
764
|
+
maxAttempts: job.maxAttempts,
|
|
765
|
+
willRetry,
|
|
766
|
+
error: error.message
|
|
767
|
+
}));
|
|
768
|
+
this.events.jobFailed?.(job, error, willRetry);
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Execute a function with a timeout.
|
|
772
|
+
*/
|
|
773
|
+
async executeWithTimeout(fn, timeoutMs) {
|
|
774
|
+
return new Promise((resolve, reject) => {
|
|
775
|
+
const timer = setTimeout(() => {
|
|
776
|
+
reject(/* @__PURE__ */ new Error(`Job timed out after ${timeoutMs}ms`));
|
|
777
|
+
}, timeoutMs);
|
|
778
|
+
fn().then((result) => {
|
|
779
|
+
clearTimeout(timer);
|
|
780
|
+
resolve(result);
|
|
781
|
+
}).catch((error) => {
|
|
782
|
+
clearTimeout(timer);
|
|
783
|
+
reject(error);
|
|
784
|
+
});
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* Sleep for a given number of milliseconds.
|
|
789
|
+
*/
|
|
790
|
+
sleepMs(ms) {
|
|
791
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
792
|
+
}
|
|
793
|
+
};
|
|
794
|
+
/**
|
|
795
|
+
* Process a single job (for testing or one-off execution).
|
|
796
|
+
*/
|
|
797
|
+
async function processJob(driver, queue = "default") {
|
|
798
|
+
const worker = new Worker(driver, {
|
|
799
|
+
queues: [queue],
|
|
800
|
+
maxJobs: 1,
|
|
801
|
+
stopWhenEmpty: true
|
|
802
|
+
});
|
|
803
|
+
await worker.start();
|
|
804
|
+
return worker.getProcessedJobsCount() > 0;
|
|
805
|
+
}
|
|
806
|
+
//#endregion
|
|
807
|
+
//#region src/queue/FailedJobReporter.ts
|
|
808
|
+
/**
|
|
809
|
+
* Default handler that writes structured JSON to stderr.
|
|
810
|
+
*/
|
|
811
|
+
function defaultLogHandler(info) {
|
|
812
|
+
console.error(JSON.stringify({
|
|
813
|
+
level: "error",
|
|
814
|
+
msg: `Job failed: ${info.jobName}`,
|
|
815
|
+
job: info.jobName,
|
|
816
|
+
queue: info.queue,
|
|
817
|
+
attempt: info.attempt,
|
|
818
|
+
maxAttempts: info.maxAttempts,
|
|
819
|
+
willRetry: info.willRetry,
|
|
820
|
+
error: info.error.message,
|
|
821
|
+
failedAt: info.failedAt.toISOString()
|
|
822
|
+
}));
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* Configurable reporter for failed queue jobs.
|
|
826
|
+
*
|
|
827
|
+
* Registered by default in QueueServiceProvider to log failures.
|
|
828
|
+
* Can be extended with custom handlers (e.g., Sentry, Slack notifications).
|
|
829
|
+
*
|
|
830
|
+
* @example
|
|
831
|
+
* ```ts
|
|
832
|
+
* const reporter = new FailedJobReporter()
|
|
833
|
+
*
|
|
834
|
+
* // Add a custom handler alongside the default logger
|
|
835
|
+
* reporter.onFailure(async (info) => {
|
|
836
|
+
* await sendToSentry(info.error)
|
|
837
|
+
* })
|
|
838
|
+
* ```
|
|
839
|
+
*/
|
|
840
|
+
var FailedJobReporter = class {
|
|
841
|
+
handlers = [];
|
|
842
|
+
constructor() {
|
|
843
|
+
this.handlers.push(defaultLogHandler);
|
|
844
|
+
}
|
|
845
|
+
/** Add a custom handler for failed jobs. */
|
|
846
|
+
onFailure(handler) {
|
|
847
|
+
this.handlers.push(handler);
|
|
848
|
+
return this;
|
|
849
|
+
}
|
|
850
|
+
/** Report a job failure to all registered handlers. */
|
|
851
|
+
async report(info) {
|
|
852
|
+
for (const handler of this.handlers) try {
|
|
853
|
+
await handler(info);
|
|
854
|
+
} catch {}
|
|
855
|
+
}
|
|
856
|
+
};
|
|
857
|
+
//#endregion
|
|
858
|
+
//#region src/queue/QueueManager.ts
|
|
859
|
+
/**
|
|
860
|
+
* Queue manager for handling multiple queue drivers.
|
|
861
|
+
*
|
|
862
|
+
* @example
|
|
863
|
+
* ```ts
|
|
864
|
+
* import { QueueManager, MemoryDriver, RedisDriver } from '@guren/server/queue'
|
|
865
|
+
* import { createRedisClient } from '@guren/server/redis'
|
|
866
|
+
*
|
|
867
|
+
* const redis = createRedisClient({ url: process.env.REDIS_URL })
|
|
868
|
+
*
|
|
869
|
+
* const queueManager = new QueueManager({
|
|
870
|
+
* default: 'redis',
|
|
871
|
+
* drivers: {
|
|
872
|
+
* memory: () => new MemoryDriver(),
|
|
873
|
+
* redis: () => new RedisDriver(redis),
|
|
874
|
+
* }
|
|
875
|
+
* })
|
|
876
|
+
*
|
|
877
|
+
* // Use the default driver
|
|
878
|
+
* const driver = queueManager.driver()
|
|
879
|
+
*
|
|
880
|
+
* // Use a specific driver
|
|
881
|
+
* const memoryDriver = queueManager.driver('memory')
|
|
882
|
+
* ```
|
|
883
|
+
*/
|
|
884
|
+
var QueueManager = class {
|
|
885
|
+
defaultDriver;
|
|
886
|
+
driverFactories = /* @__PURE__ */ new Map();
|
|
887
|
+
resolvedDrivers = /* @__PURE__ */ new Map();
|
|
888
|
+
constructor(config = {}) {
|
|
889
|
+
this.defaultDriver = config.default ?? "memory";
|
|
890
|
+
if (config.drivers) for (const [name, factory] of Object.entries(config.drivers)) this.driverFactories.set(name, factory);
|
|
891
|
+
}
|
|
892
|
+
/**
|
|
893
|
+
* Get a queue driver by name.
|
|
894
|
+
* Returns the default driver if no name is specified.
|
|
895
|
+
*/
|
|
896
|
+
driver(name) {
|
|
897
|
+
const driverName = name ?? this.defaultDriver;
|
|
898
|
+
const cached = this.resolvedDrivers.get(driverName);
|
|
899
|
+
if (cached) return cached;
|
|
900
|
+
const factory = this.driverFactories.get(driverName);
|
|
901
|
+
if (!factory) throw new Error(`Queue driver not found: ${driverName}`);
|
|
902
|
+
const driver = factory();
|
|
903
|
+
this.resolvedDrivers.set(driverName, driver);
|
|
904
|
+
if (driverName === this.defaultDriver) setQueueDriver(driver);
|
|
905
|
+
return driver;
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* Register a custom driver factory.
|
|
909
|
+
*/
|
|
910
|
+
registerDriver(name, factory) {
|
|
911
|
+
this.driverFactories.set(name, factory);
|
|
912
|
+
this.resolvedDrivers.delete(name);
|
|
913
|
+
}
|
|
914
|
+
/**
|
|
915
|
+
* Check if a driver is registered.
|
|
916
|
+
*/
|
|
917
|
+
hasDriver(name) {
|
|
918
|
+
return this.driverFactories.has(name);
|
|
919
|
+
}
|
|
920
|
+
/**
|
|
921
|
+
* Get the default driver name.
|
|
922
|
+
*/
|
|
923
|
+
getDefaultDriverName() {
|
|
924
|
+
return this.defaultDriver;
|
|
925
|
+
}
|
|
926
|
+
/**
|
|
927
|
+
* Get all registered driver names.
|
|
928
|
+
*/
|
|
929
|
+
getDriverNames() {
|
|
930
|
+
return Array.from(this.driverFactories.keys());
|
|
931
|
+
}
|
|
932
|
+
/**
|
|
933
|
+
* Set the default driver and update global driver.
|
|
934
|
+
*/
|
|
935
|
+
setDefaultDriver(name) {
|
|
936
|
+
if (!this.driverFactories.has(name)) throw new Error(`Queue driver not found: ${name}`);
|
|
937
|
+
const driver = this.driver(name);
|
|
938
|
+
setQueueDriver(driver);
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
/**
|
|
942
|
+
* Create a queue manager with default configuration.
|
|
943
|
+
*/
|
|
944
|
+
function createQueueManager(config) {
|
|
945
|
+
return new QueueManager(config);
|
|
946
|
+
}
|
|
947
|
+
//#endregion
|
|
948
|
+
export { processJob as a, RedisDriver as c, Worker as i, SyncDriver as l, createQueueManager as n, SqsDriver as o, FailedJobReporter as r, createSqsAdapter as s, QueueManager as t, MemoryDriver as u };
|