Skip to content

bay ​

@c9up/bay: background jobs: job classes dispatched onto named queues and run by a worker, with memory and Redis drivers behind one driver contract. Guide: Queues.

Installation ​

bash
pnpm add @c9up/bay

ream configure @c9up/bay registers the provider and the @c9up/bay/commands commands, writes config/queue.ts and adds QUEUE_DRIVER=memory to .env with its validation rule. The Redis driver needs @c9up/quasar (an optional peer) when it names a connection.

Entry points ​

ImportContents
@c9up/bayJob, QueueManager, dispatchers, defineConfig, drivers, the two drivers, backoff helpers, errors, types
@c9up/bay/providerBayProvider (default export)
@c9up/bay/services/mainThe booted QueueManager (default export), setQueue, getQueue, clearQueue
@c9up/bay/testingFakeQueue
@c9up/bay/commandsThe queue:work and make:job commands
@c9up/bay/configureconfigure(codemods), run by ream configure

Exports ​

@c9up/bay ​

ExportKindDescription
JobclassAbstract base of a job class: execute(), optional failed(error), static options, static dispatch() / dispatchMany().
QueueManagerclassDispatches jobs, runs the worker loop, answers lookups and sizes.
JobDispatcherclassFluent builder returned by Job.dispatch(); awaiting it sends the job.
JobBatchDispatcherclassFluent builder returned by Job.dispatchMany().
defineConfigfunctiondefineConfig<T extends BayProviderConfig>(config: T): T: types config/queue.ts.
driversconstAdapter factories: memory(), redis(options).
storesconstThe same object as drivers, under its older name.
MemoryDriverclassIn-process driver; jobs do not survive a restart. new MemoryDriver(options?: { maxFailedJobs?: number }), 1000 failed jobs kept by default.
RedisDriverclassRedis driver with visibility leases and stalled-job recovery. new RedisDriver(source: RedisClientSource, options?: RedisDriverOptions).
quasarConnectionfunctionquasarConnection(name?: string): () => Promise<RedisClient>: a client source that loads a @c9up/quasar connection on first use.
BackoffStrategyclassComputes retry delays: calculateDelay(attempt), getNextRetryAt(attempt), getConfig().
exponentialBackofffunctionexponentialBackoff(config?): BackoffFactory; defaults baseDelay: '1s', maxDelay: '5m', multiplier: 2, jitter: true.
linearBackofffunctionlinearBackoff(config?): BackoffFactory; defaults baseDelay: '5s', maxDelay: '2m'.
fixedBackofffunctionfixedBackoff(delay?: Duration): BackoffFactory; default '10s'.
customBackofffunctioncustomBackoff(config: BackoffConfig): BackoffFactory.
errorsnamespaceThe package's errors, one class per code, see Errors
jobNameOffunctionjobNameOf(job: JobClass): string: options.name, else the class name.
isJobClassfunctionisJobClass(value: unknown): value is JobClass.
queueOffunctionqueueOf(job: JobRecord): string: the record's queue, 'default' when it has none.
DEFAULT_QUEUEconst'default'.
DEFAULT_PRIORITYconst5.
Durationtypenumber | string: milliseconds, or '500ms', '10s', '1m', '2h', '1d'.
JobOptionsinterfaceThe static options of a job class (see below).
JobRetentiontypeboolean | { age?: Duration; count?: number }.
JobContextinterface{ jobId; name; attempt; queue; priority; acquiredAt: Date; stalledCount }, all readonly.
JobClassinterfaceA constructor of Job<Payload> with name and optional options.
DispatchResultinterface{ jobId: string }.
DispatchManyResultinterface{ jobIds: string[] }.
DispatchOptionsinterfaceJobOptions without name, plus dedup?: { id: string; ttl?: Duration; extend?: boolean } and maxAttempts?: number.
WorkerOptionsinterface{ idleDelay?; stalledInterval?; concurrency?; queues?; unknownJobRetries? }.
QueueDriverinterfaceThe driver contract: push, pop, fail, complete, retry, failed, size; optional sizeOf, getJob, recoverStale, renew, renewIntervalMs. recoverStale() answers a StaleRecovery, or the recovered count alone for a driver that never fails a job for stalling.
StaleRecoveryinterface{ recovered: number; failed: Array<{ job: JobRecord; error: Error }> }: what one stall sweep did. failed lists the jobs it filed as failed for stalling too often, each with the error their failed() hook receives.
JobRecordinterfaceA job as stored: id, name, payload, attempts, maxAttempts, status, createdAt, queue?, runAt?, priority?…
JobStatustype'pending' | 'active' | 'delayed' | 'completed' | 'failed'.
JobLookupinterface{ status: JobStatus; data: JobRecord; finishedAt?: number; error?: string }.
JobHandlerinterface{ handle(payload: unknown, signal: AbortSignal, context?: JobContext): Promise<void> }.
HandlerRegistrationtypeJobHandler | Constructor<JobHandler>.
JobFactorytype(jobClass: Constructor) => unknown: builds job and handler classes.
Constructortypenew (...args: never[]) => T.
QueueManagerOptionsinterface{ jobFactory?: JobFactory }.
AdapterFactorytype() => QueueDriver.
QueueStoreFactorytypeSame as AdapterFactory.
BackoffConfiginterface{ strategy: 'exponential' | 'linear' | 'fixed'; baseDelay: Duration; maxDelay?: Duration; multiplier?: number; jitter?: boolean }.
ResolvedBackoffinterfaceBackoffConfig with the delays in milliseconds.
BackoffFactorytype() => BackoffStrategy.
RedisClientinterfaceThe commands the Redis driver sends (evalsha, script, rpush, zadd, lrange…).
RedisClientSourcetypeRedisClient | (() => RedisClient | Promise<RedisClient>).
RedisDriverOptionsinterface{ prefix?: string; visibilityTimeoutMs?: number; maxStalledCount?: number; maxFailedJobs?: number }.
BayProviderConfiginterfaceThe shape of config/queue.ts (see Configuration).
BayAppContext / BayContainer / BayConfigStoreinterfaceThe host the provider needs.

