node-sidekiq-client
Version:
Sidekiq client for nodejs
122 lines (121 loc) • 5.2 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SidekiqClient = void 0;
// src/index.ts
const redis_1 = require("redis");
const crypto_1 = require("crypto");
class SidekiqClient {
/**
* Initialize SidekiqClient.
*
* @param redisUrlOrClient - Redis connection URL (string) or a RedisClientType/RedisClientPoolType instance.
*/
constructor(redisUrlOrClient) {
if (typeof redisUrlOrClient === 'string') {
// create a new client from URL
this.redis = (0, redis_1.createClient)({ url: redisUrlOrClient });
// auto-connect
this.redis.connect().catch((err) => {
throw new Error(`Failed to connect to Redis: ${err}`);
});
}
else {
this.redis = redisUrlOrClient;
}
}
/**
* Enqueue a job for immediate asynchronous processing.
*
* @param queue - Name of the queue.
* @param jobClass - Name of the job class.
* @param args - Array of job arguments.
* @param options - Additional options (e.g., retry settings, metadata).
* @returns The JID (24-character hex string).
*/
performAsync(queue_1, jobClass_1, args_1) {
return __awaiter(this, arguments, void 0, function* (queue, jobClass, args, options = {}) {
const job = this.buildJobPayload(queue, jobClass, args, options, true);
// lpush "queue:<queue>" "<JSON>"
yield this.redis.lPush(`queue:${queue}`, JSON.stringify(job));
return job.jid;
});
}
/**
* Schedule a job to run after a delay (in miliseconds).
*
* @param msFromNow - Delay (in miliseconds) before job should run.
* @param queue - Name of the queue.
* @param jobClass - Name of the job class.
* @param args - Array of job arguments.
* @param options - Additional options.
* @returns The JID (24-character hex string).
*/
performIn(msFromNow_1, queue_1, jobClass_1, args_1) {
return __awaiter(this, arguments, void 0, function* (msFromNow, queue, jobClass, args, options = {}) {
const timestamp = Date.now() + msFromNow;
return this.zaddScheduled(queue, jobClass, args, timestamp, options);
});
}
/**
* Schedule a job to run at a specific Unix timestamp.
*
* @param unixTimestamp - When the job should run (miliseconds since epoch).
* @param queue - Name of the queue.
* @param jobClass - Name of the job class.
* @param args - Array of job arguments.
* @param options - Additional options.
* @returns The JID (24-character hex string).
*/
performAt(unixTimestamp_1, queue_1, jobClass_1, args_1) {
return __awaiter(this, arguments, void 0, function* (unixTimestamp, queue, jobClass, args, options = {}) {
// Ensure the timestamp is in seconds, sidekiq uses seconds.fraction
// but node and most peaople programin in node use milliseconds
const timestampInSeconds = unixTimestamp / 1000;
return this.zaddScheduled(queue, jobClass, args, timestampInSeconds, options);
});
}
/**
* Internal: add a scheduled job to the "schedule" sorted set.
*/
zaddScheduled(queue, jobClass, args, timestamp, options) {
return __awaiter(this, void 0, void 0, function* () {
const job = this.buildJobPayload(queue, jobClass, args, options, false);
// zAdd "schedule" { score: timestamp, value: JSON.stringify(job) }
// In Redis v4, zAdd takes an array of { score, value } or a single object
yield this.redis.zAdd('schedule', {
score: timestamp,
value: JSON.stringify(job)
});
return job.jid;
});
}
/**
* Build the job payload (same fields as Python version).
*/
buildJobPayload(queue, jobClass, args, options, includeEnqueued) {
const now = Date.now() / 1000; // seconds.fraction
const jid = (0, crypto_1.randomBytes)(12).toString('hex'); // 24 hex chars
const base = {
class: jobClass,
queue,
args,
jid,
created_at: now
};
if (includeEnqueued) {
base.enqueued_at = now;
}
// Merge any extra options on top of base
return Object.assign(Object.assign({}, base), options);
}
}
exports.SidekiqClient = SidekiqClient;