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