All files worker.js

65.65% Statements 86/131
54.72% Branches 29/53
38.89% Functions 7/18
65.38% Lines 85/130

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365                          7x 7x                                               9x 9x 9x 9x 9x 9x 9x 9x 9x 9x   9x         9x 10x 10x       10x 9x 9x 9x 1x       1x           10x 40x 40x     10x 10x 10x     9x 9x 40x         26x               26x 26x 26x       26x 26x   26x                                 5x   5x 28x         28x             28x                                                                                                       5x       5x 5x 28x   5x             33x   33x                     32x 9x 4x     5x 5x             5x     5x     23x 23x 26x 26x 26x                                 23x   1x 1x                 28x 28x 28x 27x 4x 4x 4x 4x     23x 23x 26x           23x   23x 23x   1x       1x 1x   1x                               3x 5x                                                                                          
/**
 * @file src/worker.js
 * @copyright Karim Alibhai. All rights reserved.
 */
 
import { performance } from 'perf_hooks'
 
import createDebug from 'debug'
import { v4 as uuid } from 'uuid'
 
import { Queue } from './queue'
import { kQueue, kTimers, kWorker } from './symbols'
 
const debug = createDebug('superq')
const isTestEnv = process.env.NODE_ENV === 'test'
 
export class Worker {
	constructor({
		consumerID,
		queues,
 
		/**
		 * (Optional) Amount of time to wait in milliseconds before
		 * retrying a failed job.
		 */
		retryTimeout = 10000,
 
		/**
		 * (Optional) Amount of time to wait in milliseconds before
		 * assuming there are no jobs available in the queue. This will
		 * be the minimum amount of time a worker will exit after receiving
		 * a SIGINT.
		 */
		readTimeout = 5000,
 
		// Dependency injection for tests
		[kTimers]: timers = global,
	} = {}) {
		this.queues = new Set()
		this.queuesByName = new Map()
		this.queueNames = []
		this.delayedQueueNames = []
		this.xreadStreams = []
		this.consumerID = consumerID || uuid()
		this.retryTimeout = retryTimeout
		this.readTimeout = readTimeout
		this.timers = isTestEnv ? timers : global
		this.shouldRun = false
 
		Iif (!Array.isArray(queues)) {
			throw new Error(`Queues must be an array of queue objects`)
		}
 
		let redisConnectionHash
		for (const queue of queues) {
			const queueHandle = queue[kQueue]
			Iif (!(queueHandle instanceof Queue)) {
				throw new Error(`Queues must be an array of queue objects`)
			}
 
			if (!redisConnectionHash) {
				redisConnectionHash = queueHandle.redisConnectionHash
				this.redis = queueHandle.redis
				this.consumerGroup = queueHandle.consumerGroup
			} else Iif (redisConnectionHash !== queueHandle.redisConnectionHash) {
				throw new Error(
					`All queues in the worker should be connected to the same redis db`,
				)
			} else Iif (this.consumerGroup !== queueHandle.consumerGroup) {
				throw new Error(
					`All queues in the worker should be part of the same consumer group`,
				)
			}
 
			for (const xstream of queueHandle.xstreams) {
				this.xreadStreams.push(xstream)
				this.queuesByName.set(xstream, queueHandle)
			}
 
			this.queues.add(queueHandle)
			this.queueNames.push(queueHandle.queueName)
			this.delayedQueueNames.push(queueHandle.delayedQueueName)
		}
 
		const numStreams = this.xreadStreams.length
		for (let i = 0; i < numStreams; ++i) {
			this.xreadStreams.push('>')
		}
	}
 
	parseJobEntry(res) {
		Iif (res.length + 0 !== 2) {
			throw new Error(
				`Unexpected number of items returned to XReadGroup (expected 2): ${JSON.stringify(
					res,
				)}`,
			)
		}
 
		const queueName = res[0]
		const queue = this.queuesByName.get(queueName)
		Iif (!queue) {
			throw new Error(`No such queue exists: '${queueName}'`)
		}
 
		const jobID = res[1][0][0]
		const jobData = queue.parseDictionary(jobID, res[1][0][1])
 
		return {
			ID: jobID,
			age: 0,
			attempted: 0,
			data: jobData.data,
			maxAttempts: jobData.maxAttempts,
			name: jobData.name,
			callerStack: jobData.callerStack,
			queue,
			queueName,
		}
	}
 
