@kairojsmodule/queue 0.0.0-stage → 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.
- package/index.d.ts +25 -0
- package/package.json +20 -4
- package/src/Job.js +12 -0
- package/src/Queue.js +64 -0
- package/src/Worker.js +58 -0
- package/src/index.js +3 -0
- package/test/queue.test.js +62 -0
- package/README.md +0 -3
package/index.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export declare class Job {
|
|
2
|
+
data: Record<string, any>;
|
|
3
|
+
retries: number;
|
|
4
|
+
backoffMs: number;
|
|
5
|
+
timeoutMs: number;
|
|
6
|
+
constructor(data?: Record<string, any>);
|
|
7
|
+
handle(): Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export declare class Queue {
|
|
11
|
+
dispatch(jobOrHandler: Job | Function, data?: Record<string, any>, options?: { delay?: number; retries?: number; backoffMs?: number }): string;
|
|
12
|
+
pop(): any;
|
|
13
|
+
size(): number;
|
|
14
|
+
getFailed(): any[];
|
|
15
|
+
clear(): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export declare const defaultQueue: Queue;
|
|
19
|
+
|
|
20
|
+
export declare class Worker {
|
|
21
|
+
constructor(queue?: Queue);
|
|
22
|
+
processNext(): Promise<{ success: boolean; id: string; error?: string } | null>;
|
|
23
|
+
work(options?: { stopWhenEmpty?: boolean; pollIntervalMs?: number }): Promise<void>;
|
|
24
|
+
stop(): void;
|
|
25
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kairojsmodule/queue",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Background jobs, worker execution, retries, and failure tracking for KairoJS",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"types": "./index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.js"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"kairojs",
|
|
13
|
+
"queue",
|
|
14
|
+
"jobs",
|
|
15
|
+
"workers",
|
|
16
|
+
"background"
|
|
17
|
+
],
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public"
|
|
20
|
+
},
|
|
21
|
+
"author": "Riski Ardiane <@kairojsmodule>"
|
|
22
|
+
}
|
package/src/Job.js
ADDED
package/src/Queue.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { Job } from './Job.js';
|
|
3
|
+
|
|
4
|
+
export class Queue {
|
|
5
|
+
constructor() {
|
|
6
|
+
this._jobs = [];
|
|
7
|
+
this._failed = [];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Dispatch a job instance or handler function to the queue.
|
|
12
|
+
* @param {Job|Function} jobOrHandler
|
|
13
|
+
* @param {Record<string, any>} [data={}]
|
|
14
|
+
* @param {Object} [options={}]
|
|
15
|
+
*/
|
|
16
|
+
dispatch(jobOrHandler, data = {}, options = {}) {
|
|
17
|
+
const id = crypto.randomUUID();
|
|
18
|
+
const initialData = (jobOrHandler && jobOrHandler.data) ? { ...jobOrHandler.data, ...data } : data;
|
|
19
|
+
|
|
20
|
+
const entry = {
|
|
21
|
+
id,
|
|
22
|
+
job: jobOrHandler,
|
|
23
|
+
data: initialData,
|
|
24
|
+
attempts: 0,
|
|
25
|
+
retries: options.retries !== undefined ? options.retries : jobOrHandler.retries || 3,
|
|
26
|
+
backoffMs: options.backoffMs !== undefined ? options.backoffMs : jobOrHandler.backoffMs || 200,
|
|
27
|
+
availableAt: options.delay ? Date.now() + options.delay : Date.now()
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
this._jobs.push(entry);
|
|
31
|
+
return id;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
pop() {
|
|
35
|
+
const now = Date.now();
|
|
36
|
+
const idx = this._jobs.findIndex((j) => j.availableAt <= now);
|
|
37
|
+
if (idx === -1) return null;
|
|
38
|
+
return this._jobs.splice(idx, 1)[0];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
size() {
|
|
42
|
+
return this._jobs.length;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
logFailed(entry, error) {
|
|
46
|
+
this._failed.push({
|
|
47
|
+
id: entry.id,
|
|
48
|
+
data: entry.data,
|
|
49
|
+
failedAt: new Date().toISOString(),
|
|
50
|
+
error: error.message
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
getFailed() {
|
|
55
|
+
return this._failed;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
clear() {
|
|
59
|
+
this._jobs = [];
|
|
60
|
+
this._failed = [];
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const defaultQueue = new Queue();
|
package/src/Worker.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { defaultQueue } from './Queue.js';
|
|
2
|
+
|
|
3
|
+
export class Worker {
|
|
4
|
+
constructor(queue = defaultQueue) {
|
|
5
|
+
this.queue = queue;
|
|
6
|
+
this.isRunning = false;
|
|
7
|
+
this._stopRequested = false;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
async processNext() {
|
|
11
|
+
const entry = this.queue.pop();
|
|
12
|
+
if (!entry) return null;
|
|
13
|
+
|
|
14
|
+
entry.attempts += 1;
|
|
15
|
+
|
|
16
|
+
try {
|
|
17
|
+
if (typeof entry.job === 'function') {
|
|
18
|
+
await entry.job(entry.data);
|
|
19
|
+
} else if (entry.job && typeof entry.job.handle === 'function') {
|
|
20
|
+
entry.job.data = { ...entry.job.data, ...entry.data };
|
|
21
|
+
await entry.job.handle();
|
|
22
|
+
}
|
|
23
|
+
return { success: true, id: entry.id };
|
|
24
|
+
} catch (err) {
|
|
25
|
+
if (entry.attempts <= entry.retries) {
|
|
26
|
+
// Retry with backoff
|
|
27
|
+
entry.availableAt = Date.now() + entry.backoffMs * entry.attempts;
|
|
28
|
+
this.queue._jobs.push(entry);
|
|
29
|
+
return { success: false, retry: true, id: entry.id, error: err.message };
|
|
30
|
+
} else {
|
|
31
|
+
// Log to failed jobs
|
|
32
|
+
this.queue.logFailed(entry, err);
|
|
33
|
+
return { success: false, retry: false, id: entry.id, error: err.message };
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async work({ stopWhenEmpty = false, pollIntervalMs = 50 } = {}) {
|
|
39
|
+
this.isRunning = true;
|
|
40
|
+
this._stopRequested = false;
|
|
41
|
+
|
|
42
|
+
while (!this._stopRequested) {
|
|
43
|
+
const res = await this.processNext();
|
|
44
|
+
if (!res) {
|
|
45
|
+
if (stopWhenEmpty) {
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
await new Promise((r) => setTimeout(r, pollIntervalMs));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
this.isRunning = false;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
stop() {
|
|
56
|
+
this._stopRequested = true;
|
|
57
|
+
}
|
|
58
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { test, describe } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { Queue, Worker, Job } from '../src/index.js';
|
|
4
|
+
|
|
5
|
+
describe('Queue & Background Workers', () => {
|
|
6
|
+
test('dispatches and executes background jobs', async () => {
|
|
7
|
+
const queue = new Queue();
|
|
8
|
+
const worker = new Worker(queue);
|
|
9
|
+
const executed = [];
|
|
10
|
+
|
|
11
|
+
class WelcomeEmailJob extends Job {
|
|
12
|
+
async handle() {
|
|
13
|
+
executed.push(this.data.email);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
queue.dispatch(new WelcomeEmailJob({ email: 'user@example.com' }));
|
|
18
|
+
assert.equal(queue.size(), 1);
|
|
19
|
+
|
|
20
|
+
const res = await worker.processNext();
|
|
21
|
+
assert.equal(res.success, true);
|
|
22
|
+
assert.deepEqual(executed, ['user@example.com']);
|
|
23
|
+
assert.equal(queue.size(), 0);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('retries failed jobs with backoff and records failure', async () => {
|
|
27
|
+
const queue = new Queue();
|
|
28
|
+
const worker = new Worker(queue);
|
|
29
|
+
let attempts = 0;
|
|
30
|
+
|
|
31
|
+
const failingJob = async () => {
|
|
32
|
+
attempts++;
|
|
33
|
+
throw new Error('Connection refused');
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
queue.dispatch(failingJob, {}, { retries: 2, backoffMs: 1 });
|
|
37
|
+
|
|
38
|
+
// Attempt 1: Fails -> queued for retry
|
|
39
|
+
const res1 = await worker.processNext();
|
|
40
|
+
assert.equal(res1.success, false);
|
|
41
|
+
assert.equal(res1.retry, true);
|
|
42
|
+
|
|
43
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
44
|
+
|
|
45
|
+
// Attempt 2: Fails -> queued for retry
|
|
46
|
+
const res2 = await worker.processNext();
|
|
47
|
+
assert.equal(res2.success, false);
|
|
48
|
+
assert.equal(res2.retry, true);
|
|
49
|
+
|
|
50
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
51
|
+
|
|
52
|
+
// Attempt 3: Exceeds retry limit -> moved to failed queue
|
|
53
|
+
const res3 = await worker.processNext();
|
|
54
|
+
assert.equal(res3.success, false);
|
|
55
|
+
assert.equal(res3.retry, false);
|
|
56
|
+
|
|
57
|
+
assert.equal(queue.size(), 0);
|
|
58
|
+
const failedList = queue.getFailed();
|
|
59
|
+
assert.equal(failedList.length, 1);
|
|
60
|
+
assert.equal(failedList[0].error, 'Connection refused');
|
|
61
|
+
});
|
|
62
|
+
});
|
package/README.md
DELETED