All files queue.js

88.7% Statements 157/177
73.21% Branches 82/112
96.67% Functions 29/30
88.51% Lines 154/174

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 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616                                7x 7x     35x 35x 35x 35x     35x             7x             7x               10x 10x 10x 10x   10x       3x           3x           8x 7x 12x 7x     38x       32x                                                                                                                                 10x 10x 10x 10x 10x 10x 10x 10x     10x 10x 10x 10x 10x 10x 10x 40x   10x       85x                     35x 33x         35x 35x               35x           35x       35x 1x       34x 1x   1x                       1x 1x 33x   2x   2x             2x     31x                       75x             35x   35x 35x                       35x       35x                       26x 26x                 26x 104x   26x 26x     26x 26x     26x 26x     26x 26x             26x     26x     26x     26x       26x                             2x     2x               2x     3x         2x 3x           2x       9x   9x     3x   3x                   3x 3x           3x 2x       2x         2x               9x       26x 26x             26x     26x               26x 26x 26x 2x           2x   24x     2x                 26x 26x   26x 2x                   2x           2x 2x           2x 2x         2x 2x     24x               24x 24x             24x 15x             24x         28x         4x 4x 4x     4x         10x 10x   10x 10x       10x       11x   11x 44x                     11x 11x                     2x   8x     2x   2x 8x 8x   8x     2x       3x         10x 10x   10x    
/**
 * @file src/queue.js
 * @copyright Karim Alibhai. All rights reserved.
 */
 
import { EventEmitter } from 'events'
import * as os from 'os'
 
import createDebug from 'debug'
import { now as microtime } from 'microtime'
import ms from 'ms'
 
import { createRedis } from './redis'
import { createJobProxy } from './runtime'
import { kRedisClient, kTimers } from './symbols'
 
const debug = createDebug('superq')
const isTestEnv = process.env.NODE_ENV === 'test'
 
function buildStackWithError() {
	const error = new Error()
	Error.captureStackTrace(error, buildStackWithError)
	const stack = error.stack.split('\n').slice(1)
	stack.unshift(
		`\nat ${new Date().toISOString()} [${os.hostname()}:${process.pid}]:\n`,
	)
	return stack.join('\n')
}
 
/**
 * JobPriority represents the possible values for the priority of a single
 * enqueued job.
 */
export const JobPriority = {
	Low: 'low',
	Normal: 'normal',
	High: 'high',
	Critical: 'critical',
}
 
const priorityList = [
	JobPriority.Critical,
	JobPriority.High,
	JobPriority.Normal,
	JobPriority.Low,
]
 
function createRedisHash(options) {
	const host = options && options.host ? options.host : 'localhost'
	const port = options && options.port ? options.port : 6379
	const password = options && options.password ? options.password : ''
	const db = options && options.db !== undefined ? options.db : 0
 
	return `redis://_:${password}@${host}:${port}/${db}`
}
 
function createExecutionID(job, data) {
	Iif (typeof job === 'object' && Reflect.has(job, 'getExecutionID')) {
		return job.getExecutionID(data)
	}
 
	// TODO: should use stable stringify, since this can yield
	// different hashes for the same data object
	return Buffer.from(JSON.stringify(data), 'utf8').toString('base64')
}
 
/**
 * Sets up the dependencies for a given job.
 */
const dependenciesKey = ({ name, jobID }) => `dependencies(${name}:${jobID})`
const reverseDependenciesKey = ({ name, jobID }) =>
	`reverseDependencies(${name}:${jobID})`
const jobDataKey = ({ name, jobID }) => `jobData(${name}:${jobID})`
 
function defaultSerializer(data) {
	return Buffer.from(JSON.stringify(data), 'utf8').toString('hex')
}
 
function defaultDeserializer(string) {
	return JSON.parse(Buffer.from(string, 'hex').toString('utf8'))
}
 