	/**
	 * Retrieves a single claimed job from a redis PEL for execution.
	 */
	async popPendingJob(count) {
		const entries = []
 
		for (const [queueName, queue] of this.queuesByName.entries()) {
			Iif (entries.length >= count) {
				break
			}
 
			const [res] =
				(await this.redis.xpending(
					queueName,
					this.consumerGroup,
					'-',
					'+',
					String(count),
				)) || []
			Iif (res) {
				const jobID = res[0]
				const lastConsumer = res[1]
				const attempted = res[3]
 
				debug(`Trying to xclaim ${jobID} from ${lastConsumer} in ${queueName}`)
				const [claimInfo] =
					(await this.redis.xclaim(
						queueName,
						this.consumerGroup,
						this.consumerID,
						this.retryTimeout,
						jobID,
						'RETRYCOUNT',
						String(attempted + 1),
					)) || []
				if (claimInfo) {
					const jobData = queue.parseDictionary(claimInfo[0], claimInfo[1])
					debug(
						`JobInfo => %O`,
						await this.redis.xpending(
							queueName,
							this.consumerGroup,
							'-',
							'+',
							String(count),
						),
					)
 
					entries.push({
						ID: jobID,
						age: res[2],
						attempted,
						data: jobData.data,
						maxAttempts: jobData.maxAttempts,
						name: jobData.name,
						callerStack: jobData.callerStack,
						queueName,
						queue: this.queuesByName.get(queueName),
					})
				} else {
					if (isTestEnv) {
						throw new Error(
							`Could not claim ${jobID} from ${lastConsumer} in ${queueName}`,
						)
					}
 
					debug(`Could not claim ${jobID} from ${lastConsumer} in ${queueName}`)
				}
			}
		}
 
		return entries
	}
 
	async shiftDelayedJobs() {
		const goals = []
		for (const queue of this.queuesByName.values()) {
			goals.push(queue.shiftDelayedJobs())
		}
		await Promise.all(goals)
	}
 
	/**
	 * Retrieves one job from redis for execution.
	 */
	async popJob(count, tryPending = true) {
		try {
			const res =
				(await this.redis.xreadgroup(
					'GROUP',
					this.consumerGroup,
					this.consumerID,
					'BLOCK',
					String(this.readTimeout),
					'COUNT',
					String(count),
					'STREAMS',
					...this.xreadStreams,
				)) || []
			if (res.length === 0) {
				if (!tryPending) {
					return []
				}
 
				const pendingJobs = await this.popPendingJob(count)
				Iif (pendingJobs.length > 0) {
					return pendingJobs
				}
 
				// If we failed to grab any pending jobs either, go ahead
				// and initiate a shift on the delayed queue to make more work
				// available
				await this.shiftDelayedJobs()
 
				// Try once more to get a job off the queue
				return this.popJob(count, false)
			}
 
			const entries = []
			for (const result of res) {
				try {
					const entry = this.parseJobEntry(result)
					entries.push(entry)
				} catch (err) {
					console.error(`Failed to parse job entry: %O`, err, result)
 
					const queue = this.queuesByName.get(result[0])
					if (!queue) {
						throw new Error(`No queue found by name: '${result[0]}'`)
					}
 
					await queue.ackJob({
						ID: result[1][0][0],
						name: 'unknown',
						queueName: result[0],
					})
				}
			}
 
			return entries
		} catch (err) {
			Eif (isTestEnv) {
				throw err
			}
 
			console.error(`Failed to retrieve jobs from redis`, err)
			return []
		}
	}
 
	async tick() {
		try {
			performance.mark('startWorkerTick')
			const entries = await this.popJob(1)
			if (entries.length === 0) {
				debug(`Read nothing from any job stream`)
				performance.mark('stopWorkerTick')
				performance.measure('worker tick', 'startWorkerTick', 'stopWorkerTick')
				return []
			}
 
			const goals = []
			for (const entry of entries) {
				goals.push(
					entry.queue.executeJobEntry(entry).catch(() => {
						// TODO: Log error for monitoring
					}),
				)
			}
			await Promise.all(goals)
 
			performance.mark('stopWorkerTick')
			performance.measure('worker tick', 'startWorkerTick', 'stopWorkerTick')
		} catch (error) {
			Iif (!String(error).includes('NOGROUP')) {
				throw error
			}
 
			for (const queue of this.queues) {
				await queue.createJobStreams()
			}
			return this.tick()
		}
	}
 
	async process() {
		this.shouldRun = true
		while (this.shouldRun) {
			await this.tick()
		}
	}
 
	async shutdown() {
		this.shouldRun = false
	}
 
	on(event, handler) {
		for (const queue of this.queues) {
			queue.on(event, handler)
		}
	}
 
	off(event, handler) {
		for (const queue of this.queues) {
			queue.off(event, handler)
		}
	}
}
 
export class WorkerHandle {
	constructor(options) {
		this[kWorker] = new Worker(options)
		this.concurrency =
			options.concurrency === undefined ? 1 : options.concurrency
	}
 
	on(event, handler) {
		this[kWorker].on(event, handler)
		return this
	}
 
	off(event, handler) {
		this[kWorker].off(event, handler)
		return this
	}
 
	run() {
		return Promise.all(
			[...new Array(this.concurrency)].map(() => {
				return this[kWorker].process()
			}),
		)
	}
 
	start() {
		this.runner = this.run()
	}
 
	async stop() {
		await this[kWorker].shutdown()
		return this.runner
	}
}