redis-smq
Version:
A high-performance, reliable, and scalable message queue for Node.js.
90 lines • 3.44 kB
JavaScript
import { CallbackEmptyReplyError, createLogger, env, Runnable, WorkerCluster, } from 'redis-smq-common';
import { Configuration } from '../../config-manager/configuration.js';
import { RedisConnectionPool } from '../redis/redis-connection-pool/redis-connection-pool.js';
import { ERedisConnectionAcquisitionMode } from '../redis/redis-connection-pool/types/connection-pool.js';
import path from 'path';
import { isMainThread } from 'node:worker_threads';
import { RedisConfig } from '../redis/redis-config.js';
const curDir = env.getCurrentDir();
const workersPath = path.resolve(curDir, 'jobs');
export class BackgroundJobCluster extends Runnable {
static instance = null;
logger;
config;
workerCluster = null;
redisClient = null;
constructor() {
super();
this.config = Configuration.getConfig();
this.logger = createLogger(this.config.logger, [
`${this.constructor.name}-${this.getId()}`,
]);
}
static run(cb) {
if (!isMainThread) {
return cb();
}
if (!BackgroundJobCluster.instance) {
BackgroundJobCluster.instance = new BackgroundJobCluster();
}
BackgroundJobCluster.instance.run(cb);
}
static shutdown(cb) {
if (BackgroundJobCluster.instance) {
BackgroundJobCluster.instance.shutdown(() => {
BackgroundJobCluster.instance = null;
cb();
});
return;
}
cb();
}
goingUp() {
return super.goingUp().concat([
(cb) => {
const redisConnectionPool = RedisConnectionPool.getInstance();
redisConnectionPool.acquire(ERedisConnectionAcquisitionMode.SHARED, (err, redisClient) => {
if (err)
return cb(err);
if (!redisClient)
return cb(new CallbackEmptyReplyError());
this.redisClient = redisClient;
this.workerCluster = new WorkerCluster(redisClient, this.logger, null, '.job.js');
this.workerCluster.on('workerCluster.error', (err) => {
this.logger.error(err);
});
this.workerCluster.loadFromDir(workersPath, {
config: this.config,
redisConfig: RedisConfig.getConfig(),
loggerContext: { namespaces: this.logger.getNamespaces() },
}, (err) => {
if (err)
return cb(err);
this.workerCluster?.run(() => void 0);
cb();
});
});
},
]);
}
goingDown() {
return [
(cb) => {
if (this.workerCluster) {
this.workerCluster.removeAllListeners('workerCluster.error');
this.workerCluster.shutdown(cb);
}
else
cb();
},
(cb) => {
if (this.redisClient) {
RedisConnectionPool.getInstance().release(this.redisClient);
this.redisClient = null;
}
cb();
},
].concat(super.goingDown());
}
}
//# sourceMappingURL=background-job-cluster.js.map