@c9up/bay/provider ​

ExportKindDescription
default (BayProvider)providerregister() binds the QueueManager built from the queue config, with the container's make as job factory; boot() seats it on services/main; ready() imports every job class under locations and registers it; shutdown() stops the worker.

@c9up/bay/services/main ​

ExportKindDescription
defaultconstThe booted QueueManager; a member read before boot throws. Job.dispatch() sends through it.
setQueuefunctionsetQueue(value: QueueManager): void.
getQueuefunctiongetQueue(): QueueManager | undefined.
clearQueuefunctionclearQueue(): void.

@c9up/bay/testing ​

ExportKindDescription
FakeQueueclassA QueueDriver that records pushes and never runs them.
FakeQueuePredicateinterface{ payloadMatches?: (payload: unknown) => boolean }.
FakeQueuePredicateArgtypeFakeQueuePredicate | ((job: JobRecord) => boolean).

@c9up/bay/commands ​

CommandArguments and flagsDescription
queue:work--queue <names> (comma-separated, in order), --concurrency <n>Boots the app and processes jobs until the process is stopped.
make:job<name> (may hold a subdirectory)Writes a job class in the first configured location.

The module also exports getMetaData(), getCommand(metadata) (the command loader contract) and the BayCommandClass type.

Job ​

ts
export default class SendEmail extends Job<{ to: string }> {
  static options = { queue: 'emails', maxRetries: 5 }
  async execute() { /* this.payload, this.signal, this.context */ }
}
MemberSignatureDescription
optionsstatic options: JobOptionsDefaults of every dispatch of this class.
dispatchstatic dispatch<Payload>(payload: Payload): JobDispatcher<Payload>Queue one job.
dispatchManystatic dispatchMany<Payload>(payloads: readonly Payload[]): JobBatchDispatcher<Payload>Queue one job per payload.
payloadreadonly payload: PayloadThe dispatched payload.
signalreadonly signal: AbortSignalAborts when the attempt's timeout passes.
contextreadonly context: JobContextId, attempt, queue, priority of this attempt.
executeabstract execute(): Promise<void> | voidThe work.
failedfailed?(error: Error): Promise<void> | voidCalled once the last attempt failed: with E_JOB_MAX_ATTEMPTS_REACHED (the attempt's error as cause) once retries ran out, with the attempt's own error when maxAttempts is 1 or failOnTimeout ended it, with E_JOB_STALLED when the job stalled more than maxStalledCount times.

JobOptions ​

OptionTypeDefaultDescription
namestringclass nameThe name a worker resolves the record by.
queuestring'default'Queue the job waits in.
prioritynumber51 to 10, lower runs first.
maxRetriesnumber3How many times the handler may run.
delayDurationnoneHold the job back before a worker may take it.
retry{ maxRetries?: number; backoff?: BackoffFactory }noneRetry count and delay between attempts.
timeoutDurationnonePer-attempt limit; 0 means none; at most about 24.8 days.
failOnTimeoutbooleanfalseFail at once on a timeout instead of retrying.
removeOnCompleteJobRetentionremovedKeep completed jobs: false keeps all, { age, count } bounds them.
removeOnFailJobRetentionremovedSame for failed jobs.

JobDispatcher and JobBatchDispatcher ​

Both are PromiseLike: await sends.

MemberSignatureDescription
toQueuetoQueue(queue: string): thisSend to this queue instead of the class's.
inin(delay: Duration): thisDelay the job (JobDispatcher only).
prioritypriority(priority: number): this1 to 10, lower runs first.
dedupdedup(options: { id: string; ttl?: Duration; extend?: boolean }): thisQueue only if no job of the same class holds this id (JobDispatcher only).
runrun(): Promise<DispatchResult> / Promise<DispatchManyResult>Send explicitly.

QueueManager ​

new QueueManager(driver: QueueDriver, workerDefaults?: WorkerOptions, options?: QueueManagerOptions).

MemberSignatureDescription
registerregister(name: string, handler: HandlerRegistration): voidRegister a handler under a name.
registerJobregisterJob(job: JobClass): voidRegister a job class under its name, so a worker can find it. Checks its options.
registeredJobsregisteredJobs(): ReadonlyMap<string, JobClass>Every known job class.
dispatchdispatch<Payload>(job: JobClass<Payload>, payload: Payload, options?: DispatchOptions): Promise<string>Queue a job; resolves to its id, or the id of the job holding its dedup id. Also takes a registered name.
dispatchManydispatchMany<Payload>(job: JobClass<Payload>, payloads: readonly Payload[], options?: DispatchOptions): Promise<string[]>Every record is checked before the first push.
getJobgetJob(jobId: string, queue?: string): Promise<JobLookup | null>Where a job is; null once gone. Needs a driver with getJob.
processOneprocessOne(queues?: readonly string[]): Promise<boolean>Run the next job; false when there was none.
workwork(options?: WorkerOptions | number, stalledIntervalArg?: number): Promise<void>Start the worker loop; recovers stalled jobs at start and every stalledInterval.
recoverStalerecoverStale(): Promise<number>Move jobs left by a crashed worker back to pending.
draindrain(): Promise<void>Wait for the attempts in flight.
stopstop(): Promise<void>Stop the loop and wait for it and the jobs in flight.
failedJobsfailedJobs(): Promise<JobRecord[]>The failed jobs the driver keeps.
sizesize(): Promise<number>Jobs waiting on the default queue, delayed ones included.
sizeOfsizeOf(queue: string): Promise<number>Jobs waiting on a named queue.

FakeQueue ​

new FakeQueue(), handed to a QueueManager in place of a driver.

MemberSignatureDescription
getPushedgetPushed(): JobRecord[]Copies of the recorded jobs.
resetreset(): voidForget them.
assertPushedassertPushed(name: string, predicate?: FakeQueuePredicateArg): voidThrows an AssertionError unless a recorded job matches.
assertNotPushedassertNotPushed(name: string, predicate?: FakeQueuePredicateArg): voidThrows an AssertionError if one matches.

Configuration ​

config/queue.ts, read under the queue key.

OptionTypeDefaultDescription
defaultstring—The adapter to run on. The generated config reads QUEUE_DRIVER.
adaptersRecord<string, AdapterFactory>—Named adapters (stores is accepted under its older name). Without them, a memory driver is used.
worker.idleDelayDuration2000Wait after finding no job.
worker.stalledIntervalDuration30000Time between stalled-job sweeps.
worker.concurrencynumber1Jobs run at once.
worker.queuesreadonly string[]['default']Queues served, in order.
worker.unknownJobRetriesnumber10Times a job no handler answers is put back (30 s later) before it fails.
locationsreadonly string[]['app/jobs']Directories whose job classes are imported at boot.
jobFactoryJobFactorycontainer makeHow job classes are built.

drivers.redis({ connection, prefix, visibilityTimeoutMs, maxStalledCount, maxFailedJobs }): connection is a client source or a quasar connection name; prefix defaults to 'queue:', visibilityTimeoutMs to 30000, maxStalledCount to 1, maxFailedJobs to 1000 (0 keeps all). The driver honours the connection's keyPrefix: every key it writes, leases and dedup ids included, carries it, so two applications can share one Redis database.

Container bindings ​

TokenResolves to
QueueManager (class)The QueueManager built from config/queue.ts
'bay.queue'The same manager
'queue'The same manager

The two string tokens are typed on ContainerBindings once @c9up/bay is imported.

Errors ​

CodeRaised when
E_CONFIGURATION_ERRORconfig.queue is not what defineConfig returns, declares adapters without a default, its default names an adapter it does not declare, a backoff names an unknown strategy, or a RedisDriver option (visibilityTimeoutMs, maxStalledCount, maxFailedJobs) is out of range.
E_ADAPTER_INIT_ERRORThe selected adapter's factory threw while building its driver; its error is the cause.
E_BAY_INVALID_ADAPTERAn adapter factory did not build a queue driver.
E_BAY_UNSUPPORTED_DRIVERThe driver key names a driver; declare it under adapters instead.
E_BAY_INVALID_BINDINGThe container answers something other than a QueueManager for the QueueManager token.
E_QUEUE_NOT_INITIALIZEDThe queue is used before BayProvider booted or setQueue() was called (service accessor, Job.dispatch(), queue:work), or ready() ran before boot().
E_BAY_QUASAR_MISSINGA Redis adapter names a quasar connection and @c9up/quasar is not installed, or its manager is not available yet.
E_BAY_INCOMPLETE_CONNECTIONThe Redis connection lacks a command the driver issues (EVALSHA, SCRIPT LOAD, …).
E_BAY_UNEXPECTED_REPLYA Redis script answered with a reply the driver cannot read.
E_BAY_INVALID_JOB_OPTIONSA job class declares an option it cannot run with; the specific refusal is in cause.
E_BAY_INVALID_JOB_NAMEA job's options.name is empty, or make:job is given a name that cannot become a file and a class.
E_BAY_DUPLICATE_JOBTwo job classes answer to the same name.
E_BAY_INVALID_ATTEMPTSmaxAttempts / maxRetries is not a whole number >= 1, or a backoff is asked for an attempt below 1.
E_BAY_INVALID_PRIORITYA priority is not a whole number from 1 to 10.
E_INVALID_TIMEOUTA job timeout is not 0 or a whole number of milliseconds setTimeout can hold (1 to 2147483647).
E_INVALID_DURATION_EXPRESSIONA duration is neither a non-negative number of milliseconds nor a string like '10s'. The message names the value; help names the option that held it.
E_BAY_INVALID_RETENTIONremoveOnComplete / removeOnFail is not a boolean or a valid { age?, count? }.
E_INVALID_BASE_DELAYA backoff baseDelay is not above zero.
E_INVALID_MAX_DELAYA backoff maxDelay is not above zero, or not above baseDelay.
E_INVALID_MULTIPLIERA backoff multiplier is not above zero, or is below 1 for the exponential strategy.
E_BAY_INVALID_DEDUPA dedup has an empty id, a ttl that is not a whole number from 1, or extend without a ttl.
E_BAY_INVALID_WORKER_OPTIONSA worker option is out of range: idleDelay, stalledInterval, concurrency, unknownJobRetries or queues.
E_WORKER_ALREADY_RUNNINGwork() is called while the manager's worker is already running.
E_BAY_UNSUPPORTED_OPERATIONThe queue driver has no getJob() or sizeOf() for the lookup asked.
E_BAY_INVALID_JOB_FACTORYThe job factory built something that is not the job class, or a handler without handle(); the attempt fails with it.
E_JOB_TIMEOUTAn attempt ran past its timeout; carries job (its name) and timeout (ms). What failOnTimeout looks for.
E_JOB_MAX_ATTEMPTS_REACHEDHanded to a job's failed() hook once its retries ran out; the last attempt's error is the cause.
E_JOB_NOT_FOUNDA job no handler or job class answers to stays unknown past unknownJobRetries; the failed record keeps its message.
E_JOB_STALLEDThe Redis driver files a job reclaimed from a dead worker more than maxStalledCount times as failed; the failed record keeps its message, and the job's failed() hook receives the error.
E_BAY_UNSERIALIZABLE_JOBA job record cannot be stored as JSON the way Redis would carry it.
E_BAY_JOBS_DIRECTORY_UNREADABLEA declared jobs directory exists but cannot be read.
E_BAY_NO_JOBS_FOUNDJob files were scanned and none yielded a Job subclass.
E_BAY_DUPLICATE_JOB_IDFakeQueue.push() is given a job id it already holds.
E_BAY_FAKE_JOB_NOT_FOUNDFakeQueue is asked to complete, fail or retry a job it does not hold.

Each one is a class of the errors namespace and a @c9up/flare Exception with status 500: branch on error.code or on error instanceof errors.E_*. A failure the queue library has too keeps that library's code and message (E_JOB_TIMEOUT, E_CONFIGURATION_ERROR, …); what bay adds carries E_BAY_. FakeQueue.assertPushed() / assertNotPushed() throw node:assert's AssertionError.

Migration ​

  • BayError is gone: test error.code, or error instanceof errors.E_BAY_* with import { errors } from '@c9up/bay'.
  • JobTimeoutError becomes errors.E_JOB_TIMEOUT; it carries job and timeout, and is built as new errors.E_JOB_TIMEOUT([name, ms]).
  • Codes the queue library also has now carry its name: E_BAY_JOB_TIMEOUT is now E_JOB_TIMEOUT, E_BAY_ALREADY_RUNNING is now E_WORKER_ALREADY_RUNNING, E_BAY_INVALID_TIMEOUT is now E_INVALID_TIMEOUT, E_BAY_INVALID_CONFIG is now E_CONFIGURATION_ERROR, E_BAY_NOT_BOOTED is now E_QUEUE_NOT_INITIALIZED, E_BAY_INVALID_DURATION is now E_INVALID_DURATION_EXPRESSION.
  • E_BAY_UNKNOWN_ADAPTER is now E_CONFIGURATION_ERROR.
  • E_BAY_INVALID_BACKOFF is split: E_INVALID_BASE_DELAY, E_INVALID_MAX_DELAY, E_INVALID_MULTIPLIER; an unknown strategy is E_CONFIGURATION_ERROR.
  • E_BAY_JOB_NOT_FOUND (the FakeQueue lookup) is now E_BAY_FAKE_JOB_NOT_FOUND; E_JOB_NOT_FOUND now means a job name nothing is registered under.
  • E_BAY_ASSERTION_FAILED is gone: FakeQueue assertions throw AssertionError from node:assert.
  • An adapter factory that throws now raises E_ADAPTER_INIT_ERROR, with the factory's error as cause (E_BAY_QUASAR_MISSING included).
  • A job's failed() hook now receives E_JOB_MAX_ATTEMPTS_REACHED, with the last attempt's error as cause, once retries ran out; it still receives the attempt's own error when maxAttempts is 1 or failOnTimeout ended the job.

See also ​