queue-jobs-worker 1.0.5 → 2.0.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.
Files changed (64) hide show
  1. package/README.md +754 -572
  2. package/dist/index.d.ts +546 -29
  3. package/dist/index.js +1268 -2448
  4. package/dist/scripts/claim-job.lua +117 -0
  5. package/dist/scripts/clear-queue.lua +42 -0
  6. package/dist/scripts/list-jobs.lua +50 -0
  7. package/dist/scripts/remove-job.lua +41 -0
  8. package/dist/scripts/save-job.lua +52 -0
  9. package/dist/scripts/update-job.lua +183 -0
  10. package/package.json +91 -110
  11. package/CHANGELOG.md +0 -133
  12. package/LICENSE +0 -21
  13. package/assets/queue-jobs-worker-demo.gif +0 -0
  14. package/assets/queue-jobs-worker-github.png +0 -0
  15. package/dist/core/backoff.d.ts +0 -24
  16. package/dist/core/backoff.d.ts.map +0 -1
  17. package/dist/core/client.d.ts +0 -95
  18. package/dist/core/client.d.ts.map +0 -1
  19. package/dist/core/id.d.ts +0 -9
  20. package/dist/core/id.d.ts.map +0 -1
  21. package/dist/core/index.d.ts +0 -7
  22. package/dist/core/index.d.ts.map +0 -1
  23. package/dist/core/job.d.ts +0 -75
  24. package/dist/core/job.d.ts.map +0 -1
  25. package/dist/core/queue.d.ts +0 -72
  26. package/dist/core/queue.d.ts.map +0 -1
  27. package/dist/core/worker.d.ts +0 -65
  28. package/dist/core/worker.d.ts.map +0 -1
  29. package/dist/events/emitter.d.ts +0 -24
  30. package/dist/events/emitter.d.ts.map +0 -1
  31. package/dist/index.cjs +0 -2578
  32. package/dist/index.cjs.map +0 -1
  33. package/dist/index.d.ts.map +0 -1
  34. package/dist/index.js.map +0 -1
  35. package/dist/lib/scripts/claim.lua +0 -27
  36. package/dist/lib/scripts/index.d.ts +0 -5
  37. package/dist/lib/scripts/index.d.ts.map +0 -1
  38. package/dist/lib/scripts/rate-limit.lua +0 -36
  39. package/dist/lib/scripts/recover-stalled.lua +0 -40
  40. package/dist/lib/scripts/renew-lock.lua +0 -16
  41. package/dist/storage/in-memory.adapter.d.ts +0 -33
  42. package/dist/storage/in-memory.adapter.d.ts.map +0 -1
  43. package/dist/storage/index.d.ts +0 -5
  44. package/dist/storage/index.d.ts.map +0 -1
  45. package/dist/storage/mysql.adapter.d.ts +0 -38
  46. package/dist/storage/mysql.adapter.d.ts.map +0 -1
  47. package/dist/storage/postgres.adapter.d.ts +0 -38
  48. package/dist/storage/postgres.adapter.d.ts.map +0 -1
  49. package/dist/storage/redis.adapter.d.ts +0 -45
  50. package/dist/storage/redis.adapter.d.ts.map +0 -1
  51. package/dist/types/client.types.d.ts +0 -41
  52. package/dist/types/client.types.d.ts.map +0 -1
  53. package/dist/types/events.types.d.ts +0 -22
  54. package/dist/types/events.types.d.ts.map +0 -1
  55. package/dist/types/index.d.ts +0 -10
  56. package/dist/types/index.d.ts.map +0 -1
  57. package/dist/types/job.types.d.ts +0 -97
  58. package/dist/types/job.types.d.ts.map +0 -1
  59. package/dist/types/queue.types.d.ts +0 -43
  60. package/dist/types/queue.types.d.ts.map +0 -1
  61. package/dist/types/storage.types.d.ts +0 -138
  62. package/dist/types/storage.types.d.ts.map +0 -1
  63. package/dist/types/worker.types.d.ts +0 -25
  64. package/dist/types/worker.types.d.ts.map +0 -1