export class Queue extends EventEmitter {
	constructor({
		/**
		 * (Required) Name to give to the queue.
		 */
		name,
 
		/**
		 * (Optional) String to prefix to each key stored in redis. Very
		 * useful for debugging.
		 */
		keyPrefix = 'superq:',
 
		/**
		 * (Optional) Override for the name of the redis consumer group.
		 */
		consumerGroup = 'superq-workers',
 
		/**
		 * (Required) Jobs object containing jobs that should be registered
		 * to this queue.
		 */
		jobs,
 
		/**
		 * (Optional) Redis connection options - passed straight to ioredis.
		 */
		redis,
 
		/**
		 * (Optional) The default priority of an enqueued job.
		 * This priority can be overriden by the job implementation.
		 */
		defaultPriority = JobPriority.Normal,
 
		/**
		 * (Optional) The default number of times to retry a failed job.
		 * This number can be overriden by the job implementation.
		 */
		defaultRetryAttempts = 1,
 
		/**
		 * (Optional) Serialize is the function to be used to serialize
		 * job parameters from an object into a string.
		 */
		serialize = defaultSerializer,
 
		/**
		 * (Optional) Deserialize is the function to be used to deserialize
		 * job parameters from a string into an object.
		 */
		deserialize = defaultDeserializer,
 
		/**
		 * (Default: true) If true, superq will write some basic logs to stdout
		 * to signal major events such as jobs starting and jobs ending.
		 */
		enableEventLogs = true,
 
		// Dependency injection for tests
		[kTimers]: timers,
	} = {}) {
		super()
		this.keyPrefix = keyPrefix
		this.queueName = name
		this.delayedQueueName = this.getKey(`delayed:${name}`)
		this.redis = null
		this.redisConnectionHash = createRedisHash(redis)
		this.consumerGroup = consumerGroup
		Iif (typeof jobs !== 'object' || jobs === null) {
			throw new Error(`Jobs object is required when creating a queue instance`)
		}
		this.jobs = new Map(Object.entries(jobs))
		this.timers = (isTestEnv ? timers : null) || global
		this.serializeData = serialize
		this.deserializeData = deserialize
		this.defaultPriority = defaultPriority
		this.defaultRetryAttempts = defaultRetryAttempts
		this.xstreams = priorityList.map(priority => {
			return this.getQueueName(priority)
		})
		this.enableEventLogs = enableEventLogs
	}
 
	getKey(key) {
		return this.keyPrefix + key
	}
 
	getJobByName(name) {
		return this.jobs.get(name)
	}
 
	/**
	 * Enqueues a job into the queue.
	 */
	async Enqueue(name, data, options = {}) {
		if (!options.callerStack) {
			options.callerStack = buildStackWithError()
		}
 
		// grab the job implementation
		const job =
			name === 'markJobAsDone' ? this.markJobAsDone : this.jobs.get(name)
		Iif (!job) {
			throw new Error(
				`There exists no registered job in this queue with the name: '${name}'`,
			)
		}
 
		// figure out priority
		const priority =
			typeof job === 'object' && Reflect.has(job, 'getPriority')
				? job.getPriority(data)
				: this.defaultPriority
 
		// figure out max attempts
		const maxAttempts =
			typeof job === 'object' && Reflect.has(job, 'getAttempts')
				? job.getAttempts(data)
				: this.defaultRetryAttempts
 
		if (Reflect.has(options, 'delay') && Reflect.has(options, 'dependencies')) {
			throw new Error(`Jobs cannot be both delayed and have dependencies`)
		}
 
		// if job is delayed, enqueue it for later
		if (options.delay !== undefined) {
			const execID = createExecutionID(job, data)
 
			await this.redis.zadd(
				this.delayedQueueName,
				String(this.timers.Date.now() + options.delay),
				this.serializeData({
					name,
					data,
					priority,
					maxAttempts,
					callerStack: options.callerStack,
				}),
			)
 
			debug(`Enqueued ${name}:${execID} for ${options.delay}ms from now`)
			return { name, jobID: execID }
		} else if (options.dependencies && options.dependencies.length > 0) {
			// setup dependencies, if the job has any
			const execID = createExecutionID(job, data)
 
			await this.setupJobDependencies({
				name,
				data,
				execID,
				dependencies: options.dependencies,
				callerStack: options.callerStack,
			})
			return { name, jobID: execID }
		}
 
		return this.addJobToQueue(
			{
				name,
				data,
				priority,
				maxAttempts,
			},
			options,
		)
	}
 
	getQueueName(priority) {
		return this.getKey(`${this.queueName}:${priority}`)
	}
 
