UNPKG

redis-smq

Version:

A high-performance, reliable, and scalable message queue for Node.js.

80 lines 2.96 kB
import { CallbackEmptyReplyError, createLogger, PanicError, } from 'redis-smq-common'; import { WorkerAbstract } from '../worker/worker-abstract.js'; import { RedisConnectionPool } from '../../redis/redis-connection-pool/redis-connection-pool.js'; import { ERedisConnectionAcquisitionMode } from '../../redis/redis-connection-pool/types/connection-pool.js'; import { redisKeys } from '../../redis/redis-keys/redis-keys.js'; import { HeartbeatFactory } from '../../heartbeat/heartbeat.js'; export class BackgroundJobWorkerAbstract extends WorkerAbstract { logger; redisClient = null; heartbeat = null; constructor(payload) { super(payload); this.logger = createLogger(payload.config.logger, [ ...payload.loggerContext.namespaces, this.constructor.name, ]); this.logger.debug(`Worker ${this.constructor.name} initialized.`); } setUpHeartbeat = (cb) => { if (!this.redisClient) return cb(new PanicError({ message: 'Redis client is not initialized', })); try { const { keyWorkerHeartbeat } = redisKeys.getWorkerKeys(this.id); this.heartbeat = HeartbeatFactory(this.redisClient, this.logger, { heartbeatKey: keyWorkerHeartbeat, componentId: this.id, componentType: this.constructor.name, }); this.heartbeat.run(cb); } catch (error) { const err = error instanceof Error ? error : new Error(String(error)); cb(err); } }; shutdownHeartbeat = (cb) => { if (this.heartbeat) { return this.heartbeat.shutdown((err) => { this.heartbeat = null; cb(err); }); } cb(); }; goingUp() { return super.goingUp().concat([ (cb) => { RedisConnectionPool.getInstance().acquire(ERedisConnectionAcquisitionMode.SHARED, (err, redisClient) => { if (err) return cb(err); if (!redisClient) return cb(new CallbackEmptyReplyError()); this.redisClient = redisClient; cb(); }); }, this.setUpHeartbeat, ]); } goingDown() { return [ this.shutdownHeartbeat, (cb) => { if (this.redisClient) { RedisConnectionPool.getInstance().release(this.redisClient); this.redisClient = null; } cb(); }, ].concat(super.goingDown()); } getRedisClient() { if (!this.redisClient) throw new PanicError({ message: 'A RedisClient instance is required.' }); return this.redisClient; } } //# sourceMappingURL=background-job-worker-abstract.js.map