package/dist/index.cjs DELETED
@@ -1,2578 +0,0 @@
1
- 'use strict';
2
-
3
- var crypto = require('crypto');
4
- var croner = require('croner');
5
- var events = require('events');
6
-
7
- var __defProp = Object.defineProperty;
8
- var __getOwnPropNames = Object.getOwnPropertyNames;
9
- var __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
- };
12
- var __export = (target, all) => {
13
- for (var name in all)
14
- __defProp(target, name, { get: all[name], enumerable: true });
15
- };
16
-
17
- // src/lib/scripts/claim.lua
18
- var claim_default;
19
- var init_claim = __esm({
20
- "src/lib/scripts/claim.lua"() {
21
- claim_default = "local prefix = ARGV[4]\nlocal now_ms = tonumber(ARGV[3])\n\n-- Promote due delayed jobs into the waiting set.\nlocal due = redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', now_ms)\nfor _, jid in ipairs(due) do\n local pri_raw = redis.call('HGET', prefix .. 'job:' .. jid, 'priority')\n local pri = tonumber(pri_raw) or 0\n redis.call('ZADD', KEYS[1], -pri, jid)\n redis.call('ZREM', KEYS[2], jid)\n redis.call('HSET', prefix .. 'job:' .. jid, 'status', 'waiting')\nend\n\n-- Pop the top-priority job.\nlocal items = redis.call('ZPOPMIN', KEYS[1], 1)\nif #items == 0 then return '' end\nlocal job_id = items[1]\n\n-- Lock it.\nredis.call('SADD', KEYS[3], job_id)\nredis.call('HSET', prefix .. 'job:' .. job_id,\n 'status', 'active',\n 'lockId', ARGV[1],\n 'lockExpiresAt', ARGV[2],\n 'updatedAt', ARGV[2]\n)\nreturn job_id\n";
22
- }
23
- });
24
-
25
- // src/lib/scripts/recover-stalled.lua
26
- var recover_stalled_default;
27
- var init_recover_stalled = __esm({
28
- "src/lib/scripts/recover-stalled.lua"() {
29
- recover_stalled_default = "local job_key = KEYS[1]\nlocal active_set = KEYS[2]\nlocal waiting_zset = KEYS[3]\n\nlocal job_id = ARGV[1]\nlocal expected_exp = ARGV[2]\nlocal expected_lock = ARGV[3]\nlocal recovery_ts = ARGV[4]\nlocal priority_score = tonumber(ARGV[5])\n\n-- Re-read the three guard fields in one atomic HMGET.\nlocal fields = redis.call('HMGET', job_key, 'lockExpiresAt', 'lockId', 'status')\nlocal current_exp = fields[1] or ''\nlocal current_lock = fields[2] or ''\nlocal current_status = fields[3] or ''\n\n-- Guard 1: job must still be active.\n-- If the worker already completed, failed, or moved to DLQ, skip.\nif current_status ~= 'active' then return 0 end\n\n-- Guard 2: lockId must not have changed.\n-- A different worker may have claimed the job after the original lock expired\n-- and before this script runs.\nif current_lock ~= expected_lock then return 0 end\n\n-- Guard 3: lockExpiresAt must be exactly what the caller observed.\n-- If the worker renewed its lock the timestamp will be later than observed;\n-- the CAS mismatch catches that without needing ISO\u2192epoch conversion in Lua.\nif current_exp ~= expected_exp then return 0 end\n\n-- All guards passed \u2014 recover atomically.\nredis.call('HSET', job_key,\n 'status', 'waiting',\n 'lockId', '',\n 'lockExpiresAt', '',\n 'updatedAt', recovery_ts\n)\nredis.call('SREM', active_set, job_id)\nredis.call('ZADD', waiting_zset, priority_score, job_id)\nreturn 1\n";
30
- }
31
- });
32
-
33
- // src/lib/scripts/renew-lock.lua
34
- var renew_lock_default;
35
- var init_renew_lock = __esm({
36
- "src/lib/scripts/renew-lock.lua"() {
37
- renew_lock_default = "local job_key = KEYS[1]\nlocal lock_id = ARGV[1]\nlocal new_exp = ARGV[2]\nlocal now_iso = ARGV[3]\n\nlocal fields = redis.call('HMGET', job_key, 'status', 'lockId', 'lockExpiresAt')\nlocal status = fields[1] or ''\nlocal current_lock = fields[2] or ''\nlocal current_exp = fields[3] or ''\n\nif status ~= 'active' then return 0 end\nif current_lock ~= lock_id then return 0 end\nif current_exp == '' or current_exp <= now_iso then return 0 end\n\nredis.call('HSET', job_key, 'lockExpiresAt', new_exp, 'updatedAt', now_iso)\nreturn 1\n";
38
- }
39
- });
40
-
41
- // src/lib/scripts/rate-limit.lua
42
- var rate_limit_default;
43
- var init_rate_limit = __esm({
44
- "src/lib/scripts/rate-limit.lua"() {
45
- rate_limit_default = `-- RATE_LIMIT_LUA
46
- -- KEYS[1]: rate_count_key ("qjw:rate:{queue}")
47
- -- KEYS[2]: rate_ts_key ("qjw:rate:{queue}:ts")
48
- -- ARGV[1]: max (number)
49
- -- ARGV[2]: windowMs (number)
50
- -- ARGV[3]: nowMs (number)
51
- -- ARGV[4]: ttlSec (number)
52
- --
53
- -- Returns:
54
- -- 1: Allowed
55
- -- 0: Rejected
56
-
57
- local ck = KEYS[1]
58
- local tk = KEYS[2]
59
- local max = tonumber(ARGV[1])
60
- local windowMs = tonumber(ARGV[2])
61
- local nowMs = tonumber(ARGV[3])
62
- local ttlSec = tonumber(ARGV[4])
63
-
64
- local windowStart = redis.call('GET', tk)
65
-
66
- if not windowStart or (nowMs - tonumber(windowStart)) >= windowMs then
67
- redis.call('SET', ck, '1', 'EX', ttlSec)
68
- redis.call('SET', tk, tostring(nowMs), 'EX', ttlSec)
69
- return 1
70
- end
71
-
72
- local current = tonumber(redis.call('GET', ck) or '0')
73
- if current >= max then
74
- return 0
75
- end
76
-
77
- redis.call('INCR', ck)
78
- redis.call('EXPIRE', ck, ttlSec)
79
- redis.call('EXPIRE', tk, ttlSec)
80
- return 1
81
- `;
82
- }
83
- });
84
-
85
- // src/lib/scripts/index.ts
86
- var CLAIM_LUA, RECOVER_STALLED_LUA, RENEW_LOCK_LUA, RATE_LIMIT_LUA;
87
- var init_scripts = __esm({
88
- "src/lib/scripts/index.ts"() {
89
- init_claim();
90
- init_recover_stalled();
91
- init_renew_lock();
92
- init_rate_limit();
93
- CLAIM_LUA = claim_default;
94
- RECOVER_STALLED_LUA = recover_stalled_default;
95
- RENEW_LOCK_LUA = renew_lock_default;
96
- RATE_LIMIT_LUA = rate_limit_default;
97
- }
98
- });
99
-
100
- // src/storage/redis.adapter.ts
101
- var redis_adapter_exports = {};
102
- __export(redis_adapter_exports, {
103
- RedisStorageAdapter: () => exports.RedisStorageAdapter
104
- });
105
- async function loadRedis() {
106
- try {
107
- return await import('redis');
108
- } catch {
109
- throw new Error(
110
- 'RedisStorageAdapter requires the "redis" package (node-redis v4+).\nInstall it: npm install redis'
111
- );
112
- }
113
- }
114
- function jobToHash(job) {
115
- return {
116
- id: job.id,
117
- queue: job.queue,
118
- type: job.type,
119
- payload: JSON.stringify(job.payload),
120
- status: job.status,
121
- attemptsMade: String(job.attemptsMade),
122
- maxAttempts: String(job.maxAttempts),
123
- retryDelay: String(job.retryDelay),
124
- backoff: job.backoff,
125
- timeout: String(job.timeout),
126
- priority: String(job.priority),
127
- runAt: job.runAt,
128
- ...job.cron !== void 0 ? { cron: job.cron } : {},
129
- attempts: JSON.stringify(job.attempts),
130
- lockId: job.lockId ?? "",
131
- lockExpiresAt: job.lockExpiresAt ?? "",
132
- createdAt: job.createdAt,
133
- updatedAt: job.updatedAt,
134
- completedAt: job.completedAt ?? "",
135
- failedAt: job.failedAt ?? ""
136
- };
137
- }
138
- function hashToJob(h) {
139
- const job = {
140
- id: h["id"] ?? "",
141
- queue: h["queue"] ?? "",
142
- type: h["type"] ?? "",
143
- payload: JSON.parse(h["payload"] ?? "null"),
144
- status: h["status"] ?? "waiting",
145
- attemptsMade: Number(h["attemptsMade"] ?? 0),
146
- maxAttempts: Number(h["maxAttempts"] ?? 1),
147
- retryDelay: Number(h["retryDelay"] ?? 1e3),
148
- backoff: h["backoff"] ?? "exponential",
149
- timeout: Number(h["timeout"] ?? 3e4),
150
- priority: Number(h["priority"] ?? 0),
151
- runAt: h["runAt"] ?? (/* @__PURE__ */ new Date()).toISOString(),
152
- attempts: JSON.parse(h["attempts"] ?? "[]"),
153
- lockId: h["lockId"] || null,
154
- lockExpiresAt: h["lockExpiresAt"] || null,
155
- createdAt: h["createdAt"] ?? (/* @__PURE__ */ new Date()).toISOString(),
156
- updatedAt: h["updatedAt"] ?? (/* @__PURE__ */ new Date()).toISOString(),
157
- completedAt: h["completedAt"] || null,
158
- failedAt: h["failedAt"] || null
159
- };
160
- if (h["cron"]) job.cron = h["cron"];
161
- return job;
162
- }
163
- var PREFIX, k; exports.RedisStorageAdapter = void 0;
164
- var init_redis_adapter = __esm({
165
- "src/storage/redis.adapter.ts"() {
166
- init_scripts();
167
- PREFIX = "qjw:";
168
- k = {
169
- job: (id) => `${PREFIX}job:${id}`,
170
- waiting: (q) => `${PREFIX}queue:${q}:waiting`,
171
- delayed: (q) => `${PREFIX}queue:${q}:delayed`,
172
- active: (q) => `${PREFIX}queue:${q}:active`,
173
- completed: (q) => `${PREFIX}queue:${q}:completed`,
174
- dead: (q) => `${PREFIX}queue:${q}:dead`,
175
- rateCount: (q) => `${PREFIX}rate:${q}`,
176
- rateTs: (q) => `${PREFIX}rate:${q}:ts`
177
- };
178
- exports.RedisStorageAdapter = class {
179
- client;
180
- url;
181
- constructor(connectionString) {
182
- this.url = connectionString;
183
- }
184
- // -------------------------------------------------------------------------
185
- // Lifecycle
186
- // -------------------------------------------------------------------------
187
- async initialize() {
188
- const { createClient } = await loadRedis();
189
- this.client = createClient({ url: this.url });
190
- this.client.on("error", () => {
191
- });
192
- await this.client.connect();
193
- const pong = await this.client.ping();
194
- if (pong !== "PONG") {
195
- throw new Error(
196
- "RedisStorageAdapter: PING returned unexpected response. Connection may be unhealthy."
197
- );
198
- }
199
- }
200
- async close() {
201
- if (this.client) {
202
- await this.client.quit();
203
- }
204
- }
205
- // -------------------------------------------------------------------------
206
- // Enqueue
207
- // -------------------------------------------------------------------------
208
- async enqueue(input) {
209
- const now = (/* @__PURE__ */ new Date()).toISOString();
210
- const runAtMs = new Date(input.runAt).getTime();
211
- const isDelayed = runAtMs > Date.now();
212
- const job = {
213
- id: input.id,
214
- queue: input.queue,
215
- type: input.type,
216
- payload: input.payload,
217
- status: isDelayed ? "delayed" : "waiting",
218
- attemptsMade: 0,
219
- maxAttempts: input.maxAttempts,
220
- retryDelay: input.retryDelay,
221
- backoff: input.backoff,
222
- timeout: input.timeout,
223
- priority: input.priority,
224
- runAt: input.runAt,
225
- ...input.cron !== void 0 ? { cron: input.cron } : {},
226
- attempts: [],
227
- lockId: null,
228
- lockExpiresAt: null,
229
- createdAt: now,
230
- updatedAt: now,
231
- completedAt: null,
232
- failedAt: null
233
- };
234
- const key = k.job(input.id);
235
- const exists = await this.client.exists(key);
236
- if (exists) {
237
- const hash = await this.client.hGetAll(key);
238
- return hashToJob(hash);
239
- }
240
- const multi = this.client.multi();
241
- multi.hSet(key, jobToHash(job));
242
- if (isDelayed) {
243
- multi.zAdd(k.delayed(input.queue), { score: runAtMs, value: input.id });
244
- } else {
245
- multi.zAdd(k.waiting(input.queue), { score: -input.priority, value: input.id });
246
- }
247
- await multi.exec();
248
- return job;
249
- }
250
- // -------------------------------------------------------------------------
251
- // Claim (atomic Lua)
252
- // -------------------------------------------------------------------------
253
- async claim(input) {
254
- const { queue, lockId, lockDuration, now } = input;
255
- const nowMs = new Date(now).getTime();
256
- const lockExpiresAt = new Date(nowMs + lockDuration).toISOString();
257
- const jobId = await this.client.eval(CLAIM_LUA, {
258
- keys: [k.waiting(queue), k.delayed(queue), k.active(queue)],
259
- arguments: [lockId, lockExpiresAt, String(nowMs), PREFIX]
260
- });
261
- if (!jobId) return null;
262
- const hash = await this.client.hGetAll(k.job(jobId));
263
- if (!hash || Object.keys(hash).length === 0) return null;
264
- return hashToJob(hash);
265
- }
266
- // -------------------------------------------------------------------------
267
- // Renew lock
268
- // -------------------------------------------------------------------------
269
- async renewLock(jobId, lockId, lockDuration) {
270
- const nowMs = Date.now();
271
- const nowIso = new Date(nowMs).toISOString();
272
- const newExpiresAt = new Date(nowMs + lockDuration).toISOString();
273
- const res = await this.client.eval(RENEW_LOCK_LUA, {
274
- keys: [k.job(jobId)],
275
- arguments: [lockId, newExpiresAt, nowIso]
276
- });
277
- return Number(res) === 1;
278
- }
279
- // -------------------------------------------------------------------------
280
- // Complete
281
- // -------------------------------------------------------------------------
282
- async complete(jobId, lockId) {
283
- const now = (/* @__PURE__ */ new Date()).toISOString();
284
- const hash = await this.client.hGetAll(k.job(jobId));
285
- if (!hash || Object.keys(hash).length === 0) return;
286
- if (lockId !== void 0) {
287
- if (hash["status"] !== "active" || hash["lockId"] !== lockId) return;
288
- }
289
- const queue = hash["queue"] ?? "";
290
- const multi = this.client.multi();
291
- multi.hSet(k.job(jobId), {
292
- status: "completed",
293
- lockId: "",
294
- lockExpiresAt: "",
295
- completedAt: now,
296
- updatedAt: now
297
- });
298
- multi.sRem(k.active(queue), jobId);
299
- multi.sAdd(k.completed(queue), jobId);
300
- await multi.exec();
301
- }
302
- // -------------------------------------------------------------------------
303
- // Requeue
304
- // -------------------------------------------------------------------------
305
- async requeue(input) {
306
- const now = (/* @__PURE__ */ new Date()).toISOString();
307
- const hash = await this.client.hGetAll(k.job(input.jobId));
308
- if (!hash || Object.keys(hash).length === 0) return;
309
- if (input.lockId !== void 0) {
310
- if (hash["status"] !== "active" || hash["lockId"] !== input.lockId) return;
311
- }
312
- const queue = hash["queue"] ?? "";
313
- const attempts = JSON.parse(hash["attempts"] ?? "[]");
314
- attempts.push({
315
- attempt: input.attemptNumber,
316
- startedAt: hash["updatedAt"] ?? now,
317
- finishedAt: now,
318
- error: input.error,
319
- ...input.stack !== void 0 ? { stack: input.stack } : {}
320
- });
321
- const multi = this.client.multi();
322
- multi.hSet(k.job(input.jobId), {
323
- status: "waiting",
324
- attemptsMade: String(input.attemptNumber),
325
- attempts: JSON.stringify(attempts),
326
- runAt: input.runAt,
327
- lockId: "",
328
- lockExpiresAt: "",
329
- updatedAt: now
330
- });
331
- multi.sRem(k.active(queue), input.jobId);
332
- multi.zAdd(k.delayed(queue), {
333
- score: new Date(input.runAt).getTime(),
334
- value: input.jobId
335
- });
336
- await multi.exec();
337
- }
338
- // -------------------------------------------------------------------------
339
- // Move to DLQ
340
- // -------------------------------------------------------------------------
341
- async moveToDlq(input) {
342
- const now = (/* @__PURE__ */ new Date()).toISOString();
343
- const hash = await this.client.hGetAll(k.job(input.jobId));
344
- if (!hash || Object.keys(hash).length === 0) return;
345
- if (input.lockId !== void 0) {
346
- if (hash["status"] !== "active" || hash["lockId"] !== input.lockId) return;
347
- }
348
- const queue = hash["queue"] ?? "";
349
- const attempts = JSON.parse(hash["attempts"] ?? "[]");
350
- attempts.push({
351
- attempt: input.attemptNumber,
352
- startedAt: hash["updatedAt"] ?? now,
353
- finishedAt: now,
354
- error: input.error,
355
- ...input.stack !== void 0 ? { stack: input.stack } : {}
356
- });
357
- const multi = this.client.multi();
358
- multi.hSet(k.job(input.jobId), {
359
- status: "dead",
360
- attemptsMade: String(input.attemptNumber),
361
- attempts: JSON.stringify(attempts),
362
- lockId: "",
363
- lockExpiresAt: "",
364
- failedAt: now,
365
- updatedAt: now
366
- });
367
- multi.sRem(k.active(queue), input.jobId);
368
- multi.sAdd(k.dead(queue), input.jobId);
369
- await multi.exec();
370
- }
371
- // -------------------------------------------------------------------------
372
- // Release lock
373
- // -------------------------------------------------------------------------
374
- async releaseLock(jobId, lockId) {
375
- const hash = await this.client.hGetAll(k.job(jobId));
376
- if (!hash || Object.keys(hash).length === 0) return;
377
- if (lockId !== void 0) {
378
- if (hash["status"] !== "active" || hash["lockId"] !== lockId) return;
379
- }
380
- const now = (/* @__PURE__ */ new Date()).toISOString();
381
- await this.client.hSet(k.job(jobId), {
382
- lockId: "",
383
- lockExpiresAt: now,
384
- updatedAt: now
385
- });
386
- }
387
- // -------------------------------------------------------------------------
388
- // Recover stalled jobs (atomic compare-and-swap per job via Lua)
389
- //
390
- // Previous implementation: two-phase read pipeline → write pipeline.
391
- // Race condition: a worker could complete or renew its lock between the two
392
- // phases, causing recovery to overwrite a legitimately-active job.
393
- //
394
- // Fix (issue #6): for each candidate job the RECOVER_STALLED_LUA script
395
- // re-reads lockExpiresAt, lockId, and status atomically and only applies
396
- // the recovery if all three still match what was observed in the read phase
397
- // (compare-and-swap). If the worker renewed or completed the job in the
398
- // window between the read and the Lua call, the CAS mismatch causes the
399
- // script to return 0 and the job is left untouched.
400
- // -------------------------------------------------------------------------
401
- async recoverStalledJobs(queue, now) {
402
- const nowMs = new Date(now).getTime();
403
- const activeIds = await this.client.sMembers(k.active(queue));
404
- if (activeIds.length === 0) return [];
405
- const fetchPipeline = this.client.multi();
406
- for (const jobId of activeIds) {
407
- fetchPipeline.hmGet(k.job(jobId), ["lockExpiresAt", "lockId", "priority"]);
408
- }
409
- const fetchResults = await fetchPipeline.exec();
410
- const recovered = [];
411
- const evalPromises = [];
412
- for (let i = 0; i < activeIds.length; i++) {
413
- const jobId = activeIds[i];
414
- const fields = fetchResults[i];
415
- if (!fields) continue;
416
- const [lockExpiresAt, lockId, priorityStr] = fields;
417
- if (!lockExpiresAt) continue;
418
- if (new Date(lockExpiresAt).getTime() > nowMs) continue;
419
- const priority = Number(priorityStr ?? "0");
420
- const priorityScore = String(-priority);
421
- const p = this.client.eval(RECOVER_STALLED_LUA, {
422
- keys: [k.job(jobId), k.active(queue), k.waiting(queue)],
423
- arguments: [jobId, lockExpiresAt, lockId ?? "", now, priorityScore]
424
- }).then((result) => {
425
- if (result === 1) recovered.push(jobId);
426
- });
427
- evalPromises.push(p);
428
- }
429
- await Promise.all(evalPromises);
430
- return recovered;
431
- }
432
- // -------------------------------------------------------------------------
433
- // Reads
434
- // -------------------------------------------------------------------------
435
- async getJob(jobId) {
436
- const hash = await this.client.hGetAll(k.job(jobId));
437
- if (!hash || Object.keys(hash).length === 0) return null;
438
- return hashToJob(hash);
439
- }
440
- async getJobs(filter) {
441
- const { queue, status, limit = 100, offset = 0 } = filter;
442
- let ids = [];
443
- if (queue && status) {
444
- switch (status) {
445
- case "waiting":
446
- ids = await this.client.zRange(k.waiting(queue), 0, -1);
447
- break;
448
- case "delayed":
449
- ids = await this.client.zRange(k.delayed(queue), 0, -1);
450
- break;
451
- case "active":
452
- ids = await this.client.sMembers(k.active(queue));
453
- break;
454
- case "completed":
455
- ids = await this.client.sMembers(k.completed(queue));
456
- break;
457
- case "dead":
458
- ids = await this.client.sMembers(k.dead(queue));
459
- break;
460
- default:
461
- ids = [];
462
- }
463
- } else {
464
- for await (const key of this.client.scanIterator({
465
- MATCH: `${PREFIX}job:*`,
466
- COUNT: 500
467
- })) {
468
- const keyStr = Array.isArray(key) ? String(key[0]) : String(key);
469
- ids.push(keyStr.replace(`${PREFIX}job:`, ""));
470
- }
471
- }
472
- const results = [];
473
- const page = ids.slice(offset, offset + limit);
474
- for (const id of page) {
475
- const job = await this.getJob(id);
476
- if (!job) continue;
477
- if (queue && job.queue !== queue) continue;
478
- if (status && job.status !== status) continue;
479
- results.push(job);
480
- }
481
- return results;
482
- }
483
- async getJobCounts(queue) {
484
- const [waiting, delayed, active, completed, dead] = await Promise.all([
485
- this.client.zCard(k.waiting(queue)),
486
- this.client.zCard(k.delayed(queue)),
487
- this.client.sCard(k.active(queue)),
488
- this.client.sCard(k.completed(queue)),
489
- this.client.sCard(k.dead(queue))
490
- ]);
491
- return { waiting, delayed, active, completed, dead };
492
- }
493
- // -------------------------------------------------------------------------
494
- // Rate limiting
495
- // -------------------------------------------------------------------------
496
- async checkAndIncrementRateLimit(queue, max, windowMs, now) {
497
- const nowMs = new Date(now).getTime();
498
- const ck = k.rateCount(queue);
499
- const tk = k.rateTs(queue);
500
- const ttlSec = Math.max(1, Math.ceil(windowMs / 1e3));
501
- const res = await this.client.eval(RATE_LIMIT_LUA, {
502
- keys: [ck, tk],
503
- arguments: [String(max), String(windowMs), String(nowMs), String(ttlSec)]
504
- });
505
- return Number(res) === 1;
506
- }
507
- };
508
- }
509
- });
510
-
511
- // src/storage/postgres.adapter.ts
512
- var postgres_adapter_exports = {};
513
- __export(postgres_adapter_exports, {
514
- PostgreSQLStorageAdapter: () => exports.PostgreSQLStorageAdapter
515
- });
516
- async function loadPg() {
517
- try {
518
- return await import('pg');
519
- } catch {
520
- throw new Error(
521
- 'PostgreSQLStorageAdapter requires the "pg" package (node-postgres).\nInstall it: npm install pg'
522
- );
523
- }
524
- }
525
- function rowToJob(row) {
526
- const job = {
527
- id: row.id,
528
- queue: row.queue,
529
- type: row.type,
530
- payload: row.payload,
531
- status: row.status,
532
- attemptsMade: row.attempts_made,
533
- maxAttempts: row.max_attempts,
534
- retryDelay: row.retry_delay,
535
- backoff: row.backoff,
536
- timeout: row.timeout,
537
- priority: row.priority,
538
- runAt: row.run_at.toISOString(),
539
- attempts: row.attempts,
540
- lockId: row.lock_id,
541
- lockExpiresAt: row.lock_expires_at ? row.lock_expires_at.toISOString() : null,
542
- createdAt: row.created_at.toISOString(),
543
- updatedAt: row.updated_at.toISOString(),
544
- completedAt: row.completed_at ? row.completed_at.toISOString() : null,
545
- failedAt: row.failed_at ? row.failed_at.toISOString() : null
546
- };
547
- if (row.cron) job.cron = row.cron;
548
- return job;
549
- }
550
- var CREATE_JOBS_TABLE, CREATE_RATE_TABLE; exports.PostgreSQLStorageAdapter = void 0;
551
- var init_postgres_adapter = __esm({
552
- "src/storage/postgres.adapter.ts"() {
553
- CREATE_JOBS_TABLE = `
554
- CREATE TABLE IF NOT EXISTS qjw_jobs (
555
- id TEXT NOT NULL PRIMARY KEY,
556
- queue TEXT NOT NULL,
557
- type TEXT NOT NULL,
558
- payload JSONB NOT NULL DEFAULT '{}',
559
- status TEXT NOT NULL DEFAULT 'waiting',
560
- attempts_made INTEGER NOT NULL DEFAULT 0,
561
- max_attempts INTEGER NOT NULL DEFAULT 3,
562
- retry_delay INTEGER NOT NULL DEFAULT 1000,
563
- backoff TEXT NOT NULL DEFAULT 'exponential',
564
- timeout INTEGER NOT NULL DEFAULT 30000,
565
- priority INTEGER NOT NULL DEFAULT 0,
566
- run_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
567
- cron TEXT,
568
- attempts JSONB NOT NULL DEFAULT '[]',
569
- lock_id TEXT,
570
- lock_expires_at TIMESTAMPTZ,
571
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
572
- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
573
- completed_at TIMESTAMPTZ,
574
- failed_at TIMESTAMPTZ
575
- );
576
- CREATE INDEX IF NOT EXISTS qjw_jobs_claim_idx
577
- ON qjw_jobs (queue, status, run_at, priority DESC)
578
- WHERE status IN ('waiting', 'delayed');
579
- `;
580
- CREATE_RATE_TABLE = `
581
- CREATE TABLE IF NOT EXISTS qjw_rate_limits (
582
- queue TEXT NOT NULL PRIMARY KEY,
583
- count INTEGER NOT NULL DEFAULT 0,
584
- window_start BIGINT NOT NULL DEFAULT 0
585
- );
586
- `;
587
- exports.PostgreSQLStorageAdapter = class {
588
- pool;
589
- connectionString;
590
- constructor(connectionString) {
591
- this.connectionString = connectionString;
592
- }
593
- // -------------------------------------------------------------------------
594
- // Lifecycle
595
- // -------------------------------------------------------------------------
596
- async initialize() {
597
- const { Pool } = await loadPg();
598
- this.pool = new Pool({ connectionString: this.connectionString });
599
- const client = await this.pool.connect();
600
- try {
601
- await client.query("SELECT 1");
602
- await client.query(CREATE_JOBS_TABLE);
603
- await client.query(CREATE_RATE_TABLE);
604
- } finally {
605
- client.release();
606
- }
607
- }
608
- async close() {
609
- if (this.pool) {
610
- await this.pool.end();
611
- }
612
- }
613
- // -------------------------------------------------------------------------
614
- // Enqueue
615
- // -------------------------------------------------------------------------
616
- async enqueue(input) {
617
- const res = await this.pool.query(
618
- `INSERT INTO qjw_jobs
619
- (id, queue, type, payload, status, attempts_made, max_attempts,
620
- retry_delay, backoff, timeout, priority, run_at, cron,
621
- attempts, lock_id, lock_expires_at, created_at, updated_at,
622
- completed_at, failed_at)
623
- VALUES ($1,$2,$3,$4,
624
- CASE WHEN $5::timestamptz > NOW() THEN 'delayed' ELSE 'waiting' END,
625
- 0,$6,$7,$8,$9,$10,$5,$11,
626
- '[]'::jsonb, NULL, NULL, NOW(), NOW(), NULL, NULL)
627
- ON CONFLICT (id) DO NOTHING
628
- RETURNING *`,
629
- [
630
- input.id,
631
- input.queue,
632
- input.type,
633
- JSON.stringify(input.payload),
634
- input.runAt,
635
- input.maxAttempts,
636
- input.retryDelay,
637
- input.backoff,
638
- input.timeout,
639
- input.priority,
640
- input.cron ?? null
641
- ]
642
- );
643
- if (res.rows.length > 0) {
644
- return rowToJob(res.rows[0]);
645
- }
646
- const existing = await this.pool.query("SELECT * FROM qjw_jobs WHERE id = $1", [
647
- input.id
648
- ]);
649
- return rowToJob(existing.rows[0]);
650
- }
651
- // -------------------------------------------------------------------------
652
- // Claim (SELECT … FOR UPDATE SKIP LOCKED)
653
- // -------------------------------------------------------------------------
654
- async claim(input) {
655
- const { queue, lockId, lockDuration, now } = input;
656
- const lockExpiresAt = new Date(new Date(now).getTime() + lockDuration).toISOString();
657
- const client = await this.pool.connect();
658
- try {
659
- await client.query("BEGIN");
660
- const res = await client.query(
661
- `SELECT * FROM qjw_jobs
662
- WHERE queue = $1
663
- AND status IN ('waiting', 'delayed')
664
- AND run_at <= $2::timestamptz
665
- AND (lock_expires_at IS NULL OR lock_expires_at <= $2::timestamptz)
666
- ORDER BY priority DESC, run_at ASC, created_at ASC
667
- LIMIT 1
668
- FOR UPDATE SKIP LOCKED`,
669
- [queue, now]
670
- );
671
- if (res.rows.length === 0) {
672
- await client.query("ROLLBACK");
673
- return null;
674
- }
675
- const row = res.rows[0];
676
- await client.query(
677
- `UPDATE qjw_jobs
678
- SET status = 'active', lock_id = $1, lock_expires_at = $2, updated_at = NOW()
679
- WHERE id = $3`,
680
- [lockId, lockExpiresAt, row.id]
681
- );
682
- await client.query("COMMIT");
683
- const updated = await this.pool.query("SELECT * FROM qjw_jobs WHERE id = $1", [
684
- row.id
685
- ]);
686
- return rowToJob(updated.rows[0]);
687
- } catch (err) {
688
- await client.query("ROLLBACK");
689
- throw err;
690
- } finally {
691
- client.release();
692
- }
693
- }
694
- // -------------------------------------------------------------------------
695
- // Renew lock
696
- // -------------------------------------------------------------------------
697
- async renewLock(jobId, lockId, lockDuration) {
698
- const newLockExpiresAt = new Date(Date.now() + lockDuration).toISOString();
699
- const res = await this.pool.query(
700
- `UPDATE qjw_jobs
701
- SET lock_expires_at = $1::timestamptz,
702
- updated_at = NOW()
703
- WHERE id = $2 AND status = 'active' AND lock_id = $3 AND lock_expires_at > NOW()`,
704
- [newLockExpiresAt, jobId, lockId]
705
- );
706
- return (res.rowCount ?? 0) > 0;
707
- }
708
- // -------------------------------------------------------------------------
709
- // Complete
710
- // -------------------------------------------------------------------------
711
- async complete(jobId, lockId) {
712
- if (lockId !== void 0) {
713
- await this.pool.query(
714
- `UPDATE qjw_jobs
715
- SET status = 'completed', lock_id = NULL, lock_expires_at = NULL,
716
- completed_at = NOW(), updated_at = NOW()
717
- WHERE id = $1 AND status = 'active' AND lock_id = $2`,
718
- [jobId, lockId]
719
- );
720
- } else {
721
- await this.pool.query(
722
- `UPDATE qjw_jobs
723
- SET status = 'completed', lock_id = NULL, lock_expires_at = NULL,
724
- completed_at = NOW(), updated_at = NOW()
725
- WHERE id = $1`,
726
- [jobId]
727
- );
728
- }
729
- }
730
- // -------------------------------------------------------------------------
731
- // Requeue
732
- // -------------------------------------------------------------------------
733
- async requeue(input) {
734
- const now = (/* @__PURE__ */ new Date()).toISOString();
735
- const attempt = {
736
- attempt: input.attemptNumber,
737
- startedAt: now,
738
- finishedAt: now,
739
- error: input.error,
740
- ...input.stack !== void 0 ? { stack: input.stack } : {}
741
- };
742
- if (input.lockId !== void 0) {
743
- await this.pool.query(
744
- `UPDATE qjw_jobs
745
- SET status = 'waiting',
746
- attempts_made = $1,
747
- attempts = attempts || $2::jsonb,
748
- run_at = $3::timestamptz,
749
- lock_id = NULL,
750
- lock_expires_at = NULL,
751
- updated_at = NOW()
752
- WHERE id = $4 AND status = 'active' AND lock_id = $5`,
753
- [input.attemptNumber, JSON.stringify([attempt]), input.runAt, input.jobId, input.lockId]
754
- );
755
- } else {
756
- await this.pool.query(
757
- `UPDATE qjw_jobs
758
- SET status = 'waiting',
759
- attempts_made = $1,
760
- attempts = attempts || $2::jsonb,
761
- run_at = $3::timestamptz,
762
- lock_id = NULL,
763
- lock_expires_at = NULL,
764
- updated_at = NOW()
765
- WHERE id = $4`,
766
- [input.attemptNumber, JSON.stringify([attempt]), input.runAt, input.jobId]
767
- );
768
- }
769
- }
770
- // -------------------------------------------------------------------------
771
- // Move to DLQ
772
- // -------------------------------------------------------------------------
773
- async moveToDlq(input) {
774
- const now = (/* @__PURE__ */ new Date()).toISOString();
775
- const attempt = {
776
- attempt: input.attemptNumber,
777
- startedAt: now,
778
- finishedAt: now,
779
- error: input.error,
780
- ...input.stack !== void 0 ? { stack: input.stack } : {}
781
- };
782
- if (input.lockId !== void 0) {
783
- await this.pool.query(
784
- `UPDATE qjw_jobs
785
- SET status = 'dead',
786
- attempts_made = $1,
787
- attempts = attempts || $2::jsonb,
788
- lock_id = NULL,
789
- lock_expires_at = NULL,
790
- failed_at = NOW(),
791
- updated_at = NOW()
792
- WHERE id = $3 AND status = 'active' AND lock_id = $4`,
793
- [input.attemptNumber, JSON.stringify([attempt]), input.jobId, input.lockId]
794
- );
795
- } else {
796
- await this.pool.query(
797
- `UPDATE qjw_jobs
798
- SET status = 'dead',
799
- attempts_made = $1,
800
- attempts = attempts || $2::jsonb,
801
- lock_id = NULL,
802
- lock_expires_at = NULL,
803
- failed_at = NOW(),
804
- updated_at = NOW()
805
- WHERE id = $3`,
806
- [input.attemptNumber, JSON.stringify([attempt]), input.jobId]
807
- );
808
- }
809
- }
810
- // -------------------------------------------------------------------------
811
- // Release lock
812
- // -------------------------------------------------------------------------
813
- async releaseLock(jobId, lockId) {
814
- if (lockId !== void 0) {
815
- await this.pool.query(
816
- `UPDATE qjw_jobs
817
- SET lock_id = NULL, lock_expires_at = NOW(), updated_at = NOW()
818
- WHERE id = $1 AND status = 'active' AND lock_id = $2`,
819
- [jobId, lockId]
820
- );
821
- } else {
822
- await this.pool.query(
823
- `UPDATE qjw_jobs
824
- SET lock_id = NULL, lock_expires_at = NOW(), updated_at = NOW()
825
- WHERE id = $1`,
826
- [jobId]
827
- );
828
- }
829
- }
830
- // -------------------------------------------------------------------------
831
- // Recover stalled jobs
832
- // -------------------------------------------------------------------------
833
- async recoverStalledJobs(queue, now) {
834
- const res = await this.pool.query(
835
- `UPDATE qjw_jobs
836
- SET status = 'waiting', lock_id = NULL, lock_expires_at = NULL, updated_at = NOW()
837
- WHERE queue = $1
838
- AND status = 'active'
839
- AND lock_expires_at <= $2::timestamptz
840
- RETURNING id`,
841
- [queue, now]
842
- );
843
- return res.rows.map((r) => r.id);
844
- }
845
- // -------------------------------------------------------------------------
846
- // Reads
847
- // -------------------------------------------------------------------------
848
- async getJob(jobId) {
849
- const res = await this.pool.query("SELECT * FROM qjw_jobs WHERE id = $1", [jobId]);
850
- if (res.rows.length === 0) return null;
851
- return rowToJob(res.rows[0]);
852
- }
853
- async getJobs(filter) {
854
- const { queue, status, limit = 100, offset = 0 } = filter;
855
- const conditions = [];
856
- const params = [];
857
- let idx = 1;
858
- if (queue !== void 0) {
859
- conditions.push(`queue = $${idx++}`);
860
- params.push(queue);
861
- }
862
- if (status !== void 0) {
863
- conditions.push(`status = $${idx++}`);
864
- params.push(status);
865
- }
866
- const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
867
- params.push(limit, offset);
868
- const res = await this.pool.query(
869
- `SELECT * FROM qjw_jobs ${where}
870
- ORDER BY priority DESC, run_at ASC, created_at ASC
871
- LIMIT $${idx++} OFFSET $${idx}`,
872
- params
873
- );
874
- return res.rows.map((r) => rowToJob(r));
875
- }
876
- async getJobCounts(queue) {
877
- const res = await this.pool.query(
878
- "SELECT status, COUNT(*)::int AS count FROM qjw_jobs WHERE queue = $1 GROUP BY status",
879
- [queue]
880
- );
881
- const counts = {
882
- waiting: 0,
883
- active: 0,
884
- completed: 0,
885
- delayed: 0,
886
- dead: 0
887
- };
888
- for (const row of res.rows) {
889
- if (row.status in counts) {
890
- counts[row.status] = Number(row.count);
891
- }
892
- }
893
- return counts;
894
- }
895
- // -------------------------------------------------------------------------
896
- // Rate limiting
897
- // -------------------------------------------------------------------------
898
- async checkAndIncrementRateLimit(queue, max, windowMs, now) {
899
- const nowMs = new Date(now).getTime();
900
- const client = await this.pool.connect();
901
- try {
902
- await client.query("BEGIN");
903
- await client.query(
904
- `INSERT INTO qjw_rate_limits (queue, count, window_start) VALUES ($1, 0, 0)
905
- ON CONFLICT (queue) DO NOTHING`,
906
- [queue]
907
- );
908
- const res = await client.query(
909
- "SELECT count, window_start FROM qjw_rate_limits WHERE queue = $1 FOR UPDATE",
910
- [queue]
911
- );
912
- const row = res.rows[0];
913
- const windowStart = Number(row?.window_start ?? 0);
914
- const count = Number(row?.count ?? 0);
915
- if (!row || nowMs - windowStart >= windowMs) {
916
- await client.query(
917
- "UPDATE qjw_rate_limits SET count = 1, window_start = $2 WHERE queue = $1",
918
- [queue, nowMs]
919
- );
920
- await client.query("COMMIT");
921
- return true;
922
- }
923
- if (count >= max) {
924
- await client.query("COMMIT");
925
- return false;
926
- }
927
- await client.query("UPDATE qjw_rate_limits SET count = count + 1 WHERE queue = $1", [queue]);
928
- await client.query("COMMIT");
929
- return true;
930
- } catch (err) {
931
- await client.query("ROLLBACK");
932
- throw err;
933
- } finally {
934
- client.release();
935
- }
936
- }
937
- };
938
- }
939
- });
940
-
941
- // src/storage/mysql.adapter.ts
942
- var mysql_adapter_exports = {};
943
- __export(mysql_adapter_exports, {
944
- MySQLStorageAdapter: () => exports.MySQLStorageAdapter
945
- });
946
- async function loadMySQL2() {
947
- try {
948
- return await import('mysql2/promise');
949
- } catch {
950
- throw new Error(
951
- 'MySQLStorageAdapter requires the "mysql2" package.\nInstall it: npm install mysql2'
952
- );
953
- }
954
- }
955
- function rowToJob2(row) {
956
- const payload = typeof row.payload === "string" ? JSON.parse(row.payload) : row.payload;
957
- const attempts = typeof row.attempts === "string" ? JSON.parse(row.attempts) : row.attempts ?? [];
958
- const job = {
959
- id: row.id,
960
- queue: row.queue,
961
- type: row.type,
962
- payload,
963
- status: row.status,
964
- attemptsMade: Number(row.attempts_made),
965
- maxAttempts: Number(row.max_attempts),
966
- retryDelay: Number(row.retry_delay),
967
- backoff: row.backoff,
968
- timeout: Number(row.timeout),
969
- priority: Number(row.priority),
970
- runAt: row.run_at instanceof Date ? row.run_at.toISOString() : String(row.run_at),
971
- attempts,
972
- lockId: row.lock_id,
973
- lockExpiresAt: row.lock_expires_at instanceof Date ? row.lock_expires_at.toISOString() : null,
974
- createdAt: row.created_at instanceof Date ? row.created_at.toISOString() : String(row.created_at),
975
- updatedAt: row.updated_at instanceof Date ? row.updated_at.toISOString() : String(row.updated_at),
976
- completedAt: row.completed_at instanceof Date ? row.completed_at.toISOString() : null,
977
- failedAt: row.failed_at instanceof Date ? row.failed_at.toISOString() : null
978
- };
979
- if (row.cron) job.cron = row.cron;
980
- return job;
981
- }
982
- var CREATE_JOBS_TABLE2, CREATE_RATE_TABLE2; exports.MySQLStorageAdapter = void 0;
983
- var init_mysql_adapter = __esm({
984
- "src/storage/mysql.adapter.ts"() {
985
- CREATE_JOBS_TABLE2 = `
986
- CREATE TABLE IF NOT EXISTS qjw_jobs (
987
- id VARCHAR(36) NOT NULL PRIMARY KEY,
988
- queue VARCHAR(255) NOT NULL,
989
- type VARCHAR(255) NOT NULL,
990
- payload JSON NOT NULL,
991
- status VARCHAR(20) NOT NULL DEFAULT 'waiting',
992
- attempts_made INT NOT NULL DEFAULT 0,
993
- max_attempts INT NOT NULL DEFAULT 3,
994
- retry_delay INT NOT NULL DEFAULT 1000,
995
- backoff VARCHAR(20) NOT NULL DEFAULT 'exponential',
996
- timeout INT NOT NULL DEFAULT 30000,
997
- priority INT NOT NULL DEFAULT 0,
998
- run_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
999
- cron VARCHAR(255),
1000
- attempts JSON NOT NULL,
1001
- lock_id VARCHAR(255),
1002
- lock_expires_at DATETIME(3),
1003
- created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
1004
- updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
1005
- completed_at DATETIME(3),
1006
- failed_at DATETIME(3),
1007
- INDEX qjw_jobs_claim_idx (queue, status, run_at, priority)
1008
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
1009
- `;
1010
- CREATE_RATE_TABLE2 = `
1011
- CREATE TABLE IF NOT EXISTS qjw_rate_limits (
1012
- queue VARCHAR(255) NOT NULL PRIMARY KEY,
1013
- count INT NOT NULL DEFAULT 0,
1014
- window_start BIGINT NOT NULL DEFAULT 0
1015
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
1016
- `;
1017
- exports.MySQLStorageAdapter = class {
1018
- pool;
1019
- connectionString;
1020
- constructor(connectionString) {
1021
- this.connectionString = connectionString;
1022
- }
1023
- // -------------------------------------------------------------------------
1024
- // Lifecycle
1025
- // -------------------------------------------------------------------------
1026
- async initialize() {
1027
- const mysql2 = await loadMySQL2();
1028
- this.pool = mysql2.createPool({
1029
- uri: this.connectionString,
1030
- waitForConnections: true,
1031
- connectionLimit: 10,
1032
- queueLimit: 0
1033
- });
1034
- const conn = await this.pool.getConnection();
1035
- try {
1036
- await conn.query("SELECT 1");
1037
- await conn.query(CREATE_JOBS_TABLE2);
1038
- await conn.query(CREATE_RATE_TABLE2);
1039
- } finally {
1040
- conn.release();
1041
- }
1042
- }
1043
- async close() {
1044
- if (this.pool) {
1045
- await this.pool.end();
1046
- }
1047
- }
1048
- // -------------------------------------------------------------------------
1049
- // Enqueue
1050
- // -------------------------------------------------------------------------
1051
- async enqueue(input) {
1052
- const runAtMs = new Date(input.runAt).getTime();
1053
- const isDelayed = runAtMs > Date.now();
1054
- const status = isDelayed ? "delayed" : "waiting";
1055
- await this.pool.query(
1056
- `INSERT IGNORE INTO qjw_jobs
1057
- (id, queue, type, payload, status, attempts_made, max_attempts,
1058
- retry_delay, backoff, timeout, priority, run_at, cron,
1059
- attempts, lock_id, lock_expires_at, created_at, updated_at,
1060
- completed_at, failed_at)
1061
- VALUES (?,?,?,?,?,0,?,?,?,?,?,?,?,?,NULL,NULL,NOW(3),NOW(3),NULL,NULL)`,
1062
- [
1063
- input.id,
1064
- input.queue,
1065
- input.type,
1066
- JSON.stringify(input.payload),
1067
- status,
1068
- input.maxAttempts,
1069
- input.retryDelay,
1070
- input.backoff,
1071
- input.timeout,
1072
- input.priority,
1073
- input.runAt,
1074
- input.cron ?? null,
1075
- JSON.stringify([])
1076
- ]
1077
- );
1078
- const rows = await this.pool.query("SELECT * FROM qjw_jobs WHERE id = ?", [input.id]);
1079
- const row = rows[0][0];
1080
- return rowToJob2(row);
1081
- }
1082
- // -------------------------------------------------------------------------
1083
- // Claim (transaction + SELECT … FOR UPDATE SKIP LOCKED)
1084
- // -------------------------------------------------------------------------
1085
- async claim(input) {
1086
- const { queue, lockId, lockDuration, now } = input;
1087
- const lockExpiresAt = new Date(new Date(now).getTime() + lockDuration).toISOString().slice(0, 23).replace("T", " ");
1088
- const nowMysql = new Date(now).toISOString().slice(0, 23).replace("T", " ");
1089
- const conn = await this.pool.getConnection();
1090
- try {
1091
- await conn.beginTransaction();
1092
- const [rows] = await conn.query(
1093
- `SELECT * FROM qjw_jobs
1094
- WHERE queue = ?
1095
- AND status IN ('waiting', 'delayed')
1096
- AND run_at <= ?
1097
- AND (lock_expires_at IS NULL OR lock_expires_at <= ?)
1098
- ORDER BY priority DESC, run_at ASC, created_at ASC
1099
- LIMIT 1
1100
- FOR UPDATE SKIP LOCKED`,
1101
- [queue, nowMysql, nowMysql]
1102
- );
1103
- if (!rows || rows.length === 0) {
1104
- await conn.rollback();
1105
- return null;
1106
- }
1107
- const row = rows[0];
1108
- await conn.query(
1109
- `UPDATE qjw_jobs
1110
- SET status = 'active', lock_id = ?, lock_expires_at = ?, updated_at = NOW(3)
1111
- WHERE id = ?`,
1112
- [lockId, lockExpiresAt, row.id]
1113
- );
1114
- await conn.commit();
1115
- const [updated] = await this.pool.query("SELECT * FROM qjw_jobs WHERE id = ?", [
1116
- row.id
1117
- ]);
1118
- return rowToJob2(updated[0]);
1119
- } catch (err) {
1120
- await conn.rollback();
1121
- throw err;
1122
- } finally {
1123
- conn.release();
1124
- }
1125
- }
1126
- // -------------------------------------------------------------------------
1127
- // Renew lock
1128
- // -------------------------------------------------------------------------
1129
- async renewLock(jobId, lockId, lockDuration) {
1130
- const newLockExpiresAt = new Date(Date.now() + lockDuration).toISOString().slice(0, 23).replace("T", " ");
1131
- const [result] = await this.pool.query(
1132
- `UPDATE qjw_jobs
1133
- SET lock_expires_at = ?, updated_at = NOW(3)
1134
- WHERE id = ? AND status = 'active' AND lock_id = ? AND lock_expires_at > NOW(3)`,
1135
- [newLockExpiresAt, jobId, lockId]
1136
- );
1137
- return result.affectedRows > 0;
1138
- }
1139
- // -------------------------------------------------------------------------
1140
- // Complete
1141
- // -------------------------------------------------------------------------
1142
- async complete(jobId, lockId) {
1143
- if (lockId !== void 0) {
1144
- await this.pool.query(
1145
- `UPDATE qjw_jobs
1146
- SET status = 'completed', lock_id = NULL, lock_expires_at = NULL,
1147
- completed_at = NOW(3), updated_at = NOW(3)
1148
- WHERE id = ? AND status = 'active' AND lock_id = ?`,
1149
- [jobId, lockId]
1150
- );
1151
- } else {
1152
- await this.pool.query(
1153
- `UPDATE qjw_jobs
1154
- SET status = 'completed', lock_id = NULL, lock_expires_at = NULL,
1155
- completed_at = NOW(3), updated_at = NOW(3)
1156
- WHERE id = ?`,
1157
- [jobId]
1158
- );
1159
- }
1160
- }
1161
- // -------------------------------------------------------------------------
1162
- // Requeue
1163
- // -------------------------------------------------------------------------
1164
- async requeue(input) {
1165
- const now = (/* @__PURE__ */ new Date()).toISOString();
1166
- const attempt = JSON.stringify({
1167
- attempt: input.attemptNumber,
1168
- startedAt: now,
1169
- finishedAt: now,
1170
- error: input.error,
1171
- ...input.stack !== void 0 ? { stack: input.stack } : {}
1172
- });
1173
- if (input.lockId !== void 0) {
1174
- await this.pool.query(
1175
- `UPDATE qjw_jobs
1176
- SET status = 'waiting',
1177
- attempts_made = attempts_made + 1,
1178
- attempts = JSON_ARRAY_APPEND(attempts, '$', CAST(? AS JSON)),
1179
- run_at = ?,
1180
- lock_id = NULL,
1181
- lock_expires_at = NULL,
1182
- updated_at = NOW(3)
1183
- WHERE id = ? AND status = 'active' AND lock_id = ?`,
1184
- [attempt, input.runAt, input.jobId, input.lockId]
1185
- );
1186
- } else {
1187
- await this.pool.query(
1188
- `UPDATE qjw_jobs
1189
- SET status = 'waiting',
1190
- attempts_made = attempts_made + 1,
1191
- attempts = JSON_ARRAY_APPEND(attempts, '$', CAST(? AS JSON)),
1192
- run_at = ?,
1193
- lock_id = NULL,
1194
- lock_expires_at = NULL,
1195
- updated_at = NOW(3)
1196
- WHERE id = ?`,
1197
- [attempt, input.runAt, input.jobId]
1198
- );
1199
- }
1200
- }
1201
- // -------------------------------------------------------------------------
1202
- // Move to DLQ
1203
- // -------------------------------------------------------------------------
1204
- async moveToDlq(input) {
1205
- const now = (/* @__PURE__ */ new Date()).toISOString();
1206
- const attempt = JSON.stringify({
1207
- attempt: input.attemptNumber,
1208
- startedAt: now,
1209
- finishedAt: now,
1210
- error: input.error,
1211
- ...input.stack !== void 0 ? { stack: input.stack } : {}
1212
- });
1213
- if (input.lockId !== void 0) {
1214
- await this.pool.query(
1215
- `UPDATE qjw_jobs
1216
- SET status = 'dead',
1217
- attempts_made = attempts_made + 1,
1218
- attempts = JSON_ARRAY_APPEND(attempts, '$', CAST(? AS JSON)),
1219
- lock_id = NULL,
1220
- lock_expires_at = NULL,
1221
- failed_at = NOW(3),
1222
- updated_at = NOW(3)
1223
- WHERE id = ? AND status = 'active' AND lock_id = ?`,
1224
- [attempt, input.jobId, input.lockId]
1225
- );
1226
- } else {
1227
- await this.pool.query(
1228
- `UPDATE qjw_jobs
1229
- SET status = 'dead',
1230
- attempts_made = attempts_made + 1,
1231
- attempts = JSON_ARRAY_APPEND(attempts, '$', CAST(? AS JSON)),
1232
- lock_id = NULL,
1233
- lock_expires_at = NULL,
1234
- failed_at = NOW(3),
1235
- updated_at = NOW(3)
1236
- WHERE id = ?`,
1237
- [attempt, input.jobId]
1238
- );
1239
- }
1240
- }
1241
- // -------------------------------------------------------------------------
1242
- // Release lock
1243
- // -------------------------------------------------------------------------
1244
- async releaseLock(jobId, lockId) {
1245
- if (lockId !== void 0) {
1246
- await this.pool.query(
1247
- `UPDATE qjw_jobs
1248
- SET lock_id = NULL, lock_expires_at = NOW(3), updated_at = NOW(3)
1249
- WHERE id = ? AND status = 'active' AND lock_id = ?`,
1250
- [jobId, lockId]
1251
- );
1252
- } else {
1253
- await this.pool.query(
1254
- `UPDATE qjw_jobs
1255
- SET lock_id = NULL, lock_expires_at = NOW(3), updated_at = NOW(3)
1256
- WHERE id = ?`,
1257
- [jobId]
1258
- );
1259
- }
1260
- }
1261
- // -------------------------------------------------------------------------
1262
- // Recover stalled jobs (atomic — SELECT … FOR UPDATE inside transaction)
1263
- // -------------------------------------------------------------------------
1264
- async recoverStalledJobs(queue, now) {
1265
- const nowMysql = new Date(now).toISOString().slice(0, 23).replace("T", " ");
1266
- const conn = await this.pool.getConnection();
1267
- try {
1268
- await conn.beginTransaction();
1269
- const [rows] = await conn.query(
1270
- `SELECT id FROM qjw_jobs
1271
- WHERE queue = ?
1272
- AND status = 'active'
1273
- AND lock_expires_at <= ?
1274
- FOR UPDATE SKIP LOCKED`,
1275
- [queue, nowMysql]
1276
- );
1277
- const ids = rows.map((r) => String(r["id"]));
1278
- if (ids.length > 0) {
1279
- await conn.query(
1280
- `UPDATE qjw_jobs
1281
- SET status = 'waiting', lock_id = NULL, lock_expires_at = NULL, updated_at = NOW(3)
1282
- WHERE id IN (?)`,
1283
- [ids]
1284
- );
1285
- }
1286
- await conn.commit();
1287
- return ids;
1288
- } catch (err) {
1289
- await conn.rollback();
1290
- throw err;
1291
- } finally {
1292
- conn.release();
1293
- }
1294
- }
1295
- // -------------------------------------------------------------------------
1296
- // Reads
1297
- // -------------------------------------------------------------------------
1298
- async getJob(jobId) {
1299
- const [rows] = await this.pool.query("SELECT * FROM qjw_jobs WHERE id = ?", [jobId]);
1300
- const list = rows;
1301
- if (!list || list.length === 0) return null;
1302
- return rowToJob2(list[0]);
1303
- }
1304
- async getJobs(filter) {
1305
- const { queue, status, limit = 100, offset = 0 } = filter;
1306
- const conditions = [];
1307
- const params = [];
1308
- if (queue !== void 0) {
1309
- conditions.push("queue = ?");
1310
- params.push(queue);
1311
- }
1312
- if (status !== void 0) {
1313
- conditions.push("status = ?");
1314
- params.push(status);
1315
- }
1316
- const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1317
- params.push(limit, offset);
1318
- const [rows] = await this.pool.query(
1319
- `SELECT * FROM qjw_jobs ${where}
1320
- ORDER BY priority DESC, run_at ASC, created_at ASC
1321
- LIMIT ? OFFSET ?`,
1322
- params
1323
- );
1324
- return rows.map((r) => rowToJob2(r));
1325
- }
1326
- async getJobCounts(queue) {
1327
- const [rows] = await this.pool.query(
1328
- "SELECT status, COUNT(*) AS count FROM qjw_jobs WHERE queue = ? GROUP BY status",
1329
- [queue]
1330
- );
1331
- const counts = {
1332
- waiting: 0,
1333
- active: 0,
1334
- completed: 0,
1335
- delayed: 0,
1336
- dead: 0
1337
- };
1338
- for (const row of rows) {
1339
- const s = String(row["status"]);
1340
- if (s in counts) counts[s] = Number(row["count"]);
1341
- }
1342
- return counts;
1343
- }
1344
- // -------------------------------------------------------------------------
1345
- // Rate limiting
1346
- // -------------------------------------------------------------------------
1347
- async checkAndIncrementRateLimit(queue, max, windowMs, now) {
1348
- const nowMs = new Date(now).getTime();
1349
- const conn = await this.pool.getConnection();
1350
- try {
1351
- await conn.beginTransaction();
1352
- await conn.query(
1353
- `INSERT INTO qjw_rate_limits (queue, count, window_start) VALUES (?, 0, 0)
1354
- ON DUPLICATE KEY UPDATE queue = queue`,
1355
- [queue]
1356
- );
1357
- const [rows] = await conn.query(
1358
- "SELECT count, window_start FROM qjw_rate_limits WHERE queue = ? FOR UPDATE",
1359
- [queue]
1360
- );
1361
- const existing = rows[0];
1362
- const windowStart = Number(existing?.["window_start"] ?? 0);
1363
- const count = Number(existing?.["count"] ?? 0);
1364
- if (!existing || nowMs - windowStart >= windowMs) {
1365
- await conn.query("UPDATE qjw_rate_limits SET count = 1, window_start = ? WHERE queue = ?", [
1366
- nowMs,
1367
- queue
1368
- ]);
1369
- await conn.commit();
1370
- return true;
1371
- }
1372
- if (count >= max) {
1373
- await conn.commit();
1374
- return false;
1375
- }
1376
- await conn.query("UPDATE qjw_rate_limits SET count = count + 1 WHERE queue = ?", [queue]);
1377
- await conn.commit();
1378
- return true;
1379
- } catch (err) {
1380
- await conn.rollback();
1381
- throw err;
1382
- } finally {
1383
- conn.release();
1384
- }
1385
- }
1386
- };
1387
- }
1388
- });
1389
-
1390
- // src/core/job.ts
1391
- var Job = class {
1392
- /** @internal Raw data record — treat as immutable outside storage layer. */
1393
- _data;
1394
- constructor(data) {
1395
- this._data = data;
1396
- }
1397
- // -------------------------------------------------------------------------
1398
- // Identity
1399
- // -------------------------------------------------------------------------
1400
- /** Unique, stable job identifier. */
1401
- get id() {
1402
- return this._data.id;
1403
- }
1404
- /** Name of the queue this job belongs to. */
1405
- get queue() {
1406
- return this._data.queue;
1407
- }
1408
- /** Application-defined job type (matches the registered processor). */
1409
- get type() {
1410
- return this._data.type;
1411
- }
1412
- // -------------------------------------------------------------------------
1413
- // Payload
1414
- // -------------------------------------------------------------------------
1415
- /**
1416
- * User-supplied job payload.
1417
- * Never log this value — it may contain sensitive data.
1418
- */
1419
- get data() {
1420
- return this._data.payload;
1421
- }
1422
- // -------------------------------------------------------------------------
1423
- // Status & attempts
1424
- // -------------------------------------------------------------------------
1425
- /** Current lifecycle status. */
1426
- get status() {
1427
- return this._data.status;
1428
- }
1429
- /** Number of attempts already executed (0 = not yet started). */
1430
- get attemptsMade() {
1431
- return this._data.attemptsMade;
1432
- }
1433
- /** Maximum allowed attempts. */
1434
- get maxAttempts() {
1435
- return this._data.maxAttempts;
1436
- }
1437
- /** How many attempts remain (including the current one). */
1438
- get attemptsRemaining() {
1439
- return Math.max(0, this._data.maxAttempts - this._data.attemptsMade);
1440
- }
1441
- /** Ordered list of past attempt records. */
1442
- get attemptHistory() {
1443
- return this._data.attempts;
1444
- }
1445
- // -------------------------------------------------------------------------
1446
- // Retry configuration
1447
- // -------------------------------------------------------------------------
1448
- /** Base delay in ms between retry attempts. */
1449
- get retryDelay() {
1450
- return this._data.retryDelay;
1451
- }
1452
- /** Backoff strategy applied on retry. */
1453
- get backoff() {
1454
- return this._data.backoff;
1455
- }
1456
- // -------------------------------------------------------------------------
1457
- // Execution config
1458
- // -------------------------------------------------------------------------
1459
- /** Per-attempt timeout in ms. */
1460
- get timeout() {
1461
- return this._data.timeout;
1462
- }
1463
- /** Processing priority — higher numbers are processed first. */
1464
- get priority() {
1465
- return this._data.priority;
1466
- }
1467
- // -------------------------------------------------------------------------
1468
- // Scheduling
1469
- // -------------------------------------------------------------------------
1470
- /** ISO timestamp when this job is eligible to run. */
1471
- get runAt() {
1472
- return this._data.runAt;
1473
- }
1474
- /** Cron expression for recurring jobs, or undefined. */
1475
- get cron() {
1476
- return this._data.cron;
1477
- }
1478
- // -------------------------------------------------------------------------
1479
- // Lock
1480
- // -------------------------------------------------------------------------
1481
- /** ID of the worker currently holding the lock, or null. */
1482
- get lockId() {
1483
- return this._data.lockId;
1484
- }
1485
- /** ISO timestamp when the current lock expires, or null. */
1486
- get lockExpiresAt() {
1487
- return this._data.lockExpiresAt;
1488
- }
1489
- // -------------------------------------------------------------------------
1490
- // Timestamps
1491
- // -------------------------------------------------------------------------
1492
- /** ISO timestamp when the job was first enqueued. */
1493
- get createdAt() {
1494
- return this._data.createdAt;
1495
- }
1496
- /** ISO timestamp of the last status change. */
1497
- get updatedAt() {
1498
- return this._data.updatedAt;
1499
- }
1500
- /** ISO timestamp when the job completed successfully, or null. */
1501
- get completedAt() {
1502
- return this._data.completedAt;
1503
- }
1504
- /** ISO timestamp when the job was moved to the DLQ, or null. */
1505
- get failedAt() {
1506
- return this._data.failedAt;
1507
- }
1508
- // -------------------------------------------------------------------------
1509
- // Derived helpers
1510
- // -------------------------------------------------------------------------
1511
- /** Returns true when the job has been successfully processed. */
1512
- isCompleted() {
1513
- return this._data.status === "completed";
1514
- }
1515
- /** Returns true when the job is in the Dead Letter Queue. */
1516
- isDead() {
1517
- return this._data.status === "dead";
1518
- }
1519
- /** Returns true when the job is currently being processed by a worker. */
1520
- isActive() {
1521
- return this._data.status === "active";
1522
- }
1523
- /** Returns true when the job is waiting to be claimed. */
1524
- isWaiting() {
1525
- return this._data.status === "waiting";
1526
- }
1527
- /** Returns true when the job is scheduled for a future time. */
1528
- isDelayed() {
1529
- return this._data.status === "delayed";
1530
- }
1531
- // -------------------------------------------------------------------------
1532
- // Debug representation (intentionally omits payload)
1533
- // -------------------------------------------------------------------------
1534
- toJSON() {
1535
- return {
1536
- id: this._data.id,
1537
- queue: this._data.queue,
1538
- type: this._data.type,
1539
- status: this._data.status,
1540
- attemptsMade: this._data.attemptsMade,
1541
- maxAttempts: this._data.maxAttempts,
1542
- priority: this._data.priority,
1543
- runAt: this._data.runAt,
1544
- createdAt: this._data.createdAt,
1545
- updatedAt: this._data.updatedAt,
1546
- completedAt: this._data.completedAt,
1547
- failedAt: this._data.failedAt
1548
- // Payload intentionally excluded to prevent accidental logging.
1549
- };
1550
- }
1551
- toString() {
1552
- return `Job(${this._data.id}, type=${this._data.type}, status=${this._data.status}, attempt=${this._data.attemptsMade}/${this._data.maxAttempts})`;
1553
- }
1554
- };
1555
-
1556
- // src/core/backoff.ts
1557
- var MAX_DELAY_MS = 10 * 60 * 1e3;
1558
- function calculateBackoff(strategy, baseDelay, attemptNumber) {
1559
- const attempt = Math.max(1, attemptNumber);
1560
- switch (strategy) {
1561
- case "fixed":
1562
- return baseDelay;
1563
- case "linear":
1564
- return baseDelay * attempt;
1565
- case "exponential": {
1566
- const delay = baseDelay * Math.pow(2, attempt - 1);
1567
- return Math.min(delay, MAX_DELAY_MS);
1568
- }
1569
- default: {
1570
- return baseDelay;
1571
- }
1572
- }
1573
- }
1574
- function nextRunAt(delayMs, fromDate = /* @__PURE__ */ new Date()) {
1575
- return new Date(fromDate.getTime() + delayMs).toISOString();
1576
- }
1577
- function generateJobId() {
1578
- return crypto.randomUUID();
1579
- }
1580
-
1581
- // src/core/worker.ts
1582
- function resolveConfig(workerOptions, queueOptions, defaults) {
1583
- return {
1584
- concurrency: workerOptions.concurrency ?? queueOptions.concurrency ?? defaults.concurrency,
1585
- shutdownTimeout: workerOptions.shutdownTimeout ?? 3e4,
1586
- pollInterval: queueOptions.pollInterval ?? defaults.pollInterval,
1587
- stalledInterval: queueOptions.stalledInterval ?? defaults.stalledInterval,
1588
- lockDuration: queueOptions.lockDuration ?? defaults.lockDuration,
1589
- rateLimit: queueOptions.rateLimit ?? defaults.rateLimit
1590
- };
1591
- }
1592
- var Worker = class {
1593
- /** Unique identifier for this worker instance. */
1594
- id;
1595
- queueName;
1596
- storage;
1597
- emitter;
1598
- processors;
1599
- config;
1600
- _status = "idle";
1601
- activeCount = 0;
1602
- /**
1603
- * Tracks job IDs currently being processed so we can release their locks
1604
- * when graceful shutdown times out before they finish.
1605
- */
1606
- activeJobIds = /* @__PURE__ */ new Set();
1607
- pollTimer = null;
1608
- stalledTimer = null;
1609
- /** Resolves when all active jobs finish during shutdown. */
1610
- drainResolve = null;
1611
- constructor(queueName, storage, emitter, processors, workerOptions, queueOptions, defaults) {
1612
- this.id = `worker:${queueName}:${crypto.randomUUID()}`;
1613
- this.queueName = queueName;
1614
- this.storage = storage;
1615
- this.emitter = emitter;
1616
- this.processors = processors;
1617
- this.config = resolveConfig(workerOptions, queueOptions, defaults);
1618
- }
1619
- // -------------------------------------------------------------------------
1620
- // Public API
1621
- // -------------------------------------------------------------------------
1622
- get status() {
1623
- return this._status;
1624
- }
1625
- /** Start polling for jobs. */
1626
- start() {
1627
- if (this._status !== "idle" && this._status !== "stopped") {
1628
- return;
1629
- }
1630
- this._status = "running";
1631
- this.emitter.emit("worker:started", this.id);
1632
- this.emitter.emit("worker:status", this.id, this._status);
1633
- this.schedulePoll();
1634
- this.scheduleStallCheck();
1635
- }
1636
- /**
1637
- * Gracefully stop the worker.
1638
- *
1639
- * 1. Stop accepting new jobs.
1640
- * 2. Wait up to `shutdownTimeout` ms for active jobs to finish.
1641
- * 3. Release locks on any jobs that did not finish in time so another
1642
- * worker can reclaim them.
1643
- * 4. Emit stopped event.
1644
- */
1645
- async stop() {
1646
- if (this._status === "stopped" || this._status === "stopping") {
1647
- return;
1648
- }
1649
- this._status = "stopping";
1650
- this.emitter.emit("worker:status", this.id, this._status);
1651
- if (this.pollTimer) {
1652
- clearTimeout(this.pollTimer);
1653
- this.pollTimer = null;
1654
- }
1655
- if (this.stalledTimer) {
1656
- clearTimeout(this.stalledTimer);
1657
- this.stalledTimer = null;
1658
- }
1659
- if (this.activeCount > 0) {
1660
- await Promise.race([
1661
- new Promise((resolve) => {
1662
- this.drainResolve = resolve;
1663
- }),
1664
- new Promise((resolve) => setTimeout(resolve, this.config.shutdownTimeout))
1665
- ]);
1666
- }
1667
- if (this.activeJobIds.size > 0) {
1668
- await Promise.all(
1669
- Array.from(this.activeJobIds).map(
1670
- (jobId) => this.storage.releaseLock(jobId, this.id).catch(() => {
1671
- })
1672
- )
1673
- );
1674
- }
1675
- this._status = "stopped";
1676
- this.emitter.emit("worker:stopped", this.id);
1677
- this.emitter.emit("worker:status", this.id, this._status);
1678
- }
1679
- // -------------------------------------------------------------------------
1680
- // Poll loop
1681
- // -------------------------------------------------------------------------
1682
- schedulePoll() {
1683
- if (this._status !== "running") return;
1684
- this.pollTimer = setTimeout(() => {
1685
- void this.poll();
1686
- }, this.config.pollInterval);
1687
- }
1688
- async poll() {
1689
- if (this._status !== "running") return;
1690
- try {
1691
- while (this._status === "running" && this.activeCount < this.config.concurrency) {
1692
- const claimed = await this.claimNext();
1693
- if (!claimed) break;
1694
- }
1695
- } catch (err) {
1696
- const error = err instanceof Error ? err : new Error(String(err));
1697
- this.emitter.emit("queue:error", this.queueName, error);
1698
- this.emitter.emit("worker:error", this.id, error);
1699
- }
1700
- this.schedulePoll();
1701
- }
1702
- // -------------------------------------------------------------------------
1703
- // Claim & execute
1704
- // -------------------------------------------------------------------------
1705
- async claimNext() {
1706
- const now = (/* @__PURE__ */ new Date()).toISOString();
1707
- const raw = await this.storage.claim({
1708
- queue: this.queueName,
1709
- lockId: this.id,
1710
- lockDuration: this.config.lockDuration,
1711
- now
1712
- });
1713
- if (!raw) return false;
1714
- if (this.config.rateLimit) {
1715
- const allowed = await this.storage.checkAndIncrementRateLimit(
1716
- this.queueName,
1717
- this.config.rateLimit.max,
1718
- this.config.rateLimit.duration,
1719
- now
1720
- );
1721
- if (!allowed) {
1722
- await this.storage.releaseLock(raw.id, this.id);
1723
- return false;
1724
- }
1725
- }
1726
- const job = new Job(raw);
1727
- this.activeCount += 1;
1728
- this.activeJobIds.add(job.id);
1729
- void this.executeJob(job);
1730
- return true;
1731
- }
1732
- async executeJob(job) {
1733
- this.emitter.emit("job:started", job._data);
1734
- const processor = this.processors.get(job.type);
1735
- if (!processor) {
1736
- const error = new Error(
1737
- `No processor registered for job type "${job.type}" in queue "${this.queueName}"`
1738
- );
1739
- await this.handleFailure(job, error);
1740
- return;
1741
- }
1742
- const abortController = new AbortController();
1743
- let timeoutHandle = null;
1744
- let lockRenewTimer = null;
1745
- const lockRenewInterval = Math.max(100, Math.floor(this.config.lockDuration / 2));
1746
- lockRenewTimer = setInterval(async () => {
1747
- try {
1748
- const renewed = await this.storage.renewLock(job.id, this.id, this.config.lockDuration);
1749
- if (!renewed && lockRenewTimer) {
1750
- clearInterval(lockRenewTimer);
1751
- lockRenewTimer = null;
1752
- }
1753
- } catch {
1754
- }
1755
- }, lockRenewInterval);
1756
- try {
1757
- await new Promise((resolve, reject) => {
1758
- timeoutHandle = setTimeout(() => {
1759
- const timeoutError = new Error(`Job timed out after ${job.timeout}ms`);
1760
- abortController.abort(timeoutError);
1761
- reject(timeoutError);
1762
- }, job.timeout);
1763
- Promise.resolve(processor(job, abortController.signal)).then(resolve, reject);
1764
- });
1765
- if (timeoutHandle) clearTimeout(timeoutHandle);
1766
- if (lockRenewTimer) {
1767
- clearInterval(lockRenewTimer);
1768
- lockRenewTimer = null;
1769
- }
1770
- await this.storage.complete(job.id, this.id);
1771
- const completedData = await this.storage.getJob(job.id) ?? job._data;
1772
- this.emitter.emit("job:completed", completedData);
1773
- if (job.cron) {
1774
- await this.enqueueCronNext(job);
1775
- }
1776
- } catch (err) {
1777
- if (timeoutHandle) clearTimeout(timeoutHandle);
1778
- if (lockRenewTimer) {
1779
- clearInterval(lockRenewTimer);
1780
- lockRenewTimer = null;
1781
- }
1782
- const error = err instanceof Error ? err : new Error(String(err));
1783
- await this.handleFailure(job, error);
1784
- } finally {
1785
- if (lockRenewTimer) {
1786
- clearInterval(lockRenewTimer);
1787
- lockRenewTimer = null;
1788
- }
1789
- this.activeJobIds.delete(job.id);
1790
- this.activeCount -= 1;
1791
- if (this.activeCount === 0 && this.drainResolve) {
1792
- this.drainResolve();
1793
- this.drainResolve = null;
1794
- }
1795
- }
1796
- }
1797
- // -------------------------------------------------------------------------
1798
- // Cron — re-enqueue the next occurrence after a successful run
1799
- // -------------------------------------------------------------------------
1800
- async enqueueCronNext(job) {
1801
- try {
1802
- let nextDate;
1803
- try {
1804
- const cronInstance = new croner.Cron(job.cron);
1805
- nextDate = cronInstance.nextRun();
1806
- } catch (cronErr) {
1807
- const error = cronErr instanceof Error ? cronErr : new Error(
1808
- `croner failed to initialize for expression "${job.cron}": ${String(cronErr)}`
1809
- );
1810
- this.emitter.emit("worker:error", this.id, error);
1811
- return;
1812
- }
1813
- if (nextDate === null) {
1814
- const error = new Error(
1815
- `Cron expression "${job.cron}" has no future occurrences \u2014 job "${job.id}" will not be re-enqueued`
1816
- );
1817
- this.emitter.emit("worker:error", this.id, error);
1818
- return;
1819
- }
1820
- const runAt = nextDate.toISOString();
1821
- await this.storage.enqueue({
1822
- id: generateJobId(),
1823
- queue: this.queueName,
1824
- type: job.type,
1825
- payload: job._data.payload,
1826
- maxAttempts: job.maxAttempts,
1827
- retryDelay: job.retryDelay,
1828
- backoff: job.backoff,
1829
- timeout: job.timeout,
1830
- priority: job.priority,
1831
- runAt,
1832
- cron: job.cron
1833
- });
1834
- } catch (err) {
1835
- const error = err instanceof Error ? err : new Error(String(err));
1836
- this.emitter.emit("worker:error", this.id, error);
1837
- }
1838
- }
1839
- // -------------------------------------------------------------------------
1840
- // Failure handling — requeue or DLQ
1841
- // -------------------------------------------------------------------------
1842
- async handleFailure(job, error) {
1843
- const attemptNumber = job.attemptsMade + 1;
1844
- const hasMore = attemptNumber < job.maxAttempts;
1845
- this.emitter.emit("job:failed", job._data, error);
1846
- if (hasMore) {
1847
- const delayMs = calculateBackoff(job.backoff, job.retryDelay, attemptNumber);
1848
- const runAt = nextRunAt(delayMs);
1849
- await this.storage.requeue({
1850
- jobId: job.id,
1851
- runAt,
1852
- error: error.message,
1853
- attemptNumber,
1854
- lockId: this.id,
1855
- ...error.stack !== void 0 && { stack: error.stack }
1856
- });
1857
- const updated = await this.storage.getJob(job.id);
1858
- if (updated) {
1859
- this.emitter.emit("job:retrying", updated, error, runAt);
1860
- }
1861
- } else {
1862
- await this.storage.moveToDlq({
1863
- jobId: job.id,
1864
- error: error.message,
1865
- attemptNumber,
1866
- lockId: this.id,
1867
- ...error.stack !== void 0 && { stack: error.stack }
1868
- });
1869
- const dead = await this.storage.getJob(job.id);
1870
- if (dead) {
1871
- this.emitter.emit("job:dead", dead, error);
1872
- }
1873
- }
1874
- }
1875
- // -------------------------------------------------------------------------
1876
- // Stalled-job recovery
1877
- // -------------------------------------------------------------------------
1878
- scheduleStallCheck() {
1879
- if (this._status !== "running") return;
1880
- this.stalledTimer = setTimeout(() => {
1881
- void this.recoverStalledJobs();
1882
- }, this.config.stalledInterval);
1883
- }
1884
- async recoverStalledJobs() {
1885
- if (this._status !== "running") return;
1886
- try {
1887
- const now = (/* @__PURE__ */ new Date()).toISOString();
1888
- const recovered = await this.storage.recoverStalledJobs(this.queueName, now);
1889
- for (const jobId of recovered) {
1890
- this.emitter.emit("job:stalled", jobId);
1891
- this.emitter.emit("job:recovered", jobId);
1892
- }
1893
- } catch (err) {
1894
- const error = err instanceof Error ? err : new Error(String(err));
1895
- this.emitter.emit("worker:error", this.id, error);
1896
- }
1897
- this.scheduleStallCheck();
1898
- }
1899
- };
1900
-
1901
- // src/core/queue.ts
1902
- function mergeQueueConfig(options, defaults) {
1903
- return {
1904
- concurrency: options?.concurrency ?? defaults.concurrency,
1905
- attempts: options?.attempts ?? defaults.attempts,
1906
- retryDelay: options?.retryDelay ?? defaults.retryDelay,
1907
- backoff: options?.backoff ?? defaults.backoff,
1908
- timeout: options?.timeout ?? defaults.timeout,
1909
- rateLimit: options?.rateLimit ?? defaults.rateLimit ?? void 0,
1910
- pollInterval: options?.pollInterval ?? defaults.pollInterval,
1911
- stalledInterval: options?.stalledInterval ?? defaults.stalledInterval,
1912
- lockDuration: options?.lockDuration ?? defaults.lockDuration
1913
- };
1914
- }
1915
- var Queue = class {
1916
- /** The name of this queue — unique within a QueueClient. */
1917
- name;
1918
- storage;
1919
- emitter;
1920
- resolvedConfig;
1921
- clientDefaults;
1922
- isInitialisedCheck;
1923
- /** Registered processors keyed by job type. */
1924
- processors = /* @__PURE__ */ new Map();
1925
- /** Active worker instances created by this queue. */
1926
- workers = [];
1927
- constructor(name, storage, emitter, options, defaults, isInitialisedCheck) {
1928
- this.name = name;
1929
- this.storage = storage;
1930
- this.emitter = emitter;
1931
- this.clientDefaults = defaults;
1932
- this.resolvedConfig = mergeQueueConfig(options, defaults);
1933
- this.isInitialisedCheck = isInitialisedCheck;
1934
- }
1935
- assertInitialised() {
1936
- if (this.isInitialisedCheck && !this.isInitialisedCheck()) {
1937
- throw new Error(
1938
- `Cannot execute queue operations on queue "${this.name}" because the QueueClient is not initialised. Call "await client.init()" first.`
1939
- );
1940
- }
1941
- }
1942
- // -------------------------------------------------------------------------
1943
- // Enqueue
1944
- // -------------------------------------------------------------------------
1945
- /**
1946
- * Add a new job to the queue.
1947
- *
1948
- * @param type - Job type string, must match a registered processor.
1949
- * @param payload - Arbitrary serialisable payload (never logged by default).
1950
- * @param options - Per-job overrides (attempts, delay, priority, etc.).
1951
- */
1952
- async enqueue(type, payload, options) {
1953
- this.assertInitialised();
1954
- const cfg = this.resolvedConfig;
1955
- const now = /* @__PURE__ */ new Date();
1956
- let runAt;
1957
- if (options?.schedule?.runAt !== void 0) {
1958
- runAt = new Date(options.schedule.runAt);
1959
- } else if (options?.schedule?.delay !== void 0) {
1960
- runAt = new Date(now.getTime() + options.schedule.delay);
1961
- } else {
1962
- runAt = now;
1963
- }
1964
- const raw = await this.storage.enqueue({
1965
- id: generateJobId(),
1966
- queue: this.name,
1967
- type,
1968
- payload,
1969
- maxAttempts: options?.attempts ?? cfg.attempts,
1970
- retryDelay: options?.retryDelay ?? cfg.retryDelay,
1971
- backoff: options?.backoff ?? cfg.backoff,
1972
- timeout: options?.timeout ?? cfg.timeout,
1973
- priority: options?.priority ?? 0,
1974
- runAt: runAt.toISOString(),
1975
- ...options?.schedule?.cron !== void 0 && { cron: options.schedule.cron }
1976
- });
1977
- const job = new Job(raw);
1978
- this.emitter.emit("job:enqueued", raw);
1979
- return job;
1980
- }
1981
- // -------------------------------------------------------------------------
1982
- // Processor registration
1983
- // -------------------------------------------------------------------------
1984
- /**
1985
- * Register a processor function for a given job type.
1986
- *
1987
- * Only one processor per type per queue is supported.
1988
- * Registering a second processor for the same type replaces the first.
1989
- */
1990
- process(type, processor) {
1991
- this.processors.set(type, processor);
1992
- }
1993
- // -------------------------------------------------------------------------
1994
- // Worker creation
1995
- // -------------------------------------------------------------------------
1996
- /**
1997
- * Create and start a Worker that consumes jobs from this queue.
1998
- *
1999
- * Worker-level `concurrency` overrides queue-level concurrency.
2000
- */
2001
- createWorker(options) {
2002
- this.assertInitialised();
2003
- const worker = new Worker(
2004
- this.name,
2005
- this.storage,
2006
- this.emitter,
2007
- this.processors,
2008
- options ?? {},
2009
- this.resolvedConfig,
2010
- this.clientDefaults
2011
- );
2012
- this.workers.push(worker);
2013
- worker.start();
2014
- return worker;
2015
- }
2016
- // -------------------------------------------------------------------------
2017
- // Reads
2018
- // -------------------------------------------------------------------------
2019
- /** Fetch a single job by its ID. Returns null if not found or wrong queue. */
2020
- async getJob(jobId) {
2021
- this.assertInitialised();
2022
- const raw = await this.storage.getJob(jobId);
2023
- if (!raw || raw.queue !== this.name) return null;
2024
- return new Job(raw);
2025
- }
2026
- /** Fetch jobs from this queue, optionally filtered by status. */
2027
- async getJobs(status, limit = 100, offset = 0) {
2028
- this.assertInitialised();
2029
- const raws = await this.storage.getJobs({
2030
- queue: this.name,
2031
- ...status !== void 0 && { status },
2032
- limit,
2033
- offset
2034
- });
2035
- return raws.map((r) => new Job(r));
2036
- }
2037
- /** Get job counts by status for this queue. */
2038
- async getJobCounts() {
2039
- this.assertInitialised();
2040
- return this.storage.getJobCounts(this.name);
2041
- }
2042
- // -------------------------------------------------------------------------
2043
- // Lifecycle
2044
- // -------------------------------------------------------------------------
2045
- /**
2046
- * Gracefully stop all workers attached to this queue.
2047
- * Called automatically by QueueClient.close().
2048
- */
2049
- async close() {
2050
- await Promise.all(this.workers.map((w) => w.stop()));
2051
- }
2052
- /** Return all active worker instances on this queue. */
2053
- getWorkers() {
2054
- return this.workers;
2055
- }
2056
- };
2057
-
2058
- // src/storage/in-memory.adapter.ts
2059
- var InMemoryStorageAdapter = class {
2060
- jobs = /* @__PURE__ */ new Map();
2061
- rateLimitBuckets = /* @__PURE__ */ new Map();
2062
- // -------------------------------------------------------------------------
2063
- // Lifecycle
2064
- // -------------------------------------------------------------------------
2065
- async initialize() {
2066
- }
2067
- async close() {
2068
- this.jobs.clear();
2069
- this.rateLimitBuckets.clear();
2070
- }
2071
- // -------------------------------------------------------------------------
2072
- // Enqueue
2073
- // -------------------------------------------------------------------------
2074
- async enqueue(input) {
2075
- if (this.jobs.has(input.id)) {
2076
- return this.jobs.get(input.id);
2077
- }
2078
- const now = (/* @__PURE__ */ new Date()).toISOString();
2079
- const runAt = input.runAt;
2080
- const isDelayed = new Date(runAt).getTime() > Date.now();
2081
- const job = {
2082
- id: input.id,
2083
- queue: input.queue,
2084
- type: input.type,
2085
- payload: input.payload,
2086
- status: isDelayed ? "delayed" : "waiting",
2087
- attemptsMade: 0,
2088
- maxAttempts: input.maxAttempts,
2089
- retryDelay: input.retryDelay,
2090
- backoff: input.backoff,
2091
- timeout: input.timeout,
2092
- priority: input.priority,
2093
- runAt,
2094
- ...input.cron !== void 0 && { cron: input.cron },
2095
- attempts: [],
2096
- lockId: null,
2097
- lockExpiresAt: null,
2098
- createdAt: now,
2099
- updatedAt: now,
2100
- completedAt: null,
2101
- failedAt: null
2102
- };
2103
- this.jobs.set(job.id, job);
2104
- return job;
2105
- }
2106
- // -------------------------------------------------------------------------
2107
- // Claim (atomic within a single event-loop tick)
2108
- // -------------------------------------------------------------------------
2109
- async claim(input) {
2110
- const { queue, lockId, lockDuration, now } = input;
2111
- const nowMs = new Date(now).getTime();
2112
- const eligible = [];
2113
- for (const job2 of this.jobs.values()) {
2114
- if (job2.queue !== queue) continue;
2115
- if (job2.status !== "waiting" && job2.status !== "delayed") continue;
2116
- if (new Date(job2.runAt).getTime() > nowMs) continue;
2117
- if (job2.lockId !== null && job2.lockExpiresAt !== null) {
2118
- const lockExpiry = new Date(job2.lockExpiresAt).getTime();
2119
- if (lockExpiry > nowMs) continue;
2120
- }
2121
- eligible.push(job2);
2122
- }
2123
- if (eligible.length === 0) return null;
2124
- eligible.sort((a, b) => {
2125
- if (b.priority !== a.priority) return b.priority - a.priority;
2126
- const runAtDiff = new Date(a.runAt).getTime() - new Date(b.runAt).getTime();
2127
- if (runAtDiff !== 0) return runAtDiff;
2128
- return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
2129
- });
2130
- const job = eligible[0];
2131
- if (!job) return null;
2132
- const lockExpiresAt = new Date(nowMs + lockDuration).toISOString();
2133
- job.status = "active";
2134
- job.lockId = lockId;
2135
- job.lockExpiresAt = lockExpiresAt;
2136
- job.updatedAt = now;
2137
- return job;
2138
- }
2139
- // -------------------------------------------------------------------------
2140
- // Renew lock
2141
- // -------------------------------------------------------------------------
2142
- async renewLock(jobId, lockId, lockDuration) {
2143
- const job = this.jobs.get(jobId);
2144
- if (!job) return false;
2145
- if (job.status !== "active" || job.lockId !== lockId) return false;
2146
- const nowMs = Date.now();
2147
- if (job.lockExpiresAt !== null && new Date(job.lockExpiresAt).getTime() <= nowMs) {
2148
- return false;
2149
- }
2150
- job.lockExpiresAt = new Date(nowMs + lockDuration).toISOString();
2151
- job.updatedAt = new Date(nowMs).toISOString();
2152
- return true;
2153
- }
2154
- // -------------------------------------------------------------------------
2155
- // Complete
2156
- // -------------------------------------------------------------------------
2157
- async complete(jobId, lockId) {
2158
- const job = this.jobs.get(jobId);
2159
- if (!job) return;
2160
- if (lockId !== void 0 && (job.status !== "active" || job.lockId !== lockId)) {
2161
- return;
2162
- }
2163
- const now = (/* @__PURE__ */ new Date()).toISOString();
2164
- job.status = "completed";
2165
- job.lockId = null;
2166
- job.lockExpiresAt = null;
2167
- job.completedAt = now;
2168
- job.updatedAt = now;
2169
- }
2170
- // -------------------------------------------------------------------------
2171
- // Requeue (retry)
2172
- // -------------------------------------------------------------------------
2173
- async requeue(input) {
2174
- const job = this.jobs.get(input.jobId);
2175
- if (!job) return;
2176
- if (input.lockId !== void 0 && (job.status !== "active" || job.lockId !== input.lockId)) {
2177
- return;
2178
- }
2179
- const now = (/* @__PURE__ */ new Date()).toISOString();
2180
- job.attempts.push({
2181
- attempt: input.attemptNumber,
2182
- startedAt: job.updatedAt,
2183
- finishedAt: now,
2184
- error: input.error,
2185
- ...input.stack !== void 0 && { stack: input.stack }
2186
- });
2187
- job.attemptsMade = input.attemptNumber;
2188
- job.status = "waiting";
2189
- job.runAt = input.runAt;
2190
- job.lockId = null;
2191
- job.lockExpiresAt = null;
2192
- job.updatedAt = now;
2193
- }
2194
- // -------------------------------------------------------------------------
2195
- // Move to DLQ
2196
- // -------------------------------------------------------------------------
2197
- async moveToDlq(input) {
2198
- const job = this.jobs.get(input.jobId);
2199
- if (!job) return;
2200
- if (input.lockId !== void 0 && (job.status !== "active" || job.lockId !== input.lockId)) {
2201
- return;
2202
- }
2203
- const now = (/* @__PURE__ */ new Date()).toISOString();
2204
- job.attempts.push({
2205
- attempt: input.attemptNumber,
2206
- startedAt: job.updatedAt,
2207
- finishedAt: now,
2208
- error: input.error,
2209
- ...input.stack !== void 0 && { stack: input.stack }
2210
- });
2211
- job.attemptsMade = input.attemptNumber;
2212
- job.status = "dead";
2213
- job.lockId = null;
2214
- job.lockExpiresAt = null;
2215
- job.failedAt = now;
2216
- job.updatedAt = now;
2217
- }
2218
- // -------------------------------------------------------------------------
2219
- // Release lock
2220
- // -------------------------------------------------------------------------
2221
- async releaseLock(jobId, lockId) {
2222
- const job = this.jobs.get(jobId);
2223
- if (!job) return;
2224
- if (lockId !== void 0 && (job.status !== "active" || job.lockId !== lockId)) {
2225
- return;
2226
- }
2227
- const now = (/* @__PURE__ */ new Date()).toISOString();
2228
- job.lockId = null;
2229
- job.lockExpiresAt = now;
2230
- job.updatedAt = now;
2231
- }
2232
- // -------------------------------------------------------------------------
2233
- // Recover stalled jobs
2234
- //
2235
- // Fix (issue #6): snapshot lockId and lockExpiresAt before the eligibility
2236
- // check, then re-validate both values at write time. In a single-process
2237
- // scenario all operations are synchronous within one event-loop tick, so
2238
- // the race is theoretical — but the guard makes the adapter consistent with
2239
- // the Redis CAS semantics and protects against any future async paths.
2240
- // -------------------------------------------------------------------------
2241
- async recoverStalledJobs(queue, now) {
2242
- const nowMs = new Date(now).getTime();
2243
- const recovered = [];
2244
- for (const job of this.jobs.values()) {
2245
- if (job.queue !== queue) continue;
2246
- if (job.status !== "active") continue;
2247
- if (job.lockExpiresAt === null) continue;
2248
- const lockExpiry = new Date(job.lockExpiresAt).getTime();
2249
- if (lockExpiry > nowMs) continue;
2250
- const snapshotLockId = job.lockId;
2251
- const snapshotLockExpiresAt = job.lockExpiresAt;
2252
- if (job.status !== "active") continue;
2253
- if (job.lockId !== snapshotLockId) continue;
2254
- if (job.lockExpiresAt !== snapshotLockExpiresAt) continue;
2255
- job.status = "waiting";
2256
- job.lockId = null;
2257
- job.lockExpiresAt = null;
2258
- job.updatedAt = now;
2259
- recovered.push(job.id);
2260
- }
2261
- return recovered;
2262
- }
2263
- // -------------------------------------------------------------------------
2264
- // Reads
2265
- // -------------------------------------------------------------------------
2266
- async getJob(jobId) {
2267
- return this.jobs.get(jobId) ?? null;
2268
- }
2269
- async getJobs(filter) {
2270
- const { queue, status, limit = 100, offset = 0 } = filter;
2271
- const results = [];
2272
- for (const job of this.jobs.values()) {
2273
- if (queue !== void 0 && job.queue !== queue) continue;
2274
- if (status !== void 0 && job.status !== status) continue;
2275
- results.push(job);
2276
- }
2277
- results.sort((a, b) => {
2278
- if (b.priority !== a.priority) return b.priority - a.priority;
2279
- return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
2280
- });
2281
- return results.slice(offset, offset + limit);
2282
- }
2283
- async getJobCounts(queue) {
2284
- const counts = {
2285
- waiting: 0,
2286
- active: 0,
2287
- completed: 0,
2288
- delayed: 0,
2289
- dead: 0
2290
- };
2291
- for (const job of this.jobs.values()) {
2292
- if (job.queue !== queue) continue;
2293
- counts[job.status] += 1;
2294
- }
2295
- return counts;
2296
- }
2297
- // -------------------------------------------------------------------------
2298
- // Rate limiting
2299
- // -------------------------------------------------------------------------
2300
- async checkAndIncrementRateLimit(queue, max, windowMs, now) {
2301
- const nowMs = new Date(now).getTime();
2302
- const existing = this.rateLimitBuckets.get(queue);
2303
- if (!existing || nowMs - existing.windowStart >= windowMs) {
2304
- this.rateLimitBuckets.set(queue, { count: 1, windowStart: nowMs });
2305
- return true;
2306
- }
2307
- if (existing.count >= max) {
2308
- return false;
2309
- }
2310
- existing.count += 1;
2311
- return true;
2312
- }
2313
- // -------------------------------------------------------------------------
2314
- // Internal helpers
2315
- // -------------------------------------------------------------------------
2316
- requireJob(jobId) {
2317
- const job = this.jobs.get(jobId);
2318
- if (!job) {
2319
- throw new Error(`Job not found: ${jobId}`);
2320
- }
2321
- return job;
2322
- }
2323
- };
2324
- var QueueEventEmitter = class {
2325
- emitter;
2326
- constructor() {
2327
- this.emitter = new events.EventEmitter();
2328
- this.emitter.setMaxListeners(100);
2329
- }
2330
- // -------------------------------------------------------------------------
2331
- // Subscribe
2332
- // -------------------------------------------------------------------------
2333
- on(event, listener) {
2334
- this.emitter.on(event, listener);
2335
- return this;
2336
- }
2337
- once(event, listener) {
2338
- this.emitter.once(event, listener);
2339
- return this;
2340
- }
2341
- off(event, listener) {
2342
- this.emitter.off(event, listener);
2343
- return this;
2344
- }
2345
- // ---------------------------------------------------------------------------
2346
- // Publish
2347
- // ---------------------------------------------------------------------------
2348
- emit(event, ...args) {
2349
- return this.emitter.emit(event, ...args);
2350
- }
2351
- // ---------------------------------------------------------------------------
2352
- // Utility
2353
- // ---------------------------------------------------------------------------
2354
- removeAllListeners(event) {
2355
- if (event) {
2356
- this.emitter.removeAllListeners(event);
2357
- } else {
2358
- this.emitter.removeAllListeners();
2359
- }
2360
- return this;
2361
- }
2362
- listenerCount(event) {
2363
- return this.emitter.listenerCount(event);
2364
- }
2365
- };
2366
-
2367
- // src/core/client.ts
2368
- var HARD_DEFAULTS = {
2369
- attempts: 3,
2370
- retryDelay: 1e3,
2371
- backoff: "exponential",
2372
- timeout: 3e4,
2373
- concurrency: 10,
2374
- rateLimit: void 0,
2375
- pollInterval: 1e3,
2376
- stalledInterval: 3e4,
2377
- lockDuration: 6e4
2378
- };
2379
- var QueueClient = class _QueueClient {
2380
- /** @internal — mutable so withAdapter() can replace it */
2381
- _storage;
2382
- emitter;
2383
- defaults;
2384
- dialect;
2385
- connectionString;
2386
- queues = /* @__PURE__ */ new Map();
2387
- initialised = false;
2388
- closed = false;
2389
- /** True when the adapter was supplied via {@link withAdapter}; init() skips resolveAdapter() in that case. */
2390
- _customAdapter = false;
2391
- constructor(options = {}) {
2392
- this.defaults = { ...HARD_DEFAULTS, ...options.defaults };
2393
- this.dialect = options.dialect ?? "memory";
2394
- this.connectionString = options.connectionString;
2395
- this._storage = this.buildMemoryOrEagerAdapter();
2396
- if (this.dialect === "memory") {
2397
- this.initialised = true;
2398
- }
2399
- this.emitter = new QueueEventEmitter();
2400
- }
2401
- // -------------------------------------------------------------------------
2402
- // Eager adapter construction (memory only; external adapters built in init)
2403
- // -------------------------------------------------------------------------
2404
- buildMemoryOrEagerAdapter() {
2405
- if (this.dialect === "memory") {
2406
- return new InMemoryStorageAdapter();
2407
- }
2408
- return new InMemoryStorageAdapter();
2409
- }
2410
- // -------------------------------------------------------------------------
2411
- // Initialisation
2412
- // -------------------------------------------------------------------------
2413
- /**
2414
- * Initialise the client and storage adapter.
2415
- *
2416
- * **Must be called** before creating queues when using Redis, PostgreSQL,
2417
- * or MySQL.
2418
- *
2419
- * What each adapter does:
2420
- * - **memory** — no-op (always safe to call)
2421
- * - **redis** — connects, sends PING, verifies PONG
2422
- * - **postgres** — connects, runs `SELECT 1`, auto-creates `qjw_` tables
2423
- * - **mysql** — connects, runs `SELECT 1`, auto-creates `qjw_` tables
2424
- *
2425
- * Idempotent — safe to call multiple times.
2426
- */
2427
- async init() {
2428
- if (this.initialised) return;
2429
- if (!this._customAdapter) {
2430
- this._storage = await this.resolveAdapter();
2431
- }
2432
- await this._storage.initialize();
2433
- this.initialised = true;
2434
- }
2435
- /** @deprecated Use `init()`. */
2436
- async initialize() {
2437
- return this.init();
2438
- }
2439
- async resolveAdapter() {
2440
- const cs = this.connectionString;
2441
- switch (this.dialect) {
2442
- case "memory":
2443
- return new InMemoryStorageAdapter();
2444
- case "redis": {
2445
- if (!cs) throw new Error('dialect "redis" requires a connectionString.');
2446
- const { RedisStorageAdapter: RedisStorageAdapter2 } = await Promise.resolve().then(() => (init_redis_adapter(), redis_adapter_exports));
2447
- return new RedisStorageAdapter2(cs);
2448
- }
2449
- case "postgres": {
2450
- if (!cs) throw new Error('dialect "postgres" requires a connectionString.');
2451
- const { PostgreSQLStorageAdapter: PostgreSQLStorageAdapter2 } = await Promise.resolve().then(() => (init_postgres_adapter(), postgres_adapter_exports));
2452
- return new PostgreSQLStorageAdapter2(cs);
2453
- }
2454
- case "mysql": {
2455
- if (!cs) throw new Error('dialect "mysql" requires a connectionString.');
2456
- const { MySQLStorageAdapter: MySQLStorageAdapter2 } = await Promise.resolve().then(() => (init_mysql_adapter(), mysql_adapter_exports));
2457
- return new MySQLStorageAdapter2(cs);
2458
- }
2459
- default:
2460
- throw new Error(`Unknown storage dialect: "${this.dialect}"`);
2461
- }
2462
- }
2463
- // -------------------------------------------------------------------------
2464
- // Queue management
2465
- // -------------------------------------------------------------------------
2466
- /**
2467
- * Create a named queue with optional per-queue configuration.
2468
- *
2469
- * For external dialects (redis/postgres/mysql), call `await client.init()`
2470
- * first.
2471
- */
2472
- createQueue(name, options) {
2473
- if (this.closed) throw new Error("QueueClient has been closed.");
2474
- if (this.queues.has(name)) {
2475
- throw new Error(`A queue named "${name}" already exists on this client.`);
2476
- }
2477
- if (!this.initialised) {
2478
- throw new Error(
2479
- `QueueClient is not initialised. Call "await client.init()" before creating queues for dialect "${this.dialect}".`
2480
- );
2481
- }
2482
- const queue = new Queue(
2483
- name,
2484
- this._storage,
2485
- this.emitter,
2486
- options,
2487
- this.defaults,
2488
- () => this.initialised
2489
- );
2490
- this.queues.set(name, queue);
2491
- return queue;
2492
- }
2493
- /** Returns the queue with the given name, or `undefined`. */
2494
- getQueue(name) {
2495
- return this.queues.get(name);
2496
- }
2497
- /** Returns the queue with the given name, or throws. */
2498
- requireQueue(name) {
2499
- const queue = this.getQueue(name);
2500
- if (!queue) {
2501
- throw new Error(`Queue "${name}" not found. Did you call createQueue("${name}")?`);
2502
- }
2503
- return queue;
2504
- }
2505
- /** Names of all queues registered on this client. */
2506
- get queueNames() {
2507
- return Array.from(this.queues.keys());
2508
- }
2509
- /** `true` after `init()` has completed successfully. */
2510
- get isInitialised() {
2511
- return this.initialised;
2512
- }
2513
- // -------------------------------------------------------------------------
2514
- // Events
2515
- // -------------------------------------------------------------------------
2516
- on(event, listener) {
2517
- this.emitter.on(event, listener);
2518
- return this;
2519
- }
2520
- once(event, listener) {
2521
- this.emitter.once(event, listener);
2522
- return this;
2523
- }
2524
- off(event, listener) {
2525
- this.emitter.off(event, listener);
2526
- return this;
2527
- }
2528
- // -------------------------------------------------------------------------
2529
- // Graceful shutdown
2530
- // -------------------------------------------------------------------------
2531
- /**
2532
- * Stop all workers, close all queues, and release the storage connection.
2533
- * Safe to call multiple times.
2534
- */
2535
- async close() {
2536
- if (this.closed) return;
2537
- this.closed = true;
2538
- await Promise.all(Array.from(this.queues.values()).map((q) => q.close()));
2539
- await this._storage.close();
2540
- this.emitter.removeAllListeners();
2541
- }
2542
- // -------------------------------------------------------------------------
2543
- // Advanced: custom StorageAdapter
2544
- // -------------------------------------------------------------------------
2545
- /**
2546
- * Create a QueueClient with a fully custom StorageAdapter.
2547
- *
2548
- * `init()` will call `adapter.initialize()`.
2549
- *
2550
- * @example
2551
- * const client = QueueClient.withAdapter(myAdapter);
2552
- * await client.init();
2553
- */
2554
- static withAdapter(adapter, options = {}) {
2555
- const client = new _QueueClient(options);
2556
- client._storage = adapter;
2557
- client._customAdapter = true;
2558
- client.initialised = false;
2559
- return client;
2560
- }
2561
- };
2562
-
2563
- // src/index.ts
2564
- init_redis_adapter();
2565
- init_postgres_adapter();
2566
- init_mysql_adapter();
2567
-
2568
- exports.InMemoryStorageAdapter = InMemoryStorageAdapter;
2569
- exports.Job = Job;
2570
- exports.Queue = Queue;
2571
- exports.QueueClient = QueueClient;
2572
- exports.QueueEventEmitter = QueueEventEmitter;
2573
- exports.Worker = Worker;
2574
- exports.calculateBackoff = calculateBackoff;
2575
- exports.generateJobId = generateJobId;
2576
- exports.nextRunAt = nextRunAt;
2577
- //# sourceMappingURL=index.cjs.map
2578
- //# sourceMappingURL=index.cjs.map