	/**
	 * Adds a job object to a stream.
	 */
	async addJobToQueue(job, options) {
		try {
			// add the job into the queue
			const serializedData = this.serializeData(job.data)
			const jobID = await this.redis.xadd(
				this.getQueueName(job.priority),
				'*',
				'name',
				job.name,
				'data',
				serializedData,
				'maxAttempts',
				String(job.maxAttempts),
				'callerStack',
				options.callerStack,
			)
			debug(`Enqueued ${job.name}:${jobID} with => %O`, {
				data: job.data,
				options,
			})
			return { name: job.name, jobID }
		} catch (error) {
			if (!String(error).includes('NOGROUP')) {
				throw error
			}
 
			await this.createJobStreams()
			return this.addJobToQueue(job, options)
		}
	}
 
	async ackJob(entry) {
		await this.redis.xack(entry.queueName, this.consumerGroup, entry.ID)
		await this.redis.xdel(entry.queueName, entry.ID)
	}
 
	parseDictionary(jobID, res) {
		let name
		let data
		let maxAttempts
		let callerStack
 
		for (let i = 0; i < res.length; i += 2) {
			switch (res[i]) {
				case 'name':
					name = res[i + 1]
					break
 
				case 'data':
					data = this.deserializeData(res[i + 1])
					break
 
				case 'maxAttempts':
					maxAttempts = parseInt(res[i + 1], 10)
					break
 
				case 'callerStack':
					callerStack = res[i + 1]
					break
 
				default:
					throw new Error(`Unexpected key in job entry: ${res[i]}`)
			}
		}
 
		Iif (!name) {
			throw new Error(`Job entry for ${jobID} was missing name`)
		}
		Iif (!data) {
			throw new Error(`Job entry for ${jobID} was missing data`)
		}
		Iif (!maxAttempts) {
			throw new Error(`Job entry for ${jobID} was missing maxAttempts`)
		}
		Iif (!callerStack) {
			throw new Error(`Job entry for ${jobID} was missing callerStack`)
		}
 
		return {
			data,
			maxAttempts,
			callerStack,
			name,
		}
	}
 
	async setupJobDependencies({
		name,
		data,
		execID,
		dependencies,
		callerStack,
	}) {
		const goals = []
 
		// Push data onto redis
		goals.push(
			this.redis.set(
				jobDataKey({ name, jobID: execID }),
				this.serializeData({ data, callerStack }),
			),
		)
 
		// Create a record of dependencies for this job
		goals.push(
			this.redis.sadd(
				dependenciesKey({ name, jobID: execID }),
				...dependencies.map(d => `${d.name}:${d.jobID}`),
			),
		)
 
		// Append to existing reverse records of jobs
		for (const dep of dependencies) {
			goals.push(
				this.redis.sadd(reverseDependenciesKey(dep), `${name}:${execID}`),
			)
		}
 
		// Wait for all redis commands to resolve
		await Promise.all(goals)
	}
 
	async markJobAsDone({ name, jobID }) {
		const goals = []
 
		for (const dependent of await this.redis.smembers(
			reverseDependenciesKey({ name, jobID }),
		)) {
			const [depName, depID] = dependent.split(':')
 
			goals.push(
				this.redis
					.multi()
					.srem(
						dependenciesKey({ name: depName, jobID: depID }),
						`${name}:${jobID}`,
					)
					.scard(dependenciesKey({ name: depName, jobID: depID }))
					.exec()
					.then(async res => {
						const card = res[1][1]
						debug(
							`Reached cardinality of %O for ${depName}:${depID} (reply => %O)`,
							card,
							res,
						)
 
						if (card === 0) {
							Iif (!this.jobs.has(depName)) {
								throw new Error(`Could not find dependent job: ${depName}`)
							}
 
							const { data, callerStack } = this.deserializeData(
								(await this.redis.get(
									jobDataKey({ name: depName, jobID: depID }),
								)) || '',
							)
							return this.Enqueue(depName, data, {
								callerStack,
							})
						}
					}),
			)
		}
 
		await Promise.all(goals)
	}
 
