knock-mq
Version:
Production-grade message queue implementation.
75 lines • 2.13 kB
JavaScript
import { Queue } from './queue.js';
export class QueueInstance {
config;
queue;
processor;
running = false;
pollInterval = 1000;
constructor(config) {
this.config = config;
this.queue = new Queue({
...config,
storage: config.storage
});
}
useProcessor(fn) {
this.processor = fn;
}
async enqueue(data, opts) {
return this.queue.enqueue(data, opts);
}
async enqueueOnce(id, data, opts) {
return this.config.storage.enqueueOnce(id, data, {
priority: opts?.priority || 'normal',
metadata: {
attempts: 0,
status: 'queued',
queuedAt: new Date(),
...(opts?.expiresAt ? { expiresAt: opts.expiresAt } : {})
}
});
}
async getDeadLetters(limit = 50) {
return this.config.storage.getDeadLetterItems(limit);
}
async pause() {
return this.config.storage.pause();
}
async resume() {
return this.config.storage.resume();
}
async isPaused() {
return this.config.storage.isPaused();
}
async start() {
if (!this.processor)
throw new Error('No processor attached');
this.running = true;
const { storage } = this.config;
const loop = async () => {
if (!this.running)
return;
if (await storage.isPaused()) {
setTimeout(loop, this.pollInterval);
return;
}
const items = await storage.dequeue(this.config.maxConcurrent);
for (const item of items) {
void this.queue.processItem(item, this.processor);
}
setTimeout(loop, this.pollInterval);
};
loop();
}
stop() {
this.running = false;
}
async getStats() {
return this.queue.getStats();
}
async getStatus(id) {
const item = await this.config.storage.getItem(id);
return item?.metadata.status || null;
}
}
//# sourceMappingURL=api.js.map