	async executeJobEntry(entry) {
		Eif (this.enableEventLogs) {
			console.log(
				`Job ${entry.name}:${entry.ID} starting from ${entry.queueName}`,
			)
		}
 
		// grab the job implementation
		const job =
			entry.name === 'markJobAsDone'
				? this.markJobAsDone.bind(this, entry.data)
				: this.jobs.get(entry.name)
		Iif (!job) {
			throw new Error(
				`Job ${entry.ID} referenced a non-existent job: ${entry.name}`,
			)
		}
 
		// execute the job
		let jobError
		const timeOfJobStart = microtime()
		try {
			if (typeof job === 'object') {
				Iif (!Reflect.has(job, 'run')) {
					throw new Error(
						`Job ${entry.name} is an object but does not have a run method`,
					)
				}
 
				await job.run(entry.data)
			} else {
				await job(entry.data)
			}
		} catch (err) {
			jobError = {
				message: err.message,
				stack:
					err.stack + '\n' + buildStackWithError() + '\n' + entry.callerStack,
			}
		}
 
		// mark end of the job by grabbing the time & incrementing the
		// attempts
		const duration = microtime() - timeOfJobStart
		++entry.attempted
 
		if (jobError) {
			const jobErrorEvent = {
				...jobError,
				queue: this.queueName,
				name: entry.name,
				data: entry.data,
				jobID: entry.ID,
				duration,
				attempt: entry.attempted,
			}
 
			Iif (!this.emit('jobError', jobErrorEvent)) {
				console.error(
					`Job ${entry.name}:${entry.ID} failed after ${ms(duration / 1e3)}: ${
						jobError.stack
					}`,
				)
			} else Eif (this.enableEventLogs) {
				console.error(
					`Job ${entry.name}:${entry.ID} failed after ${ms(duration / 1e3)}`,
				)
			}
 
			// If we have exceeded the max number of attempts, clear the job
			Eif (entry.attempted >= entry.maxAttempts) {
				debug(
					`Job ${entry.name}:${entry.ID} exceeded maxAttempts` +
						`(${entry.maxAttempts})`,
				)
 
				this.emit('jobFatalError', jobErrorEvent)
				await this.ackJob(entry)
			}
		} else {
			this.emit('jobEnd', {
				queue: this.queueName,
				name: entry.name,
				data: entry.data,
				jobID: entry.ID,
				duration,
				attempt: entry.attempted,
			})
			Eif (this.enableEventLogs) {
				console.log(
					`Job ${entry.name}:${entry.ID} finished after ${ms(duration / 1e3)}`,
				)
			}
 
			// Queue up a signal to resolve dependencies - for all jobs
			// except the `markJobAsDone` job
			if (entry.name !== 'markJobAsDone') {
				await this.Enqueue('markJobAsDone', {
					name: entry.name,
					jobID: entry.ID,
				})
			}
 
			// If we have completed successfully, clear the job out instead of acknowledging it
			await this.ackJob(entry)
		}
	}
 
	async shiftDelayedJobs() {
		for (const jobStr of await this.redis.zrangebyscore(
			this.delayedQueueName,
			0,
			this.timers.Date.now(),
		)) {
			const job = this.deserializeData(jobStr)
			debug(`Moving ${job.name} from delayed queue into priority queue`)
			await this.addJobToQueue(job, {
				callerStack: job.callerStack,
			})
			await this.redis.zrem(this.delayedQueueName, jobStr)
		}
	}
 
	async initQueue({ redis, [kRedisClient]: testRedisClient }) {
		Eif (isTestEnv) {
			this.redis = testRedisClient
		}
		this.redis = this.redis || (await createRedis(redis))
		Iif (!this.redis) {
			throw new Error(`Redis client is required to create a queue instance`)
		}
 
		return this.createJobStreams()
	}
 
	async createJobStreams() {
		const goals = []
 
		for (const stream of this.xstreams) {
			goals.push(
				this.redis.xgroup(
					'create',
					stream,
					this.consumerGroup,
					'0',
					'mkstream',
				),
			)
		}
 
		try {
			await Promise.all(goals)
		} catch (err) {
			if (
				!String(err).includes('BUSYGROUP Consumer Group name already exists')
			) {
				throw err
			}
		}
	}
 
	async size() {
		const info = await Promise.all(
			this.xstreams.map(stream => {
				return this.redis.sendCommand('XINFO', ['STREAM', stream])
			}),
		)
		let totalSize = 0
 
		for (const queueInfo of info) {
			const lengthLocation = queueInfo.findIndex(field => {
				return field === 'length'
			})
			totalSize += Number(queueInfo[lengthLocation + 1])
		}
 
		return totalSize
	}
 
	destroy() {
		return this.redis.close()
	}
}
 
export async function createQueue(options) {
	const queue = new Queue(options)
	await queue.initQueue(options)
 
	return createJobProxy(queue)
}