@monque/core 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -2
- package/dist/{errors-BX3oWYfZ.cjs → errors-D5ZGG2uI.cjs} +4 -4
- package/dist/errors-D5ZGG2uI.cjs.map +1 -0
- package/dist/{errors-DWkXsP3R.mjs → errors-DEvnqoOC.mjs} +1 -1
- package/dist/{errors-DW20rHWR.mjs → errors-DQ2_gprw.mjs} +4 -4
- package/dist/errors-DQ2_gprw.mjs.map +1 -0
- package/dist/{errors-Ca92IlaL.cjs → errors-Dfli-u59.cjs} +1 -1
- package/dist/index.cjs +15 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +15 -12
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +15 -12
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +15 -11
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -6
- package/dist/errors-BX3oWYfZ.cjs.map +0 -1
- package/dist/errors-DW20rHWR.mjs.map +0 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["deletions: Promise<DeleteResult>[]","job: Omit<Job<T>, '_id'>","result","checkInterval: ReturnType<typeof setInterval> | undefined","result: undefined | 'timeout'","ShutdownTimeoutError","query: Document","activeJobs: string[]","activeJobs: Job[]","job: PersistedJob<T>"],"sources":["../src/jobs/types.ts","../src/jobs/guards.ts","../src/shared/utils/backoff.ts","../src/shared/utils/cron.ts","../src/scheduler/monque.ts"],"sourcesContent":["import type { ObjectId } from 'mongodb';\n\n/**\n * Represents the lifecycle states of a job in the queue.\n *\n * Jobs transition through states as follows:\n * - PENDING → PROCESSING (when picked up by a worker)\n * - PROCESSING → COMPLETED (on success)\n * - PROCESSING → PENDING (on failure, if retries remain)\n * - PROCESSING → FAILED (on failure, after max retries exhausted)\n *\n * @example\n * ```typescript\n * if (job.status === JobStatus.PENDING) {\n * // job is waiting to be picked up\n * }\n * ```\n */\nexport const JobStatus = {\n\t/** Job is waiting to be picked up by a worker */\n\tPENDING: 'pending',\n\t/** Job is currently being executed by a worker */\n\tPROCESSING: 'processing',\n\t/** Job completed successfully */\n\tCOMPLETED: 'completed',\n\t/** Job permanently failed after exhausting all retry attempts */\n\tFAILED: 'failed',\n} as const;\n\n/**\n * Union type of all possible job status values: `'pending' | 'processing' | 'completed' | 'failed'`\n */\nexport type JobStatusType = (typeof JobStatus)[keyof typeof JobStatus];\n\n/**\n * Represents a job in the Monque queue.\n *\n * @template T - The type of the job's data payload\n *\n * @example\n * ```typescript\n * interface EmailJobData {\n * to: string;\n * subject: string;\n * template: string;\n * }\n *\n * const job: Job<EmailJobData> = {\n * name: 'send-email',\n * data: { to: 'user@example.com', subject: 'Welcome!', template: 'welcome' },\n * status: JobStatus.PENDING,\n * nextRunAt: new Date(),\n * failCount: 0,\n * createdAt: new Date(),\n * updatedAt: new Date(),\n * };\n * ```\n */\nexport interface Job<T = unknown> {\n\t/** MongoDB document identifier */\n\t_id?: ObjectId;\n\n\t/** Job type identifier, matches worker registration */\n\tname: string;\n\n\t/** Job payload - must be JSON-serializable */\n\tdata: T;\n\n\t/** Current lifecycle state */\n\tstatus: JobStatusType;\n\n\t/** When the job should be processed */\n\tnextRunAt: Date;\n\n\t/** Timestamp when job was locked for processing */\n\tlockedAt?: Date | null;\n\n\t/**\n\t * Unique identifier of the scheduler instance that claimed this job.\n\t * Used for atomic claim pattern - ensures only one instance processes each job.\n\t * Set when a job is claimed, cleared when job completes or fails.\n\t */\n\tclaimedBy?: string | null;\n\n\t/**\n\t * Timestamp of the last heartbeat update for this job.\n\t * Used to detect stale jobs when a scheduler instance crashes without releasing.\n\t * Updated periodically while job is being processed.\n\t */\n\tlastHeartbeat?: Date | null;\n\n\t/**\n\t * Heartbeat interval in milliseconds for this job.\n\t * Stored on the job to allow recovery logic to use the correct timeout.\n\t */\n\theartbeatInterval?: number;\n\n\t/** Number of failed attempts */\n\tfailCount: number;\n\n\t/** Last failure error message */\n\tfailReason?: string;\n\n\t/** Cron expression for recurring jobs */\n\trepeatInterval?: string;\n\n\t/** Deduplication key to prevent duplicate jobs */\n\tuniqueKey?: string;\n\n\t/** Job creation timestamp */\n\tcreatedAt: Date;\n\n\t/** Last modification timestamp */\n\tupdatedAt: Date;\n}\n\n/**\n * A job that has been persisted to MongoDB and has a guaranteed `_id`.\n * This is returned by `enqueue()`, `now()`, and `schedule()` methods.\n *\n * @template T - The type of the job's data payload\n */\nexport type PersistedJob<T = unknown> = Job<T> & { _id: ObjectId };\n\n/**\n * Options for enqueueing a job.\n *\n * @example\n * ```typescript\n * await monque.enqueue('sync-user', { userId: '123' }, {\n * uniqueKey: 'sync-user-123',\n * runAt: new Date(Date.now() + 5000), // Run in 5 seconds\n * });\n * ```\n */\nexport interface EnqueueOptions {\n\t/**\n\t * Deduplication key. If a job with this key is already pending or processing,\n\t * the enqueue operation will not create a duplicate.\n\t */\n\tuniqueKey?: string;\n\n\t/**\n\t * When the job should be processed. Defaults to immediately (new Date()).\n\t */\n\trunAt?: Date;\n}\n\n/**\n * Options for scheduling a recurring job.\n *\n * @example\n * ```typescript\n * await monque. schedule('0 * * * *', 'hourly-cleanup', { dir: '/tmp' }, {\n * uniqueKey: 'hourly-cleanup-job',\n * });\n * ```\n */\nexport interface ScheduleOptions {\n\t/**\n\t * Deduplication key. If a job with this key is already pending or processing,\n\t * the schedule operation will not create a duplicate.\n\t */\n\tuniqueKey?: string;\n}\n\n/**\n * Filter options for querying jobs.\n *\n * Use with `monque.getJobs()` to filter jobs by name, status, or limit results.\n *\n * @example\n * ```typescript\n * // Get all pending email jobs\n * const pendingEmails = await monque.getJobs({\n * name: 'send-email',\n * status: JobStatus.PENDING,\n * });\n *\n * // Get all failed or completed jobs (paginated)\n * const finishedJobs = await monque.getJobs({\n * status: [JobStatus.COMPLETED, JobStatus.FAILED],\n * limit: 50,\n * skip: 100,\n * });\n * ```\n */\nexport interface GetJobsFilter {\n\t/** Filter by job type name */\n\tname?: string;\n\n\t/** Filter by status (single or multiple) */\n\tstatus?: JobStatusType | JobStatusType[];\n\n\t/** Maximum number of jobs to return (default: 100) */\n\tlimit?: number;\n\n\t/** Number of jobs to skip for pagination */\n\tskip?: number;\n}\n\n/**\n * Handler function signature for processing jobs.\n *\n * @template T - The type of the job's data payload\n *\n * @example\n * ```typescript\n * const emailHandler: JobHandler<EmailJobData> = async (job) => {\n * await sendEmail(job.data.to, job.data.subject);\n * };\n * ```\n */\nexport type JobHandler<T = unknown> = (job: Job<T>) => Promise<void> | void;\n","import type { Job, JobStatusType, PersistedJob } from './types.js';\nimport { JobStatus } from './types.js';\n\n/**\n * Type guard to check if a job has been persisted to MongoDB.\n *\n * A persisted job is guaranteed to have an `_id` field, which means it has been\n * successfully inserted into the database. This is useful when you need to ensure\n * a job can be updated or referenced by its ID.\n *\n * @template T - The type of the job's data payload\n * @param job - The job to check\n * @returns `true` if the job has a valid `_id`, narrowing the type to `PersistedJob<T>`\n *\n * @example Basic usage\n * ```typescript\n * const job: Job<EmailData> = await monque.enqueue('send-email', emailData);\n *\n * if (isPersistedJob(job)) {\n * // TypeScript knows job._id exists\n * console.log(`Job ID: ${job._id.toString()}`);\n * }\n * ```\n *\n * @example In a conditional\n * ```typescript\n * function logJobId(job: Job) {\n * if (!isPersistedJob(job)) {\n * console.log('Job not yet persisted');\n * return;\n * }\n * // TypeScript knows job is PersistedJob here\n * console.log(`Processing job ${job._id.toString()}`);\n * }\n * ```\n */\nexport function isPersistedJob<T>(job: Job<T>): job is PersistedJob<T> {\n\treturn '_id' in job && job._id !== undefined && job._id !== null;\n}\n\n/**\n * Type guard to check if a value is a valid job status.\n *\n * Validates that a value is one of the four valid job statuses: `'pending'`,\n * `'processing'`, `'completed'`, or `'failed'`. Useful for runtime validation\n * of user input or external data.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid `JobStatusType`, narrowing the type\n *\n * @example Validating user input\n * ```typescript\n * function filterByStatus(status: string) {\n * if (!isValidJobStatus(status)) {\n * throw new Error(`Invalid status: ${status}`);\n * }\n * // TypeScript knows status is JobStatusType here\n * return db.jobs.find({ status });\n * }\n * ```\n *\n * @example Runtime validation\n * ```typescript\n * const statusFromApi = externalData.status;\n *\n * if (isValidJobStatus(statusFromApi)) {\n * job.status = statusFromApi;\n * } else {\n * job.status = JobStatus.PENDING;\n * }\n * ```\n */\nexport function isValidJobStatus(value: unknown): value is JobStatusType {\n\treturn typeof value === 'string' && Object.values(JobStatus).includes(value as JobStatusType);\n}\n\n/**\n * Type guard to check if a job is in pending status.\n *\n * A convenience helper for checking if a job is waiting to be processed.\n * Equivalent to `job.status === JobStatus.PENDING` but with better semantics.\n *\n * @template T - The type of the job's data payload\n * @param job - The job to check\n * @returns `true` if the job status is `'pending'`\n *\n * @example Filter pending jobs\n * ```typescript\n * const jobs = await monque.getJobs();\n * const pendingJobs = jobs.filter(isPendingJob);\n * console.log(`${pendingJobs.length} jobs waiting to be processed`);\n * ```\n *\n * @example Conditional logic\n * ```typescript\n * if (isPendingJob(job)) {\n * await monque.now(job.name, job.data);\n * }\n * ```\n */\nexport function isPendingJob<T>(job: Job<T>): boolean {\n\treturn job.status === JobStatus.PENDING;\n}\n\n/**\n * Type guard to check if a job is currently being processed.\n *\n * A convenience helper for checking if a job is actively running.\n * Equivalent to `job.status === JobStatus.PROCESSING` but with better semantics.\n *\n * @template T - The type of the job's data payload\n * @param job - The job to check\n * @returns `true` if the job status is `'processing'`\n *\n * @example Monitor active jobs\n * ```typescript\n * const jobs = await monque.getJobs();\n * const activeJobs = jobs.filter(isProcessingJob);\n * console.log(`${activeJobs.length} jobs currently running`);\n * ```\n */\nexport function isProcessingJob<T>(job: Job<T>): boolean {\n\treturn job.status === JobStatus.PROCESSING;\n}\n\n/**\n * Type guard to check if a job has completed successfully.\n *\n * A convenience helper for checking if a job finished without errors.\n * Equivalent to `job.status === JobStatus.COMPLETED` but with better semantics.\n *\n * @template T - The type of the job's data payload\n * @param job - The job to check\n * @returns `true` if the job status is `'completed'`\n *\n * @example Find completed jobs\n * ```typescript\n * const jobs = await monque.getJobs();\n * const completedJobs = jobs.filter(isCompletedJob);\n * console.log(`${completedJobs.length} jobs completed successfully`);\n * ```\n */\nexport function isCompletedJob<T>(job: Job<T>): boolean {\n\treturn job.status === JobStatus.COMPLETED;\n}\n\n/**\n * Type guard to check if a job has permanently failed.\n *\n * A convenience helper for checking if a job exhausted all retries.\n * Equivalent to `job.status === JobStatus.FAILED` but with better semantics.\n *\n * @template T - The type of the job's data payload\n * @param job - The job to check\n * @returns `true` if the job status is `'failed'`\n *\n * @example Handle failed jobs\n * ```typescript\n * const jobs = await monque.getJobs();\n * const failedJobs = jobs.filter(isFailedJob);\n *\n * for (const job of failedJobs) {\n * console.error(`Job ${job.name} failed: ${job.failReason}`);\n * await sendAlert(job);\n * }\n * ```\n */\nexport function isFailedJob<T>(job: Job<T>): boolean {\n\treturn job.status === JobStatus.FAILED;\n}\n\n/**\n * Type guard to check if a job is a recurring scheduled job.\n *\n * A recurring job has a `repeatInterval` cron expression and will be automatically\n * rescheduled after each successful completion.\n *\n * @template T - The type of the job's data payload\n * @param job - The job to check\n * @returns `true` if the job has a `repeatInterval` defined\n *\n * @example Filter recurring jobs\n * ```typescript\n * const jobs = await monque.getJobs();\n * const recurringJobs = jobs.filter(isRecurringJob);\n * console.log(`${recurringJobs.length} jobs will repeat automatically`);\n * ```\n *\n * @example Conditional cleanup\n * ```typescript\n * if (!isRecurringJob(job) && isCompletedJob(job)) {\n * // Safe to delete one-time completed jobs\n * await deleteJob(job._id);\n * }\n * ```\n */\nexport function isRecurringJob<T>(job: Job<T>): boolean {\n\treturn job.repeatInterval !== undefined && job.repeatInterval !== null;\n}\n","/**\n * Default base interval for exponential backoff in milliseconds.\n * @default 1000\n */\nexport const DEFAULT_BASE_INTERVAL = 1000;\n\n/**\n * Default maximum delay cap for exponential backoff in milliseconds.\n *\n * This prevents unbounded delays (e.g. failCount=20 is >11 days at 1s base)\n * and avoids precision/overflow issues for very large fail counts.\n * @default 86400000 (24 hours)\n */\nexport const DEFAULT_MAX_BACKOFF_DELAY = 24 * 60 * 60 * 1_000;\n\n/**\n * Calculate the next run time using exponential backoff.\n *\n * Formula: nextRunAt = now + (2^failCount × baseInterval)\n *\n * @param failCount - Number of previous failed attempts\n * @param baseInterval - Base interval in milliseconds (default: 1000ms)\n * @param maxDelay - Maximum delay in milliseconds (optional)\n * @returns The next run date\n *\n * @example\n * ```typescript\n * // First retry (failCount=1): 2^1 * 1000 = 2000ms delay\n * const nextRun = calculateBackoff(1);\n *\n * // Second retry (failCount=2): 2^2 * 1000 = 4000ms delay\n * const nextRun = calculateBackoff(2);\n *\n * // With custom base interval\n * const nextRun = calculateBackoff(3, 500); // 2^3 * 500 = 4000ms delay\n *\n * // With max delay\n * const nextRun = calculateBackoff(10, 1000, 60000); // capped at 60000ms\n * ```\n */\nexport function calculateBackoff(\n\tfailCount: number,\n\tbaseInterval: number = DEFAULT_BASE_INTERVAL,\n\tmaxDelay?: number,\n): Date {\n\tconst effectiveMaxDelay = maxDelay ?? DEFAULT_MAX_BACKOFF_DELAY;\n\tlet delay = 2 ** failCount * baseInterval;\n\n\tif (delay > effectiveMaxDelay) {\n\t\tdelay = effectiveMaxDelay;\n\t}\n\n\treturn new Date(Date.now() + delay);\n}\n\n/**\n * Calculate just the delay in milliseconds for a given fail count.\n *\n * @param failCount - Number of previous failed attempts\n * @param baseInterval - Base interval in milliseconds (default: 1000ms)\n * @param maxDelay - Maximum delay in milliseconds (optional)\n * @returns The delay in milliseconds\n */\nexport function calculateBackoffDelay(\n\tfailCount: number,\n\tbaseInterval: number = DEFAULT_BASE_INTERVAL,\n\tmaxDelay?: number,\n): number {\n\tconst effectiveMaxDelay = maxDelay ?? DEFAULT_MAX_BACKOFF_DELAY;\n\tlet delay = 2 ** failCount * baseInterval;\n\n\tif (delay > effectiveMaxDelay) {\n\t\tdelay = effectiveMaxDelay;\n\t}\n\n\treturn delay;\n}\n","import { CronExpressionParser } from 'cron-parser';\n\nimport { InvalidCronError } from '../errors.js';\n\n/**\n * Parse a cron expression and return the next scheduled run date.\n *\n * @param expression - A 5-field cron expression (minute hour day-of-month month day-of-week) or a predefined expression\n * @param currentDate - The reference date for calculating next run (default: now)\n * @returns The next scheduled run date\n * @throws {InvalidCronError} If the cron expression is invalid\n *\n * @example\n * ```typescript\n * // Every minute\n * const nextRun = getNextCronDate('* * * * *');\n *\n * // Every day at midnight\n * const nextRun = getNextCronDate('0 0 * * *');\n *\n * // Using predefined expression\n * const nextRun = getNextCronDate('@daily');\n *\n * // Every Monday at 9am\n * const nextRun = getNextCronDate('0 9 * * 1');\n * ```\n */\nexport function getNextCronDate(expression: string, currentDate?: Date): Date {\n\ttry {\n\t\tconst interval = CronExpressionParser.parse(expression, {\n\t\t\tcurrentDate: currentDate ?? new Date(),\n\t\t});\n\t\treturn interval.next().toDate();\n\t} catch (error) {\n\t\thandleCronParseError(expression, error);\n\t}\n}\n\n/**\n * Validate a cron expression without calculating the next run date.\n *\n * @param expression - A 5-field cron expression\n * @throws {InvalidCronError} If the cron expression is invalid\n *\n * @example\n * ```typescript\n * validateCronExpression('0 9 * * 1'); // Throws if invalid\n * ```\n */\nexport function validateCronExpression(expression: string): void {\n\ttry {\n\t\tCronExpressionParser.parse(expression);\n\t} catch (error) {\n\t\thandleCronParseError(expression, error);\n\t}\n}\n\nfunction handleCronParseError(expression: string, error: unknown): never {\n\t/* istanbul ignore next -- @preserve cron-parser always throws Error objects */\n\tconst errorMessage = error instanceof Error ? error.message : 'Unknown parsing error';\n\tthrow new InvalidCronError(\n\t\texpression,\n\t\t`Invalid cron expression \"${expression}\": ${errorMessage}. ` +\n\t\t\t'Expected 5-field format: \"minute hour day-of-month month day-of-week\" or predefined expression (e.g. @daily). ' +\n\t\t\t'Example: \"0 9 * * 1\" (every Monday at 9am)',\n\t);\n}\n","import { randomUUID } from 'node:crypto';\nimport { EventEmitter } from 'node:events';\nimport type {\n\tChangeStream,\n\tChangeStreamDocument,\n\tCollection,\n\tDb,\n\tDeleteResult,\n\tDocument,\n\tObjectId,\n\tWithId,\n} from 'mongodb';\n\nimport type { MonqueEventMap } from '@/events';\nimport {\n\ttype EnqueueOptions,\n\ttype GetJobsFilter,\n\tisPersistedJob,\n\ttype Job,\n\ttype JobHandler,\n\tJobStatus,\n\ttype JobStatusType,\n\ttype PersistedJob,\n\ttype ScheduleOptions,\n} from '@/jobs';\nimport {\n\tConnectionError,\n\tcalculateBackoff,\n\tgetNextCronDate,\n\tMonqueError,\n\tWorkerRegistrationError,\n} from '@/shared';\nimport type { WorkerOptions, WorkerRegistration } from '@/workers';\n\nimport type { MonqueOptions } from './types.js';\n\n/**\n * Default configuration values\n */\nconst DEFAULTS = {\n\tcollectionName: 'monque_jobs',\n\tpollInterval: 1000,\n\tmaxRetries: 10,\n\tbaseRetryInterval: 1000,\n\tshutdownTimeout: 30000,\n\tdefaultConcurrency: 5,\n\tlockTimeout: 1_800_000, // 30 minutes\n\trecoverStaleJobs: true,\n\theartbeatInterval: 30000, // 30 seconds\n\tretentionInterval: 3600_000, // 1 hour\n} as const;\n\n/**\n * Monque - MongoDB-backed job scheduler\n *\n * A type-safe job scheduler with atomic locking, exponential backoff, cron scheduling,\n * stale job recovery, and event-driven observability. Built on native MongoDB driver.\n *\n * @example Complete lifecycle\n * ```;\ntypescript\n *\n\nimport { Monque } from '@monque/core';\n\n*\n\nimport { MongoClient } from 'mongodb';\n\n*\n *\nconst client = new MongoClient('mongodb://localhost:27017');\n* await client.connect()\n*\nconst db = client.db('myapp');\n*\n * // Create instance with options\n *\nconst monque = new Monque(db, {\n * collectionName: 'jobs',\n * pollInterval: 1000,\n * maxRetries: 10,\n * shutdownTimeout: 30000,\n * });\n*\n * // Initialize (sets up indexes and recovers stale jobs)\n * await monque.initialize()\n*\n * // Register workers with type safety\n *\ntype EmailJob = {};\n* to: string\n* subject: string\n* body: string\n* }\n *\n * monque.worker<EmailJob>('send-email', async (job) =>\n{\n\t* await emailService.send(job.data.to, job.data.subject, job.data.body)\n\t*\n}\n)\n*\n * // Monitor events for observability\n * monque.on('job:complete', (\n{\n\tjob, duration;\n}\n) =>\n{\n * logger.info(`Job $job.namecompleted in $durationms`);\n * });\n *\n * monque.on('job:fail', ({ job, error, willRetry }) => {\n * logger.error(`Job $job.namefailed:`, error);\n * });\n *\n * // Start processing\n * monque.start();\n *\n * // Enqueue jobs\n * await monque.enqueue('send-email', {\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * body: 'Thanks for signing up.'\n * });\n *\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await monque.stop();\n * await client.close();\n * process.exit(0);\n * });\n * ```\n */\nexport class Monque extends EventEmitter {\n\tprivate readonly db: Db;\n\tprivate readonly options: Required<Omit<MonqueOptions, 'maxBackoffDelay' | 'jobRetention'>> &\n\t\tPick<MonqueOptions, 'maxBackoffDelay' | 'jobRetention'>;\n\tprivate collection: Collection<Document> | null = null;\n\tprivate workers: Map<string, WorkerRegistration> = new Map();\n\tprivate pollIntervalId: ReturnType<typeof setInterval> | null = null;\n\tprivate heartbeatIntervalId: ReturnType<typeof setInterval> | null = null;\n\tprivate cleanupIntervalId: ReturnType<typeof setInterval> | null = null;\n\tprivate isRunning = false;\n\tprivate isInitialized = false;\n\n\t/**\n\t * MongoDB Change Stream for real-time job notifications.\n\t * When available, provides instant job processing without polling delay.\n\t */\n\tprivate changeStream: ChangeStream | null = null;\n\n\t/**\n\t * Number of consecutive reconnection attempts for change stream.\n\t * Used for exponential backoff during reconnection.\n\t */\n\tprivate changeStreamReconnectAttempts = 0;\n\n\t/**\n\t * Maximum reconnection attempts before falling back to polling-only mode.\n\t */\n\tprivate readonly maxChangeStreamReconnectAttempts = 3;\n\n\t/**\n\t * Debounce timer for change stream event processing.\n\t * Prevents claim storms when multiple events arrive in quick succession.\n\t */\n\tprivate changeStreamDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n\n\t/**\n\t * Whether the scheduler is currently using change streams for notifications.\n\t */\n\tprivate usingChangeStreams = false;\n\n\t/**\n\t * Timer ID for change stream reconnection with exponential backoff.\n\t * Tracked to allow cancellation during shutdown.\n\t */\n\tprivate changeStreamReconnectTimer: ReturnType<typeof setTimeout> | null = null;\n\n\tconstructor(db: Db, options: MonqueOptions = {}) {\n\t\tsuper();\n\t\tthis.db = db;\n\t\tthis.options = {\n\t\t\tcollectionName: options.collectionName ?? DEFAULTS.collectionName,\n\t\t\tpollInterval: options.pollInterval ?? DEFAULTS.pollInterval,\n\t\t\tmaxRetries: options.maxRetries ?? DEFAULTS.maxRetries,\n\t\t\tbaseRetryInterval: options.baseRetryInterval ?? DEFAULTS.baseRetryInterval,\n\t\t\tshutdownTimeout: options.shutdownTimeout ?? DEFAULTS.shutdownTimeout,\n\t\t\tdefaultConcurrency: options.defaultConcurrency ?? DEFAULTS.defaultConcurrency,\n\t\t\tlockTimeout: options.lockTimeout ?? DEFAULTS.lockTimeout,\n\t\t\trecoverStaleJobs: options.recoverStaleJobs ?? DEFAULTS.recoverStaleJobs,\n\t\t\tmaxBackoffDelay: options.maxBackoffDelay,\n\t\t\tschedulerInstanceId: options.schedulerInstanceId ?? randomUUID(),\n\t\t\theartbeatInterval: options.heartbeatInterval ?? DEFAULTS.heartbeatInterval,\n\t\t\tjobRetention: options.jobRetention,\n\t\t};\n\t}\n\n\t/**\n\t * Initialize the scheduler by setting up the MongoDB collection and indexes.\n\t * Must be called before start().\n\t *\n\t * @throws {ConnectionError} If collection or index creation fails\n\t */\n\tasync initialize(): Promise<void> {\n\t\tif (this.isInitialized) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.collection = this.db.collection(this.options.collectionName);\n\n\t\t\t// Create indexes for efficient queries\n\t\t\tawait this.createIndexes();\n\n\t\t\t// Recover stale jobs if enabled\n\t\t\tif (this.options.recoverStaleJobs) {\n\t\t\t\tawait this.recoverStaleJobs();\n\t\t\t}\n\n\t\t\tthis.isInitialized = true;\n\t\t} catch (error) {\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : 'Unknown error during initialization';\n\t\t\tthrow new ConnectionError(`Failed to initialize Monque: ${message}`);\n\t\t}\n\t}\n\n\t/**\n\t * Create required MongoDB indexes for efficient job processing.\n\t *\n\t * The following indexes are created:\n\t * - `{status, nextRunAt}` - For efficient job polling queries\n\t * - `{name, uniqueKey}` - Partial unique index for deduplication (pending/processing only)\n\t * - `{name, status}` - For job lookup by type\n\t * - `{claimedBy, status}` - For finding jobs owned by a specific scheduler instance\n\t * - `{lastHeartbeat, status}` - For monitoring/debugging queries (e.g., inspecting heartbeat age)\n\t * - `{status, nextRunAt, claimedBy}` - For atomic claim queries (find unclaimed pending jobs)\n\t * - `{lockedAt, lastHeartbeat, status}` - Supports recovery scans and monitoring access patterns\n\t */\n\tprivate async createIndexes(): Promise<void> {\n\t\tif (!this.collection) {\n\t\t\tthrow new ConnectionError('Collection not initialized');\n\t\t}\n\n\t\t// Compound index for job polling - status + nextRunAt for efficient queries\n\t\tawait this.collection.createIndex({ status: 1, nextRunAt: 1 }, { background: true });\n\n\t\t// Partial unique index for deduplication - scoped by name + uniqueKey\n\t\t// Only enforced where uniqueKey exists and status is pending/processing\n\t\tawait this.collection.createIndex(\n\t\t\t{ name: 1, uniqueKey: 1 },\n\t\t\t{\n\t\t\t\tunique: true,\n\t\t\t\tpartialFilterExpression: {\n\t\t\t\t\tuniqueKey: { $exists: true },\n\t\t\t\t\tstatus: { $in: [JobStatus.PENDING, JobStatus.PROCESSING] },\n\t\t\t\t},\n\t\t\t\tbackground: true,\n\t\t\t},\n\t\t);\n\n\t\t// Index for job lookup by name\n\t\tawait this.collection.createIndex({ name: 1, status: 1 }, { background: true });\n\n\t\t// Compound index for finding jobs claimed by a specific scheduler instance.\n\t\t// Used for heartbeat updates and cleanup on shutdown.\n\t\tawait this.collection.createIndex({ claimedBy: 1, status: 1 }, { background: true });\n\n\t\t// Compound index for monitoring/debugging via heartbeat timestamps.\n\t\t// Note: stale recovery uses lockedAt + lockTimeout as the source of truth.\n\t\tawait this.collection.createIndex({ lastHeartbeat: 1, status: 1 }, { background: true });\n\n\t\t// Compound index for atomic claim queries.\n\t\t// Optimizes the findOneAndUpdate query that claims unclaimed pending jobs.\n\t\tawait this.collection.createIndex(\n\t\t\t{ status: 1, nextRunAt: 1, claimedBy: 1 },\n\t\t\t{ background: true },\n\t\t);\n\n\t\t// Expanded index that supports recovery scans (status + lockedAt) plus heartbeat monitoring patterns.\n\t\tawait this.collection.createIndex(\n\t\t\t{ status: 1, lockedAt: 1, lastHeartbeat: 1 },\n\t\t\t{ background: true },\n\t\t);\n\t}\n\n\t/**\n\t * Recover stale jobs that were left in 'processing' status.\n\t * A job is considered stale if its `lockedAt` timestamp exceeds the configured `lockTimeout`.\n\t * Stale jobs are reset to 'pending' so they can be picked up by workers again.\n\t */\n\tprivate async recoverStaleJobs(): Promise<void> {\n\t\tif (!this.collection) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst staleThreshold = new Date(Date.now() - this.options.lockTimeout);\n\n\t\tconst result = await this.collection.updateMany(\n\t\t\t{\n\t\t\t\tstatus: JobStatus.PROCESSING,\n\t\t\t\tlockedAt: { $lt: staleThreshold },\n\t\t\t},\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tstatus: JobStatus.PENDING,\n\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t},\n\t\t\t\t$unset: {\n\t\t\t\t\tlockedAt: '',\n\t\t\t\t\tclaimedBy: '',\n\t\t\t\t\tlastHeartbeat: '',\n\t\t\t\t\theartbeatInterval: '',\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tif (result.modifiedCount > 0) {\n\t\t\t// Emit event for recovered jobs\n\t\t\tthis.emit('stale:recovered', {\n\t\t\t\tcount: result.modifiedCount,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Clean up old completed and failed jobs based on retention policy.\n\t *\n\t * - Removes completed jobs older than `jobRetention.completed`\n\t * - Removes failed jobs older than `jobRetention.failed`\n\t *\n\t * The cleanup runs concurrently for both statuses if configured.\n\t *\n\t * @returns Promise resolving when all deletion operations complete\n\t */\n\tprivate async cleanupJobs(): Promise<void> {\n\t\tif (!this.collection || !this.options.jobRetention) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst { completed, failed } = this.options.jobRetention;\n\t\tconst now = Date.now();\n\t\tconst deletions: Promise<DeleteResult>[] = [];\n\n\t\tif (completed) {\n\t\t\tconst cutoff = new Date(now - completed);\n\t\t\tdeletions.push(\n\t\t\t\tthis.collection.deleteMany({\n\t\t\t\t\tstatus: JobStatus.COMPLETED,\n\t\t\t\t\tupdatedAt: { $lt: cutoff },\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tif (failed) {\n\t\t\tconst cutoff = new Date(now - failed);\n\t\t\tdeletions.push(\n\t\t\t\tthis.collection.deleteMany({\n\t\t\t\t\tstatus: JobStatus.FAILED,\n\t\t\t\t\tupdatedAt: { $lt: cutoff },\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tif (deletions.length > 0) {\n\t\t\tawait Promise.all(deletions);\n\t\t}\n\t}\n\n\t/**\n\t * Enqueue a job for processing.\n\t *\n\t * Jobs are stored in MongoDB and processed by registered workers. Supports\n\t * delayed execution via `runAt` and deduplication via `uniqueKey`.\n\t *\n\t * When a `uniqueKey` is provided, only one pending or processing job with that key\n\t * can exist. Completed or failed jobs don't block new jobs with the same key.\n\t *\n\t * Failed jobs are automatically retried with exponential backoff up to `maxRetries`\n\t * (default: 10 attempts). The delay between retries is calculated as `2^failCount × baseRetryInterval`.\n\t *\n\t * @template T - The job data payload type (must be JSON-serializable)\n\t * @param name - Job type identifier, must match a registered worker\n\t * @param data - Job payload, will be passed to the worker handler\n\t * @param options - Scheduling and deduplication options\n\t * @returns Promise resolving to the created or existing job document\n\t * @throws {ConnectionError} If database operation fails or scheduler not initialized\n\t *\n\t * @example Basic job enqueueing\n\t * ```typescript\n\t * await monque.enqueue('send-email', {\n\t * to: 'user@example.com',\n\t * subject: 'Welcome!',\n\t * body: 'Thanks for signing up.'\n\t * });\n\t * ```\n\t *\n\t * @example Delayed execution\n\t * ```typescript\n\t * const oneHourLater = new Date(Date.now() + 3600000);\n\t * await monque.enqueue('reminder', { message: 'Check in!' }, {\n\t * runAt: oneHourLater\n\t * });\n\t * ```\n\t *\n\t * @example Prevent duplicates with unique key\n\t * ```typescript\n\t * await monque.enqueue('sync-user', { userId: '123' }, {\n\t * uniqueKey: 'sync-user-123'\n\t * });\n\t * // Subsequent enqueues with same uniqueKey return existing pending/processing job\n\t * ```\n\t */\n\tasync enqueue<T>(name: string, data: T, options: EnqueueOptions = {}): Promise<PersistedJob<T>> {\n\t\tthis.ensureInitialized();\n\n\t\tconst now = new Date();\n\t\tconst job: Omit<Job<T>, '_id'> = {\n\t\t\tname,\n\t\t\tdata,\n\t\t\tstatus: JobStatus.PENDING,\n\t\t\tnextRunAt: options.runAt ?? now,\n\t\t\tfailCount: 0,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\n\t\tif (options.uniqueKey) {\n\t\t\tjob.uniqueKey = options.uniqueKey;\n\t\t}\n\n\t\ttry {\n\t\t\tif (options.uniqueKey) {\n\t\t\t\tif (!this.collection) {\n\t\t\t\t\tthrow new ConnectionError('Failed to enqueue job: collection not available');\n\t\t\t\t}\n\n\t\t\t\t// Use upsert with $setOnInsert for deduplication (scoped by name + uniqueKey)\n\t\t\t\tconst result = await this.collection.findOneAndUpdate(\n\t\t\t\t\t{\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tuniqueKey: options.uniqueKey,\n\t\t\t\t\t\tstatus: { $in: [JobStatus.PENDING, JobStatus.PROCESSING] },\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t$setOnInsert: job,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tupsert: true,\n\t\t\t\t\t\treturnDocument: 'after',\n\t\t\t\t\t},\n\t\t\t\t);\n\n\t\t\t\tif (!result) {\n\t\t\t\t\tthrow new ConnectionError('Failed to enqueue job: findOneAndUpdate returned no document');\n\t\t\t\t}\n\n\t\t\t\treturn this.documentToPersistedJob<T>(result as WithId<Document>);\n\t\t\t}\n\n\t\t\tconst result = await this.collection?.insertOne(job as Document);\n\n\t\t\tif (!result) {\n\t\t\t\tthrow new ConnectionError('Failed to enqueue job: collection not available');\n\t\t\t}\n\n\t\t\treturn { ...job, _id: result.insertedId } as PersistedJob<T>;\n\t\t} catch (error) {\n\t\t\tif (error instanceof ConnectionError) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst message = error instanceof Error ? error.message : 'Unknown error during enqueue';\n\t\t\tthrow new ConnectionError(\n\t\t\t\t`Failed to enqueue job: ${message}`,\n\t\t\t\terror instanceof Error ? { cause: error } : undefined,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Enqueue a job for immediate processing.\n\t *\n\t * Convenience method equivalent to `enqueue(name, data, { runAt: new Date() })`.\n\t * Jobs are picked up on the next poll cycle (typically within 1 second based on `pollInterval`).\n\t *\n\t * @template T - The job data payload type (must be JSON-serializable)\n\t * @param name - Job type identifier, must match a registered worker\n\t * @param data - Job payload, will be passed to the worker handler\n\t * @returns Promise resolving to the created job document\n\t * @throws {ConnectionError} If database operation fails or scheduler not initialized\n\t *\n\t * @example Send email immediately\n\t * ```typescript\n\t * await monque.now('send-email', {\n\t * to: 'admin@example.com',\n\t * subject: 'Alert',\n\t * body: 'Immediate attention required'\n\t * });\n\t * ```\n\t *\n\t * @example Process order in background\n\t * ```typescript\n\t * const order = await createOrder(data);\n\t * await monque.now('process-order', { orderId: order.id });\n\t * return order; // Return immediately, processing happens async\n\t * ```\n\t */\n\tasync now<T>(name: string, data: T): Promise<PersistedJob<T>> {\n\t\treturn this.enqueue(name, data, { runAt: new Date() });\n\t}\n\n\t/**\n\t * Schedule a recurring job with a cron expression.\n\t *\n\t * Creates a job that automatically re-schedules itself based on the cron pattern.\n\t * Uses standard 5-field cron format: minute, hour, day of month, month, day of week.\n\t * Also supports predefined expressions like `@daily`, `@weekly`, `@monthly`, etc.\n\t * After successful completion, the job is reset to `pending` status and scheduled\n\t * for its next run based on the cron expression.\n\t *\n\t * When a `uniqueKey` is provided, only one pending or processing job with that key\n\t * can exist. This prevents duplicate scheduled jobs on application restart.\n\t *\n\t * @template T - The job data payload type (must be JSON-serializable)\n\t * @param cron - Cron expression (5 fields or predefined expression)\n\t * @param name - Job type identifier, must match a registered worker\n\t * @param data - Job payload, will be passed to the worker handler on each run\n\t * @param options - Scheduling options (uniqueKey for deduplication)\n\t * @returns Promise resolving to the created job document with `repeatInterval` set\n\t * @throws {InvalidCronError} If cron expression is invalid\n\t * @throws {ConnectionError} If database operation fails or scheduler not initialized\n\t *\n\t * @example Hourly cleanup job\n\t * ```typescript\n\t * await monque.schedule('0 * * * *', 'cleanup-temp-files', {\n\t * directory: '/tmp/uploads'\n\t * });\n\t * ```\n\t *\n\t * @example Prevent duplicate scheduled jobs with unique key\n\t * ```typescript\n\t * await monque.schedule('0 * * * *', 'hourly-report', { type: 'sales' }, {\n\t * uniqueKey: 'hourly-report-sales'\n\t * });\n\t * // Subsequent calls with same uniqueKey return existing pending/processing job\n\t * ```\n\t *\n\t * @example Daily report at midnight (using predefined expression)\n\t * ```typescript\n\t * await monque.schedule('@daily', 'daily-report', {\n\t * reportType: 'sales',\n\t * recipients: ['analytics@example.com']\n\t * });\n\t * ```\n\t */\n\tasync schedule<T>(\n\t\tcron: string,\n\t\tname: string,\n\t\tdata: T,\n\t\toptions: ScheduleOptions = {},\n\t): Promise<PersistedJob<T>> {\n\t\tthis.ensureInitialized();\n\n\t\t// Validate cron and get next run date (throws InvalidCronError if invalid)\n\t\tconst nextRunAt = getNextCronDate(cron);\n\n\t\tconst now = new Date();\n\t\tconst job: Omit<Job<T>, '_id'> = {\n\t\t\tname,\n\t\t\tdata,\n\t\t\tstatus: JobStatus.PENDING,\n\t\t\tnextRunAt,\n\t\t\trepeatInterval: cron,\n\t\t\tfailCount: 0,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\n\t\tif (options.uniqueKey) {\n\t\t\tjob.uniqueKey = options.uniqueKey;\n\t\t}\n\n\t\ttry {\n\t\t\tif (options.uniqueKey) {\n\t\t\t\tif (!this.collection) {\n\t\t\t\t\tthrow new ConnectionError('Failed to schedule job: collection not available');\n\t\t\t\t}\n\n\t\t\t\t// Use upsert with $setOnInsert for deduplication (scoped by name + uniqueKey)\n\t\t\t\tconst result = await this.collection.findOneAndUpdate(\n\t\t\t\t\t{\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tuniqueKey: options.uniqueKey,\n\t\t\t\t\t\tstatus: { $in: [JobStatus.PENDING, JobStatus.PROCESSING] },\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t$setOnInsert: job,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tupsert: true,\n\t\t\t\t\t\treturnDocument: 'after',\n\t\t\t\t\t},\n\t\t\t\t);\n\n\t\t\t\tif (!result) {\n\t\t\t\t\tthrow new ConnectionError(\n\t\t\t\t\t\t'Failed to schedule job: findOneAndUpdate returned no document',\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn this.documentToPersistedJob<T>(result as WithId<Document>);\n\t\t\t}\n\n\t\t\tconst result = await this.collection?.insertOne(job as Document);\n\n\t\t\tif (!result) {\n\t\t\t\tthrow new ConnectionError('Failed to schedule job: collection not available');\n\t\t\t}\n\n\t\t\treturn { ...job, _id: result.insertedId } as PersistedJob<T>;\n\t\t} catch (error) {\n\t\t\tif (error instanceof MonqueError) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst message = error instanceof Error ? error.message : 'Unknown error during schedule';\n\t\t\tthrow new ConnectionError(\n\t\t\t\t`Failed to schedule job: ${message}`,\n\t\t\t\terror instanceof Error ? { cause: error } : undefined,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Register a worker to process jobs of a specific type.\n\t *\n\t * Workers can be registered before or after calling `start()`. Each worker\n\t * processes jobs concurrently up to its configured concurrency limit (default: 5).\n\t *\n\t * The handler function receives the full job object including metadata (`_id`, `status`,\n\t * `failCount`, etc.). If the handler throws an error, the job is retried with exponential\n\t * backoff up to `maxRetries` times. After exhausting retries, the job is marked as `failed`.\n\t *\n\t * Events are emitted during job processing: `job:start`, `job:complete`, `job:fail`, and `job:error`.\n\t *\n\t * **Duplicate Registration**: By default, registering a worker for a job name that already has\n\t * a worker will throw a `WorkerRegistrationError`. This fail-fast behavior prevents accidental\n\t * replacement of handlers. To explicitly replace a worker, pass `{ replace: true }`.\n\t *\n\t * @template T - The job data payload type for type-safe access to `job.data`\n\t * @param name - Job type identifier to handle\n\t * @param handler - Async function to execute for each job\n\t * @param options - Worker configuration\n\t * @param options.concurrency - Maximum concurrent jobs for this worker (default: `defaultConcurrency`)\n\t * @param options.replace - When `true`, replace existing worker instead of throwing error\n\t * @throws {WorkerRegistrationError} When a worker is already registered for `name` and `replace` is not `true`\n\t *\n\t * @example Basic email worker\n\t * ```typescript\n\t * interface EmailJob {\n\t * to: string;\n\t * subject: string;\n\t * body: string;\n\t * }\n\t *\n\t * monque.worker<EmailJob>('send-email', async (job) => {\n\t * await emailService.send(job.data.to, job.data.subject, job.data.body);\n\t * });\n\t * ```\n\t *\n\t * @example Worker with custom concurrency\n\t * ```typescript\n\t * // Limit to 2 concurrent video processing jobs (resource-intensive)\n\t * monque.worker('process-video', async (job) => {\n\t * await videoProcessor.transcode(job.data.videoId);\n\t * }, { concurrency: 2 });\n\t * ```\n\t *\n\t * @example Replacing an existing worker\n\t * ```typescript\n\t * // Replace the existing handler for 'send-email'\n\t * monque.worker('send-email', newEmailHandler, { replace: true });\n\t * ```\n\t *\n\t * @example Worker with error handling\n\t * ```typescript\n\t * monque.worker('sync-user', async (job) => {\n\t * try {\n\t * await externalApi.syncUser(job.data.userId);\n\t * } catch (error) {\n\t * // Job will retry with exponential backoff\n\t * // Delay = 2^failCount × baseRetryInterval (default: 1000ms)\n\t * throw new Error(`Sync failed: ${error.message}`);\n\t * }\n\t * });\n\t * ```\n\t */\n\tworker<T>(name: string, handler: JobHandler<T>, options: WorkerOptions = {}): void {\n\t\tconst concurrency = options.concurrency ?? this.options.defaultConcurrency;\n\n\t\t// Check for existing worker and throw unless replace is explicitly true\n\t\tif (this.workers.has(name) && options.replace !== true) {\n\t\t\tthrow new WorkerRegistrationError(\n\t\t\t\t`Worker already registered for job name \"${name}\". Use { replace: true } to replace.`,\n\t\t\t\tname,\n\t\t\t);\n\t\t}\n\n\t\tthis.workers.set(name, {\n\t\t\thandler: handler as JobHandler,\n\t\t\tconcurrency,\n\t\t\tactiveJobs: new Map(),\n\t\t});\n\t}\n\n\t/**\n\t * Start polling for and processing jobs.\n\t *\n\t * Begins polling MongoDB at the configured interval (default: 1 second) to pick up\n\t * pending jobs and dispatch them to registered workers. Must call `initialize()` first.\n\t * Workers can be registered before or after calling `start()`.\n\t *\n\t * Jobs are processed concurrently up to each worker's configured concurrency limit.\n\t * The scheduler continues running until `stop()` is called.\n\t *\n\t * @example Basic startup\n\t * ```typescript\n\t * const monque = new Monque(db);\n\t * await monque.initialize();\n\t *\n\t * monque.worker('send-email', emailHandler);\n\t * monque.worker('process-order', orderHandler);\n\t *\n\t * monque.start(); // Begin processing jobs\n\t * ```\n\t *\n\t * @example With event monitoring\n\t * ```typescript\n\t * monque.on('job:start', (job) => {\n\t * logger.info(`Starting job ${job.name}`);\n\t * });\n\t *\n\t * monque.on('job:complete', ({ job, duration }) => {\n\t * metrics.recordJobDuration(job.name, duration);\n\t * });\n\t *\n\t * monque.on('job:fail', ({ job, error, willRetry }) => {\n\t * logger.error(`Job ${job.name} failed:`, error);\n\t * if (!willRetry) {\n\t * alerting.sendAlert(`Job permanently failed: ${job.name}`);\n\t * }\n\t * });\n\t *\n\t * monque.start();\n\t * ```\n\t *\n\t * @throws {ConnectionError} If scheduler not initialized (call `initialize()` first)\n\t */\n\tstart(): void {\n\t\tif (this.isRunning) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.isInitialized) {\n\t\t\tthrow new ConnectionError('Monque not initialized. Call initialize() before start().');\n\t\t}\n\n\t\tthis.isRunning = true;\n\n\t\t// Set up change streams as the primary notification mechanism\n\t\tthis.setupChangeStream();\n\n\t\t// Set up polling as backup (runs at configured interval)\n\t\tthis.pollIntervalId = setInterval(() => {\n\t\t\tthis.poll().catch((error: unknown) => {\n\t\t\t\tthis.emit('job:error', { error: error as Error });\n\t\t\t});\n\t\t}, this.options.pollInterval);\n\n\t\t// Start heartbeat interval for claimed jobs\n\t\tthis.heartbeatIntervalId = setInterval(() => {\n\t\t\tthis.updateHeartbeats().catch((error: unknown) => {\n\t\t\t\tthis.emit('job:error', { error: error as Error });\n\t\t\t});\n\t\t}, this.options.heartbeatInterval);\n\n\t\t// Start cleanup interval if retention is configured\n\t\tif (this.options.jobRetention) {\n\t\t\tconst interval = this.options.jobRetention.interval ?? DEFAULTS.retentionInterval;\n\n\t\t\t// Run immediately on start\n\t\t\tthis.cleanupJobs().catch((error: unknown) => {\n\t\t\t\tthis.emit('job:error', { error: error as Error });\n\t\t\t});\n\n\t\t\tthis.cleanupIntervalId = setInterval(() => {\n\t\t\t\tthis.cleanupJobs().catch((error: unknown) => {\n\t\t\t\t\tthis.emit('job:error', { error: error as Error });\n\t\t\t\t});\n\t\t\t}, interval);\n\t\t}\n\n\t\t// Run initial poll immediately to pick up any existing jobs\n\t\tthis.poll().catch((error: unknown) => {\n\t\t\tthis.emit('job:error', { error: error as Error });\n\t\t});\n\t}\n\n\t/**\n\t * Stop the scheduler gracefully, waiting for in-progress jobs to complete.\n\t *\n\t * Stops polling for new jobs and waits for all active jobs to finish processing.\n\t * Times out after the configured `shutdownTimeout` (default: 30 seconds), emitting\n\t * a `job:error` event with a `ShutdownTimeoutError` containing incomplete jobs.\n\t * On timeout, jobs still in progress are left as `processing` for stale job recovery.\n\t *\n\t * It's safe to call `stop()` multiple times - subsequent calls are no-ops if already stopped.\n\t *\n\t * @returns Promise that resolves when all jobs complete or timeout is reached\n\t *\n\t * @example Graceful application shutdown\n\t * ```typescript\n\t * process.on('SIGTERM', async () => {\n\t * console.log('Shutting down gracefully...');\n\t * await monque.stop(); // Wait for jobs to complete\n\t * await mongoClient.close();\n\t * process.exit(0);\n\t * });\n\t * ```\n\t *\n\t * @example With timeout handling\n\t * ```typescript\n\t * monque.on('job:error', ({ error }) => {\n\t * if (error.name === 'ShutdownTimeoutError') {\n\t * logger.warn('Forced shutdown after timeout:', error.incompleteJobs);\n\t * }\n\t * });\n\t *\n\t * await monque.stop();\n\t * ```\n\t */\n\tasync stop(): Promise<void> {\n\t\tif (!this.isRunning) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.isRunning = false;\n\n\t\t// Close change stream\n\t\tawait this.closeChangeStream();\n\n\t\t// Clear debounce timer\n\t\tif (this.changeStreamDebounceTimer) {\n\t\t\tclearTimeout(this.changeStreamDebounceTimer);\n\t\t\tthis.changeStreamDebounceTimer = null;\n\t\t}\n\n\t\t// Clear reconnection timer\n\t\tif (this.changeStreamReconnectTimer) {\n\t\t\tclearTimeout(this.changeStreamReconnectTimer);\n\t\t\tthis.changeStreamReconnectTimer = null;\n\t\t}\n\n\t\tif (this.cleanupIntervalId) {\n\t\t\tclearInterval(this.cleanupIntervalId);\n\t\t\tthis.cleanupIntervalId = null;\n\t\t}\n\n\t\t// Clear polling interval\n\t\tif (this.pollIntervalId) {\n\t\t\tclearInterval(this.pollIntervalId);\n\t\t\tthis.pollIntervalId = null;\n\t\t}\n\n\t\t// Clear heartbeat interval\n\t\tif (this.heartbeatIntervalId) {\n\t\t\tclearInterval(this.heartbeatIntervalId);\n\t\t\tthis.heartbeatIntervalId = null;\n\t\t}\n\n\t\t// Wait for all active jobs to complete (with timeout)\n\t\tconst activeJobs = this.getActiveJobs();\n\t\tif (activeJobs.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Create a promise that resolves when all jobs are done\n\t\tlet checkInterval: ReturnType<typeof setInterval> | undefined;\n\t\tconst waitForJobs = new Promise<undefined>((resolve) => {\n\t\t\tcheckInterval = setInterval(() => {\n\t\t\t\tif (this.getActiveJobs().length === 0) {\n\t\t\t\t\tclearInterval(checkInterval);\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t}\n\t\t\t}, 100);\n\t\t});\n\n\t\t// Race between job completion and timeout\n\t\tconst timeout = new Promise<'timeout'>((resolve) => {\n\t\t\tsetTimeout(() => resolve('timeout'), this.options.shutdownTimeout);\n\t\t});\n\n\t\tlet result: undefined | 'timeout';\n\n\t\ttry {\n\t\t\tresult = await Promise.race([waitForJobs, timeout]);\n\t\t} finally {\n\t\t\tif (checkInterval) {\n\t\t\t\tclearInterval(checkInterval);\n\t\t\t}\n\t\t}\n\n\t\tif (result === 'timeout') {\n\t\t\tconst incompleteJobs = this.getActiveJobsList();\n\t\t\tconst { ShutdownTimeoutError } = await import('@/shared/errors.js');\n\n\t\t\tconst error = new ShutdownTimeoutError(\n\t\t\t\t`Shutdown timed out after ${this.options.shutdownTimeout}ms with ${incompleteJobs.length} incomplete jobs`,\n\t\t\t\tincompleteJobs,\n\t\t\t);\n\t\t\tthis.emit('job:error', { error });\n\t\t}\n\t}\n\n\t/**\n\t * Check if the scheduler is healthy (running and connected).\n\t *\n\t * Returns `true` when the scheduler is started, initialized, and has an active\n\t * MongoDB collection reference. Useful for health check endpoints and monitoring.\n\t *\n\t * A healthy scheduler:\n\t * - Has called `initialize()` successfully\n\t * - Has called `start()` and is actively polling\n\t * - Has a valid MongoDB collection reference\n\t *\n\t * @returns `true` if scheduler is running and connected, `false` otherwise\n\t *\n\t * @example Express health check endpoint\n\t * ```typescript\n\t * app.get('/health', (req, res) => {\n\t * const healthy = monque.isHealthy();\n\t * res.status(healthy ? 200 : 503).json({\n\t * status: healthy ? 'ok' : 'unavailable',\n\t * scheduler: healthy,\n\t * timestamp: new Date().toISOString()\n\t * });\n\t * });\n\t * ```\n\t *\n\t * @example Kubernetes readiness probe\n\t * ```typescript\n\t * app.get('/readyz', (req, res) => {\n\t * if (monque.isHealthy() && dbConnected) {\n\t * res.status(200).send('ready');\n\t * } else {\n\t * res.status(503).send('not ready');\n\t * }\n\t * });\n\t * ```\n\t *\n\t * @example Periodic health monitoring\n\t * ```typescript\n\t * setInterval(() => {\n\t * if (!monque.isHealthy()) {\n\t * logger.error('Scheduler unhealthy');\n\t * metrics.increment('scheduler.unhealthy');\n\t * }\n\t * }, 60000); // Check every minute\n\t * ```\n\t */\n\tisHealthy(): boolean {\n\t\treturn this.isRunning && this.isInitialized && this.collection !== null;\n\t}\n\n\t/**\n\t * Query jobs from the queue with optional filters.\n\t *\n\t * Provides read-only access to job data for monitoring, debugging, and\n\t * administrative purposes. Results are ordered by `nextRunAt` ascending.\n\t *\n\t * @template T - The expected type of the job data payload\n\t * @param filter - Optional filter criteria\n\t * @returns Promise resolving to array of matching jobs\n\t * @throws {ConnectionError} If scheduler not initialized\n\t *\n\t * @example Get all pending jobs\n\t * ```typescript\n\t * const pendingJobs = await monque.getJobs({ status: JobStatus.PENDING });\n\t * console.log(`${pendingJobs.length} jobs waiting`);\n\t * ```\n\t *\n\t * @example Get failed email jobs\n\t * ```typescript\n\t * const failedEmails = await monque.getJobs({\n\t * name: 'send-email',\n\t * status: JobStatus.FAILED,\n\t * });\n\t * for (const job of failedEmails) {\n\t * console.error(`Job ${job._id} failed: ${job.failReason}`);\n\t * }\n\t * ```\n\t *\n\t * @example Paginated job listing\n\t * ```typescript\n\t * const page1 = await monque.getJobs({ limit: 50, skip: 0 });\n\t * const page2 = await monque.getJobs({ limit: 50, skip: 50 });\n\t * ```\n\t *\n\t * @example Use with type guards from @monque/core\n\t * ```typescript\n\t * import { isPendingJob, isRecurringJob } from '@monque/core';\n\t *\n\t * const jobs = await monque.getJobs();\n\t * const pendingRecurring = jobs.filter(job => isPendingJob(job) && isRecurringJob(job));\n\t * ```\n\t */\n\tasync getJobs<T = unknown>(filter: GetJobsFilter = {}): Promise<PersistedJob<T>[]> {\n\t\tthis.ensureInitialized();\n\n\t\tif (!this.collection) {\n\t\t\tthrow new ConnectionError('Failed to query jobs: collection not available');\n\t\t}\n\n\t\tconst query: Document = {};\n\n\t\tif (filter.name !== undefined) {\n\t\t\tquery['name'] = filter.name;\n\t\t}\n\n\t\tif (filter.status !== undefined) {\n\t\t\tif (Array.isArray(filter.status)) {\n\t\t\t\tquery['status'] = { $in: filter.status };\n\t\t\t} else {\n\t\t\t\tquery['status'] = filter.status;\n\t\t\t}\n\t\t}\n\n\t\tconst limit = filter.limit ?? 100;\n\t\tconst skip = filter.skip ?? 0;\n\n\t\ttry {\n\t\t\tconst cursor = this.collection.find(query).sort({ nextRunAt: 1 }).skip(skip).limit(limit);\n\n\t\t\tconst docs = await cursor.toArray();\n\t\t\treturn docs.map((doc) => this.documentToPersistedJob<T>(doc));\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : 'Unknown error during getJobs';\n\t\t\tthrow new ConnectionError(\n\t\t\t\t`Failed to query jobs: ${message}`,\n\t\t\t\terror instanceof Error ? { cause: error } : undefined,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Get a single job by its MongoDB ObjectId.\n\t *\n\t * Useful for retrieving job details when you have a job ID from events,\n\t * logs, or stored references.\n\t *\n\t * @template T - The expected type of the job data payload\n\t * @param id - The job's ObjectId\n\t * @returns Promise resolving to the job if found, null otherwise\n\t * @throws {ConnectionError} If scheduler not initialized\n\t *\n\t * @example Look up job from event\n\t * ```typescript\n\t * monque.on('job:fail', async ({ job }) => {\n\t * // Later, retrieve the job to check its status\n\t * const currentJob = await monque.getJob(job._id);\n\t * console.log(`Job status: ${currentJob?.status}`);\n\t * });\n\t * ```\n\t *\n\t * @example Admin endpoint\n\t * ```typescript\n\t * app.get('/jobs/:id', async (req, res) => {\n\t * const job = await monque.getJob(new ObjectId(req.params.id));\n\t * if (!job) {\n\t * return res.status(404).json({ error: 'Job not found' });\n\t * }\n\t * res.json(job);\n\t * });\n\t * ```\n\t */\n\tasync getJob<T = unknown>(id: ObjectId): Promise<PersistedJob<T> | null> {\n\t\tthis.ensureInitialized();\n\n\t\tif (!this.collection) {\n\t\t\tthrow new ConnectionError('Failed to get job: collection not available');\n\t\t}\n\n\t\ttry {\n\t\t\tconst doc = await this.collection.findOne({ _id: id });\n\t\t\tif (!doc) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn this.documentToPersistedJob<T>(doc as WithId<Document>);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : 'Unknown error during getJob';\n\t\t\tthrow new ConnectionError(\n\t\t\t\t`Failed to get job: ${message}`,\n\t\t\t\terror instanceof Error ? { cause: error } : undefined,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Poll for available jobs and process them.\n\t *\n\t * Called at regular intervals (configured by `pollInterval`). For each registered worker,\n\t * attempts to acquire jobs up to the worker's available concurrency slots.\n\t *\n\t * @private\n\t */\n\tprivate async poll(): Promise<void> {\n\t\tif (!this.isRunning || !this.collection) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (const [name, worker] of this.workers) {\n\t\t\t// Check if worker has capacity\n\t\t\tconst availableSlots = worker.concurrency - worker.activeJobs.size;\n\n\t\t\tif (availableSlots <= 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Try to acquire jobs up to available slots\n\t\t\tfor (let i = 0; i < availableSlots; i++) {\n\t\t\t\tconst job = await this.acquireJob(name);\n\n\t\t\t\tif (job) {\n\t\t\t\t\tthis.processJob(job, worker).catch((error: unknown) => {\n\t\t\t\t\t\tthis.emit('job:error', { error: error as Error, job });\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t// No more jobs available for this worker\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Atomically acquire a pending job for processing using the claimedBy pattern.\n\t *\n\t * Uses MongoDB's `findOneAndUpdate` with atomic operations to ensure only one scheduler\n\t * instance can claim a job. The query ensures the job is:\n\t * - In pending status\n\t * - Has nextRunAt <= now\n\t * - Is not claimed by another instance (claimedBy is null/undefined)\n\t *\n\t * @private\n\t * @param name - The job type to acquire\n\t * @returns The acquired job with updated status, claimedBy, and heartbeat info, or `null` if no jobs available\n\t */\n\tprivate async acquireJob(name: string): Promise<PersistedJob | null> {\n\t\tif (!this.collection) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst now = new Date();\n\n\t\tconst result = await this.collection.findOneAndUpdate(\n\t\t\t{\n\t\t\t\tname,\n\t\t\t\tstatus: JobStatus.PENDING,\n\t\t\t\tnextRunAt: { $lte: now },\n\t\t\t\t$or: [{ claimedBy: null }, { claimedBy: { $exists: false } }],\n\t\t\t},\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tstatus: JobStatus.PROCESSING,\n\t\t\t\t\tclaimedBy: this.options.schedulerInstanceId,\n\t\t\t\t\tlockedAt: now,\n\t\t\t\t\tlastHeartbeat: now,\n\t\t\t\t\theartbeatInterval: this.options.heartbeatInterval,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tsort: { nextRunAt: 1 },\n\t\t\t\treturnDocument: 'after',\n\t\t\t},\n\t\t);\n\n\t\tif (!result) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn this.documentToPersistedJob(result as WithId<Document>);\n\t}\n\n\t/**\n\t * Execute a job using its registered worker handler.\n\t *\n\t * Tracks the job as active during processing, emits lifecycle events, and handles\n\t * both success and failure cases. On success, calls `completeJob()`. On failure,\n\t * calls `failJob()` which implements exponential backoff retry logic.\n\t *\n\t * @private\n\t * @param job - The job to process\n\t * @param worker - The worker registration containing the handler and active job tracking\n\t */\n\tprivate async processJob(job: PersistedJob, worker: WorkerRegistration): Promise<void> {\n\t\tconst jobId = job._id.toString();\n\t\tworker.activeJobs.set(jobId, job);\n\n\t\tconst startTime = Date.now();\n\t\tthis.emit('job:start', job);\n\n\t\ttry {\n\t\t\tawait worker.handler(job);\n\n\t\t\t// Job completed successfully\n\t\t\tconst duration = Date.now() - startTime;\n\t\t\tawait this.completeJob(job);\n\t\t\tthis.emit('job:complete', { job, duration });\n\t\t} catch (error) {\n\t\t\t// Job failed\n\t\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\t\tawait this.failJob(job, err);\n\n\t\t\tconst willRetry = job.failCount + 1 < this.options.maxRetries;\n\t\t\tthis.emit('job:fail', { job, error: err, willRetry });\n\t\t} finally {\n\t\t\tworker.activeJobs.delete(jobId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark a job as completed successfully.\n\t *\n\t * For recurring jobs (with `repeatInterval`), schedules the next run based on the cron\n\t * expression and resets `failCount` to 0. For one-time jobs, sets status to `completed`.\n\t * Clears `lockedAt` and `failReason` fields in both cases.\n\t *\n\t * @private\n\t * @param job - The job that completed successfully\n\t */\n\tprivate async completeJob(job: Job): Promise<void> {\n\t\tif (!this.collection || !isPersistedJob(job)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (job.repeatInterval) {\n\t\t\t// Recurring job - schedule next run\n\t\t\tconst nextRunAt = getNextCronDate(job.repeatInterval);\n\t\t\tawait this.collection.updateOne(\n\t\t\t\t{ _id: job._id },\n\t\t\t\t{\n\t\t\t\t\t$set: {\n\t\t\t\t\t\tstatus: JobStatus.PENDING,\n\t\t\t\t\t\tnextRunAt,\n\t\t\t\t\t\tfailCount: 0,\n\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t},\n\t\t\t\t\t$unset: {\n\t\t\t\t\t\tlockedAt: '',\n\t\t\t\t\t\tclaimedBy: '',\n\t\t\t\t\t\tlastHeartbeat: '',\n\t\t\t\t\t\theartbeatInterval: '',\n\t\t\t\t\t\tfailReason: '',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t} else {\n\t\t\t// One-time job - mark as completed\n\t\t\tawait this.collection.updateOne(\n\t\t\t\t{ _id: job._id },\n\t\t\t\t{\n\t\t\t\t\t$set: {\n\t\t\t\t\t\tstatus: JobStatus.COMPLETED,\n\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t},\n\t\t\t\t\t$unset: {\n\t\t\t\t\t\tlockedAt: '',\n\t\t\t\t\t\tclaimedBy: '',\n\t\t\t\t\t\tlastHeartbeat: '',\n\t\t\t\t\t\theartbeatInterval: '',\n\t\t\t\t\t\tfailReason: '',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\tjob.status = JobStatus.COMPLETED;\n\t\t}\n\t}\n\n\t/**\n\t * Handle job failure with exponential backoff retry logic.\n\t *\n\t * Increments `failCount` and calculates next retry time using exponential backoff:\n\t * `nextRunAt = 2^failCount × baseRetryInterval` (capped by optional `maxBackoffDelay`).\n\t *\n\t * If `failCount >= maxRetries`, marks job as permanently `failed`. Otherwise, resets\n\t * to `pending` status for retry. Stores error message in `failReason` field.\n\t *\n\t * @private\n\t * @param job - The job that failed\n\t * @param error - The error that caused the failure\n\t */\n\tprivate async failJob(job: Job, error: Error): Promise<void> {\n\t\tif (!this.collection || !isPersistedJob(job)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst newFailCount = job.failCount + 1;\n\n\t\tif (newFailCount >= this.options.maxRetries) {\n\t\t\t// Permanent failure\n\t\t\tawait this.collection.updateOne(\n\t\t\t\t{ _id: job._id },\n\t\t\t\t{\n\t\t\t\t\t$set: {\n\t\t\t\t\t\tstatus: JobStatus.FAILED,\n\t\t\t\t\t\tfailCount: newFailCount,\n\t\t\t\t\t\tfailReason: error.message,\n\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t},\n\t\t\t\t\t$unset: {\n\t\t\t\t\t\tlockedAt: '',\n\t\t\t\t\t\tclaimedBy: '',\n\t\t\t\t\t\tlastHeartbeat: '',\n\t\t\t\t\t\theartbeatInterval: '',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t} else {\n\t\t\t// Schedule retry with exponential backoff\n\t\t\tconst nextRunAt = calculateBackoff(\n\t\t\t\tnewFailCount,\n\t\t\t\tthis.options.baseRetryInterval,\n\t\t\t\tthis.options.maxBackoffDelay,\n\t\t\t);\n\n\t\t\tawait this.collection.updateOne(\n\t\t\t\t{ _id: job._id },\n\t\t\t\t{\n\t\t\t\t\t$set: {\n\t\t\t\t\t\tstatus: JobStatus.PENDING,\n\t\t\t\t\t\tfailCount: newFailCount,\n\t\t\t\t\t\tfailReason: error.message,\n\t\t\t\t\t\tnextRunAt,\n\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t},\n\t\t\t\t\t$unset: {\n\t\t\t\t\t\tlockedAt: '',\n\t\t\t\t\t\tclaimedBy: '',\n\t\t\t\t\t\tlastHeartbeat: '',\n\t\t\t\t\t\theartbeatInterval: '',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Ensure the scheduler is initialized before operations.\n\t *\n\t * @private\n\t * @throws {ConnectionError} If scheduler not initialized or collection unavailable\n\t */\n\tprivate ensureInitialized(): void {\n\t\tif (!this.isInitialized || !this.collection) {\n\t\t\tthrow new ConnectionError('Monque not initialized. Call initialize() first.');\n\t\t}\n\t}\n\n\t/**\n\t * Update heartbeats for all jobs claimed by this scheduler instance.\n\t *\n\t * This method runs periodically while the scheduler is running to indicate\n\t * that jobs are still being actively processed.\n\t *\n\t * `lastHeartbeat` is primarily an observability signal (monitoring/debugging).\n\t * Stale recovery is based on `lockedAt` + `lockTimeout`.\n\t *\n\t * @private\n\t */\n\tprivate async updateHeartbeats(): Promise<void> {\n\t\tif (!this.collection || !this.isRunning) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst now = new Date();\n\n\t\tawait this.collection.updateMany(\n\t\t\t{\n\t\t\t\tclaimedBy: this.options.schedulerInstanceId,\n\t\t\t\tstatus: JobStatus.PROCESSING,\n\t\t\t},\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tlastHeartbeat: now,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t}\n\n\t/**\n\t * Set up MongoDB Change Stream for real-time job notifications.\n\t *\n\t * Change streams provide instant notifications when jobs are inserted or when\n\t * job status changes to pending (e.g., after a retry). This eliminates the\n\t * polling delay for reactive job processing.\n\t *\n\t * The change stream watches for:\n\t * - Insert operations (new jobs)\n\t * - Update operations where status field changes\n\t *\n\t * If change streams are unavailable (e.g., standalone MongoDB), the system\n\t * gracefully falls back to polling-only mode.\n\t *\n\t * @private\n\t */\n\tprivate setupChangeStream(): void {\n\t\tif (!this.collection || !this.isRunning) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\t// Create change stream with pipeline to filter relevant events\n\t\t\tconst pipeline = [\n\t\t\t\t{\n\t\t\t\t\t$match: {\n\t\t\t\t\t\t$or: [\n\t\t\t\t\t\t\t{ operationType: 'insert' },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\toperationType: 'update',\n\t\t\t\t\t\t\t\t'updateDescription.updatedFields.status': { $exists: true },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t];\n\n\t\t\tthis.changeStream = this.collection.watch(pipeline, {\n\t\t\t\tfullDocument: 'updateLookup',\n\t\t\t});\n\n\t\t\t// Handle change events\n\t\t\tthis.changeStream.on('change', (change) => {\n\t\t\t\tthis.handleChangeStreamEvent(change);\n\t\t\t});\n\n\t\t\t// Handle errors with reconnection\n\t\t\tthis.changeStream.on('error', (error: Error) => {\n\t\t\t\tthis.emit('changestream:error', { error });\n\t\t\t\tthis.handleChangeStreamError(error);\n\t\t\t});\n\n\t\t\t// Mark as connected\n\t\t\tthis.usingChangeStreams = true;\n\t\t\tthis.changeStreamReconnectAttempts = 0;\n\t\t\tthis.emit('changestream:connected', undefined);\n\t\t} catch (error) {\n\t\t\t// Change streams not available (e.g., standalone MongoDB)\n\t\t\tthis.usingChangeStreams = false;\n\t\t\tconst reason = error instanceof Error ? error.message : 'Unknown error';\n\t\t\tthis.emit('changestream:fallback', { reason });\n\t\t}\n\t}\n\n\t/**\n\t * Handle a change stream event by triggering a debounced poll.\n\t *\n\t * Events are debounced to prevent \"claim storms\" when multiple changes arrive\n\t * in rapid succession (e.g., bulk job inserts). A 100ms debounce window\n\t * collects multiple events and triggers a single poll.\n\t *\n\t * @private\n\t * @param change - The change stream event document\n\t */\n\tprivate handleChangeStreamEvent(change: ChangeStreamDocument<Document>): void {\n\t\tif (!this.isRunning) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Trigger poll on insert (new job) or update where status changes\n\t\tconst isInsert = change.operationType === 'insert';\n\t\tconst isUpdate = change.operationType === 'update';\n\n\t\t// Get fullDocument if available (for insert or with updateLookup option)\n\t\tconst fullDocument = 'fullDocument' in change ? change.fullDocument : undefined;\n\t\tconst isPendingStatus = fullDocument?.['status'] === JobStatus.PENDING;\n\n\t\t// For inserts: always trigger since new pending jobs need processing\n\t\t// For updates: trigger if status changed to pending (retry/release scenario)\n\t\tconst shouldTrigger = isInsert || (isUpdate && isPendingStatus);\n\n\t\tif (shouldTrigger) {\n\t\t\t// Debounce poll triggers to avoid claim storms\n\t\t\tif (this.changeStreamDebounceTimer) {\n\t\t\t\tclearTimeout(this.changeStreamDebounceTimer);\n\t\t\t}\n\n\t\t\tthis.changeStreamDebounceTimer = setTimeout(() => {\n\t\t\t\tthis.changeStreamDebounceTimer = null;\n\t\t\t\tthis.poll().catch((error: unknown) => {\n\t\t\t\t\tthis.emit('job:error', { error: error as Error });\n\t\t\t\t});\n\t\t\t}, 100);\n\t\t}\n\t}\n\n\t/**\n\t * Handle change stream errors with exponential backoff reconnection.\n\t *\n\t * Attempts to reconnect up to `maxChangeStreamReconnectAttempts` times with\n\t * exponential backoff (base 1000ms). After exhausting retries, falls back to\n\t * polling-only mode.\n\t *\n\t * @private\n\t * @param error - The error that caused the change stream failure\n\t */\n\tprivate handleChangeStreamError(error: Error): void {\n\t\tif (!this.isRunning) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.changeStreamReconnectAttempts++;\n\n\t\tif (this.changeStreamReconnectAttempts > this.maxChangeStreamReconnectAttempts) {\n\t\t\t// Fall back to polling-only mode\n\t\t\tthis.usingChangeStreams = false;\n\t\t\tthis.emit('changestream:fallback', {\n\t\t\t\treason: `Exhausted ${this.maxChangeStreamReconnectAttempts} reconnection attempts: ${error.message}`,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Exponential backoff: 1s, 2s, 4s\n\t\tconst delay = 2 ** (this.changeStreamReconnectAttempts - 1) * 1000;\n\n\t\t// Clear any existing reconnect timer before scheduling a new one\n\t\tif (this.changeStreamReconnectTimer) {\n\t\t\tclearTimeout(this.changeStreamReconnectTimer);\n\t\t}\n\n\t\tthis.changeStreamReconnectTimer = setTimeout(() => {\n\t\t\tthis.changeStreamReconnectTimer = null;\n\t\t\tif (this.isRunning) {\n\t\t\t\t// Close existing change stream before reconnecting\n\t\t\t\tif (this.changeStream) {\n\t\t\t\t\tthis.changeStream.close().catch(() => {});\n\t\t\t\t\tthis.changeStream = null;\n\t\t\t\t}\n\t\t\t\tthis.setupChangeStream();\n\t\t\t}\n\t\t}, delay);\n\t}\n\n\t/**\n\t * Close the change stream cursor and emit closed event.\n\t *\n\t * @private\n\t */\n\tprivate async closeChangeStream(): Promise<void> {\n\t\tif (this.changeStream) {\n\t\t\ttry {\n\t\t\t\tawait this.changeStream.close();\n\t\t\t} catch {\n\t\t\t\t// Ignore close errors during shutdown\n\t\t\t}\n\t\t\tthis.changeStream = null;\n\n\t\t\tif (this.usingChangeStreams) {\n\t\t\t\tthis.emit('changestream:closed', undefined);\n\t\t\t}\n\t\t}\n\n\t\tthis.usingChangeStreams = false;\n\t\tthis.changeStreamReconnectAttempts = 0;\n\t}\n\n\t/**\n\t * Get array of active job IDs across all workers.\n\t *\n\t * @private\n\t * @returns Array of job ID strings currently being processed\n\t */\n\tprivate getActiveJobs(): string[] {\n\t\tconst activeJobs: string[] = [];\n\t\tfor (const worker of this.workers.values()) {\n\t\t\tactiveJobs.push(...worker.activeJobs.keys());\n\t\t}\n\t\treturn activeJobs;\n\t}\n\n\t/**\n\t * Get list of active job documents (for shutdown timeout error).\n\t *\n\t * @private\n\t * @returns Array of active Job objects\n\t */\n\tprivate getActiveJobsList(): Job[] {\n\t\tconst activeJobs: Job[] = [];\n\t\tfor (const worker of this.workers.values()) {\n\t\t\tactiveJobs.push(...worker.activeJobs.values());\n\t\t}\n\t\treturn activeJobs;\n\t}\n\n\t/**\n\t * Convert a MongoDB document to a typed PersistedJob object.\n\t *\n\t * Maps raw MongoDB document fields to the strongly-typed `PersistedJob<T>` interface,\n\t * ensuring type safety and handling optional fields (`lockedAt`, `failReason`, etc.).\n\t *\n\t * @private\n\t * @template T - The job data payload type\n\t * @param doc - The raw MongoDB document with `_id`\n\t * @returns A strongly-typed PersistedJob object with guaranteed `_id`\n\t */\n\tprivate documentToPersistedJob<T>(doc: WithId<Document>): PersistedJob<T> {\n\t\tconst job: PersistedJob<T> = {\n\t\t\t_id: doc._id,\n\t\t\tname: doc['name'] as string,\n\t\t\tdata: doc['data'] as T,\n\t\t\tstatus: doc['status'] as JobStatusType,\n\t\t\tnextRunAt: doc['nextRunAt'] as Date,\n\t\t\tfailCount: doc['failCount'] as number,\n\t\t\tcreatedAt: doc['createdAt'] as Date,\n\t\t\tupdatedAt: doc['updatedAt'] as Date,\n\t\t};\n\n\t\t// Only set optional properties if they exist\n\t\tif (doc['lockedAt'] !== undefined) {\n\t\t\tjob.lockedAt = doc['lockedAt'] as Date | null;\n\t\t}\n\t\tif (doc['claimedBy'] !== undefined) {\n\t\t\tjob.claimedBy = doc['claimedBy'] as string | null;\n\t\t}\n\t\tif (doc['lastHeartbeat'] !== undefined) {\n\t\t\tjob.lastHeartbeat = doc['lastHeartbeat'] as Date | null;\n\t\t}\n\t\tif (doc['heartbeatInterval'] !== undefined) {\n\t\t\tjob.heartbeatInterval = doc['heartbeatInterval'] as number;\n\t\t}\n\t\tif (doc['failReason'] !== undefined) {\n\t\t\tjob.failReason = doc['failReason'] as string;\n\t\t}\n\t\tif (doc['repeatInterval'] !== undefined) {\n\t\t\tjob.repeatInterval = doc['repeatInterval'] as string;\n\t\t}\n\t\tif (doc['uniqueKey'] !== undefined) {\n\t\t\tjob.uniqueKey = doc['uniqueKey'] as string;\n\t\t}\n\n\t\treturn job;\n\t}\n\n\t/**\n\t * Type-safe event emitter methods\n\t */\n\toverride emit<K extends keyof MonqueEventMap>(event: K, payload: MonqueEventMap[K]): boolean {\n\t\treturn super.emit(event, payload);\n\t}\n\n\toverride on<K extends keyof MonqueEventMap>(\n\t\tevent: K,\n\t\tlistener: (payload: MonqueEventMap[K]) => void,\n\t): this {\n\t\treturn super.on(event, listener);\n\t}\n\n\toverride once<K extends keyof MonqueEventMap>(\n\t\tevent: K,\n\t\tlistener: (payload: MonqueEventMap[K]) => void,\n\t): this {\n\t\treturn super.once(event, listener);\n\t}\n\n\toverride off<K extends keyof MonqueEventMap>(\n\t\tevent: K,\n\t\tlistener: (payload: MonqueEventMap[K]) => void,\n\t): this {\n\t\treturn super.off(event, listener);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,YAAY;CAExB,SAAS;CAET,YAAY;CAEZ,WAAW;CAEX,QAAQ;CACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACSD,SAAgB,eAAkB,KAAqC;AACtE,QAAO,SAAS,OAAO,IAAI,QAAQ,UAAa,IAAI,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmC7D,SAAgB,iBAAiB,OAAwC;AACxE,QAAO,OAAO,UAAU,YAAY,OAAO,OAAO,UAAU,CAAC,SAAS,MAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;AA2B9F,SAAgB,aAAgB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;;;;;;;;;CAcR,AAAQ,uBAA0B,KAAwC;EACzE,MAAMC,MAAuB;GAC5B,KAAK,IAAI;GACT,MAAM,IAAI;GACV,MAAM,IAAI;GACV,QAAQ,IAAI;GACZ,WAAW,IAAI;GACf,WAAW,IAAI;GACf,WAAW,IAAI;GACf,WAAW,IAAI;GACf;AAGD,MAAI,IAAI,gBAAgB,OACvB,KAAI,WAAW,IAAI;AAEpB,MAAI,IAAI,iBAAiB,OACxB,KAAI,YAAY,IAAI;AAErB,MAAI,IAAI,qBAAqB,OAC5B,KAAI,gBAAgB,IAAI;AAEzB,MAAI,IAAI,yBAAyB,OAChC,KAAI,oBAAoB,IAAI;AAE7B,MAAI,IAAI,kBAAkB,OACzB,KAAI,aAAa,IAAI;AAEtB,MAAI,IAAI,sBAAsB,OAC7B,KAAI,iBAAiB,IAAI;AAE1B,MAAI,IAAI,iBAAiB,OACxB,KAAI,YAAY,IAAI;AAGrB,SAAO;;;;;CAMR,AAAS,KAAqC,OAAU,SAAqC;AAC5F,SAAO,MAAM,KAAK,OAAO,QAAQ;;CAGlC,AAAS,GACR,OACA,UACO;AACP,SAAO,MAAM,GAAG,OAAO,SAAS;;CAGjC,AAAS,KACR,OACA,UACO;AACP,SAAO,MAAM,KAAK,OAAO,SAAS;;CAGnC,AAAS,IACR,OACA,UACO;AACP,SAAO,MAAM,IAAI,OAAO,SAAS"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["result","ShutdownTimeoutError"],"sources":["../src/jobs/types.ts","../src/jobs/guards.ts","../src/shared/utils/backoff.ts","../src/shared/utils/cron.ts","../src/scheduler/monque.ts"],"sourcesContent":["import type { ObjectId } from 'mongodb';\n\n/**\n * Represents the lifecycle states of a job in the queue.\n *\n * Jobs transition through states as follows:\n * - PENDING → PROCESSING (when picked up by a worker)\n * - PROCESSING → COMPLETED (on success)\n * - PROCESSING → PENDING (on failure, if retries remain)\n * - PROCESSING → FAILED (on failure, after max retries exhausted)\n *\n * @example\n * ```typescript\n * if (job.status === JobStatus.PENDING) {\n * // job is waiting to be picked up\n * }\n * ```\n */\nexport const JobStatus = {\n\t/** Job is waiting to be picked up by a worker */\n\tPENDING: 'pending',\n\t/** Job is currently being executed by a worker */\n\tPROCESSING: 'processing',\n\t/** Job completed successfully */\n\tCOMPLETED: 'completed',\n\t/** Job permanently failed after exhausting all retry attempts */\n\tFAILED: 'failed',\n} as const;\n\n/**\n * Union type of all possible job status values: `'pending' | 'processing' | 'completed' | 'failed'`\n */\nexport type JobStatusType = (typeof JobStatus)[keyof typeof JobStatus];\n\n/**\n * Represents a job in the Monque queue.\n *\n * @template T - The type of the job's data payload\n *\n * @example\n * ```typescript\n * interface EmailJobData {\n * to: string;\n * subject: string;\n * template: string;\n * }\n *\n * const job: Job<EmailJobData> = {\n * name: 'send-email',\n * data: { to: 'user@example.com', subject: 'Welcome!', template: 'welcome' },\n * status: JobStatus.PENDING,\n * nextRunAt: new Date(),\n * failCount: 0,\n * createdAt: new Date(),\n * updatedAt: new Date(),\n * };\n * ```\n */\nexport interface Job<T = unknown> {\n\t/** MongoDB document identifier */\n\t_id?: ObjectId;\n\n\t/** Job type identifier, matches worker registration */\n\tname: string;\n\n\t/** Job payload - must be JSON-serializable */\n\tdata: T;\n\n\t/** Current lifecycle state */\n\tstatus: JobStatusType;\n\n\t/** When the job should be processed */\n\tnextRunAt: Date;\n\n\t/** Timestamp when job was locked for processing */\n\tlockedAt?: Date | null;\n\n\t/**\n\t * Unique identifier of the scheduler instance that claimed this job.\n\t * Used for atomic claim pattern - ensures only one instance processes each job.\n\t * Set when a job is claimed, cleared when job completes or fails.\n\t */\n\tclaimedBy?: string | null;\n\n\t/**\n\t * Timestamp of the last heartbeat update for this job.\n\t * Used to detect stale jobs when a scheduler instance crashes without releasing.\n\t * Updated periodically while job is being processed.\n\t */\n\tlastHeartbeat?: Date | null;\n\n\t/**\n\t * Heartbeat interval in milliseconds for this job.\n\t * Stored on the job to allow recovery logic to use the correct timeout.\n\t */\n\theartbeatInterval?: number;\n\n\t/** Number of failed attempts */\n\tfailCount: number;\n\n\t/** Last failure error message */\n\tfailReason?: string;\n\n\t/** Cron expression for recurring jobs */\n\trepeatInterval?: string;\n\n\t/** Deduplication key to prevent duplicate jobs */\n\tuniqueKey?: string;\n\n\t/** Job creation timestamp */\n\tcreatedAt: Date;\n\n\t/** Last modification timestamp */\n\tupdatedAt: Date;\n}\n\n/**\n * A job that has been persisted to MongoDB and has a guaranteed `_id`.\n * This is returned by `enqueue()`, `now()`, and `schedule()` methods.\n *\n * @template T - The type of the job's data payload\n */\nexport type PersistedJob<T = unknown> = Job<T> & { _id: ObjectId };\n\n/**\n * Options for enqueueing a job.\n *\n * @example\n * ```typescript\n * await monque.enqueue('sync-user', { userId: '123' }, {\n * uniqueKey: 'sync-user-123',\n * runAt: new Date(Date.now() + 5000), // Run in 5 seconds\n * });\n * ```\n */\nexport interface EnqueueOptions {\n\t/**\n\t * Deduplication key. If a job with this key is already pending or processing,\n\t * the enqueue operation will not create a duplicate.\n\t */\n\tuniqueKey?: string;\n\n\t/**\n\t * When the job should be processed. Defaults to immediately (new Date()).\n\t */\n\trunAt?: Date;\n}\n\n/**\n * Options for scheduling a recurring job.\n *\n * @example\n * ```typescript\n * await monque. schedule('0 * * * *', 'hourly-cleanup', { dir: '/tmp' }, {\n * uniqueKey: 'hourly-cleanup-job',\n * });\n * ```\n */\nexport interface ScheduleOptions {\n\t/**\n\t * Deduplication key. If a job with this key is already pending or processing,\n\t * the schedule operation will not create a duplicate.\n\t */\n\tuniqueKey?: string;\n}\n\n/**\n * Filter options for querying jobs.\n *\n * Use with `monque.getJobs()` to filter jobs by name, status, or limit results.\n *\n * @example\n * ```typescript\n * // Get all pending email jobs\n * const pendingEmails = await monque.getJobs({\n * name: 'send-email',\n * status: JobStatus.PENDING,\n * });\n *\n * // Get all failed or completed jobs (paginated)\n * const finishedJobs = await monque.getJobs({\n * status: [JobStatus.COMPLETED, JobStatus.FAILED],\n * limit: 50,\n * skip: 100,\n * });\n * ```\n */\nexport interface GetJobsFilter {\n\t/** Filter by job type name */\n\tname?: string;\n\n\t/** Filter by status (single or multiple) */\n\tstatus?: JobStatusType | JobStatusType[];\n\n\t/** Maximum number of jobs to return (default: 100) */\n\tlimit?: number;\n\n\t/** Number of jobs to skip for pagination */\n\tskip?: number;\n}\n\n/**\n * Handler function signature for processing jobs.\n *\n * @template T - The type of the job's data payload\n *\n * @example\n * ```typescript\n * const emailHandler: JobHandler<EmailJobData> = async (job) => {\n * await sendEmail(job.data.to, job.data.subject);\n * };\n * ```\n */\nexport type JobHandler<T = unknown> = (job: Job<T>) => Promise<void> | void;\n","import type { Job, JobStatusType, PersistedJob } from './types.js';\nimport { JobStatus } from './types.js';\n\n/**\n * Type guard to check if a job has been persisted to MongoDB.\n *\n * A persisted job is guaranteed to have an `_id` field, which means it has been\n * successfully inserted into the database. This is useful when you need to ensure\n * a job can be updated or referenced by its ID.\n *\n * @template T - The type of the job's data payload\n * @param job - The job to check\n * @returns `true` if the job has a valid `_id`, narrowing the type to `PersistedJob<T>`\n *\n * @example Basic usage\n * ```typescript\n * const job: Job<EmailData> = await monque.enqueue('send-email', emailData);\n *\n * if (isPersistedJob(job)) {\n * // TypeScript knows job._id exists\n * console.log(`Job ID: ${job._id.toString()}`);\n * }\n * ```\n *\n * @example In a conditional\n * ```typescript\n * function logJobId(job: Job) {\n * if (!isPersistedJob(job)) {\n * console.log('Job not yet persisted');\n * return;\n * }\n * // TypeScript knows job is PersistedJob here\n * console.log(`Processing job ${job._id.toString()}`);\n * }\n * ```\n */\nexport function isPersistedJob<T>(job: Job<T>): job is PersistedJob<T> {\n\treturn '_id' in job && job._id !== undefined && job._id !== null;\n}\n\n/**\n * Type guard to check if a value is a valid job status.\n *\n * Validates that a value is one of the four valid job statuses: `'pending'`,\n * `'processing'`, `'completed'`, or `'failed'`. Useful for runtime validation\n * of user input or external data.\n *\n * @param value - The value to check\n * @returns `true` if the value is a valid `JobStatusType`, narrowing the type\n *\n * @example Validating user input\n * ```typescript\n * function filterByStatus(status: string) {\n * if (!isValidJobStatus(status)) {\n * throw new Error(`Invalid status: ${status}`);\n * }\n * // TypeScript knows status is JobStatusType here\n * return db.jobs.find({ status });\n * }\n * ```\n *\n * @example Runtime validation\n * ```typescript\n * const statusFromApi = externalData.status;\n *\n * if (isValidJobStatus(statusFromApi)) {\n * job.status = statusFromApi;\n * } else {\n * job.status = JobStatus.PENDING;\n * }\n * ```\n */\nexport function isValidJobStatus(value: unknown): value is JobStatusType {\n\treturn typeof value === 'string' && Object.values(JobStatus).includes(value as JobStatusType);\n}\n\n/**\n * Type guard to check if a job is in pending status.\n *\n * A convenience helper for checking if a job is waiting to be processed.\n * Equivalent to `job.status === JobStatus.PENDING` but with better semantics.\n *\n * @template T - The type of the job's data payload\n * @param job - The job to check\n * @returns `true` if the job status is `'pending'`\n *\n * @example Filter pending jobs\n * ```typescript\n * const jobs = await monque.getJobs();\n * const pendingJobs = jobs.filter(isPendingJob);\n * console.log(`${pendingJobs.length} jobs waiting to be processed`);\n * ```\n *\n * @example Conditional logic\n * ```typescript\n * if (isPendingJob(job)) {\n * await monque.now(job.name, job.data);\n * }\n * ```\n */\nexport function isPendingJob<T>(job: Job<T>): boolean {\n\treturn job.status === JobStatus.PENDING;\n}\n\n/**\n * Type guard to check if a job is currently being processed.\n *\n * A convenience helper for checking if a job is actively running.\n * Equivalent to `job.status === JobStatus.PROCESSING` but with better semantics.\n *\n * @template T - The type of the job's data payload\n * @param job - The job to check\n * @returns `true` if the job status is `'processing'`\n *\n * @example Monitor active jobs\n * ```typescript\n * const jobs = await monque.getJobs();\n * const activeJobs = jobs.filter(isProcessingJob);\n * console.log(`${activeJobs.length} jobs currently running`);\n * ```\n */\nexport function isProcessingJob<T>(job: Job<T>): boolean {\n\treturn job.status === JobStatus.PROCESSING;\n}\n\n/**\n * Type guard to check if a job has completed successfully.\n *\n * A convenience helper for checking if a job finished without errors.\n * Equivalent to `job.status === JobStatus.COMPLETED` but with better semantics.\n *\n * @template T - The type of the job's data payload\n * @param job - The job to check\n * @returns `true` if the job status is `'completed'`\n *\n * @example Find completed jobs\n * ```typescript\n * const jobs = await monque.getJobs();\n * const completedJobs = jobs.filter(isCompletedJob);\n * console.log(`${completedJobs.length} jobs completed successfully`);\n * ```\n */\nexport function isCompletedJob<T>(job: Job<T>): boolean {\n\treturn job.status === JobStatus.COMPLETED;\n}\n\n/**\n * Type guard to check if a job has permanently failed.\n *\n * A convenience helper for checking if a job exhausted all retries.\n * Equivalent to `job.status === JobStatus.FAILED` but with better semantics.\n *\n * @template T - The type of the job's data payload\n * @param job - The job to check\n * @returns `true` if the job status is `'failed'`\n *\n * @example Handle failed jobs\n * ```typescript\n * const jobs = await monque.getJobs();\n * const failedJobs = jobs.filter(isFailedJob);\n *\n * for (const job of failedJobs) {\n * console.error(`Job ${job.name} failed: ${job.failReason}`);\n * await sendAlert(job);\n * }\n * ```\n */\nexport function isFailedJob<T>(job: Job<T>): boolean {\n\treturn job.status === JobStatus.FAILED;\n}\n\n/**\n * Type guard to check if a job is a recurring scheduled job.\n *\n * A recurring job has a `repeatInterval` cron expression and will be automatically\n * rescheduled after each successful completion.\n *\n * @template T - The type of the job's data payload\n * @param job - The job to check\n * @returns `true` if the job has a `repeatInterval` defined\n *\n * @example Filter recurring jobs\n * ```typescript\n * const jobs = await monque.getJobs();\n * const recurringJobs = jobs.filter(isRecurringJob);\n * console.log(`${recurringJobs.length} jobs will repeat automatically`);\n * ```\n *\n * @example Conditional cleanup\n * ```typescript\n * if (!isRecurringJob(job) && isCompletedJob(job)) {\n * // Safe to delete one-time completed jobs\n * await deleteJob(job._id);\n * }\n * ```\n */\nexport function isRecurringJob<T>(job: Job<T>): boolean {\n\treturn job.repeatInterval !== undefined && job.repeatInterval !== null;\n}\n","/**\n * Default base interval for exponential backoff in milliseconds.\n * @default 1000\n */\nexport const DEFAULT_BASE_INTERVAL = 1000;\n\n/**\n * Default maximum delay cap for exponential backoff in milliseconds.\n *\n * This prevents unbounded delays (e.g. failCount=20 is >11 days at 1s base)\n * and avoids precision/overflow issues for very large fail counts.\n * @default 86400000 (24 hours)\n */\nexport const DEFAULT_MAX_BACKOFF_DELAY = 24 * 60 * 60 * 1_000;\n\n/**\n * Calculate the next run time using exponential backoff.\n *\n * Formula: nextRunAt = now + (2^failCount × baseInterval)\n *\n * @param failCount - Number of previous failed attempts\n * @param baseInterval - Base interval in milliseconds (default: 1000ms)\n * @param maxDelay - Maximum delay in milliseconds (optional)\n * @returns The next run date\n *\n * @example\n * ```typescript\n * // First retry (failCount=1): 2^1 * 1000 = 2000ms delay\n * const nextRun = calculateBackoff(1);\n *\n * // Second retry (failCount=2): 2^2 * 1000 = 4000ms delay\n * const nextRun = calculateBackoff(2);\n *\n * // With custom base interval\n * const nextRun = calculateBackoff(3, 500); // 2^3 * 500 = 4000ms delay\n *\n * // With max delay\n * const nextRun = calculateBackoff(10, 1000, 60000); // capped at 60000ms\n * ```\n */\nexport function calculateBackoff(\n\tfailCount: number,\n\tbaseInterval: number = DEFAULT_BASE_INTERVAL,\n\tmaxDelay?: number,\n): Date {\n\tconst effectiveMaxDelay = maxDelay ?? DEFAULT_MAX_BACKOFF_DELAY;\n\tlet delay = 2 ** failCount * baseInterval;\n\n\tif (delay > effectiveMaxDelay) {\n\t\tdelay = effectiveMaxDelay;\n\t}\n\n\treturn new Date(Date.now() + delay);\n}\n\n/**\n * Calculate just the delay in milliseconds for a given fail count.\n *\n * @param failCount - Number of previous failed attempts\n * @param baseInterval - Base interval in milliseconds (default: 1000ms)\n * @param maxDelay - Maximum delay in milliseconds (optional)\n * @returns The delay in milliseconds\n */\nexport function calculateBackoffDelay(\n\tfailCount: number,\n\tbaseInterval: number = DEFAULT_BASE_INTERVAL,\n\tmaxDelay?: number,\n): number {\n\tconst effectiveMaxDelay = maxDelay ?? DEFAULT_MAX_BACKOFF_DELAY;\n\tlet delay = 2 ** failCount * baseInterval;\n\n\tif (delay > effectiveMaxDelay) {\n\t\tdelay = effectiveMaxDelay;\n\t}\n\n\treturn delay;\n}\n","import { CronExpressionParser } from 'cron-parser';\n\nimport { InvalidCronError } from '../errors.js';\n\n/**\n * Parse a cron expression and return the next scheduled run date.\n *\n * @param expression - A 5-field cron expression (minute hour day-of-month month day-of-week) or a predefined expression\n * @param currentDate - The reference date for calculating next run (default: now)\n * @returns The next scheduled run date\n * @throws {InvalidCronError} If the cron expression is invalid\n *\n * @example\n * ```typescript\n * // Every minute\n * const nextRun = getNextCronDate('* * * * *');\n *\n * // Every day at midnight\n * const nextRun = getNextCronDate('0 0 * * *');\n *\n * // Using predefined expression\n * const nextRun = getNextCronDate('@daily');\n *\n * // Every Monday at 9am\n * const nextRun = getNextCronDate('0 9 * * 1');\n * ```\n */\nexport function getNextCronDate(expression: string, currentDate?: Date): Date {\n\ttry {\n\t\tconst interval = CronExpressionParser.parse(expression, {\n\t\t\tcurrentDate: currentDate ?? new Date(),\n\t\t});\n\t\treturn interval.next().toDate();\n\t} catch (error) {\n\t\thandleCronParseError(expression, error);\n\t}\n}\n\n/**\n * Validate a cron expression without calculating the next run date.\n *\n * @param expression - A 5-field cron expression\n * @throws {InvalidCronError} If the cron expression is invalid\n *\n * @example\n * ```typescript\n * validateCronExpression('0 9 * * 1'); // Throws if invalid\n * ```\n */\nexport function validateCronExpression(expression: string): void {\n\ttry {\n\t\tCronExpressionParser.parse(expression);\n\t} catch (error) {\n\t\thandleCronParseError(expression, error);\n\t}\n}\n\nfunction handleCronParseError(expression: string, error: unknown): never {\n\t/* istanbul ignore next -- @preserve cron-parser always throws Error objects */\n\tconst errorMessage = error instanceof Error ? error.message : 'Unknown parsing error';\n\tthrow new InvalidCronError(\n\t\texpression,\n\t\t`Invalid cron expression \"${expression}\": ${errorMessage}. ` +\n\t\t\t'Expected 5-field format: \"minute hour day-of-month month day-of-week\" or predefined expression (e.g. @daily). ' +\n\t\t\t'Example: \"0 9 * * 1\" (every Monday at 9am)',\n\t);\n}\n","import { randomUUID } from 'node:crypto';\nimport { EventEmitter } from 'node:events';\nimport type {\n\tChangeStream,\n\tChangeStreamDocument,\n\tCollection,\n\tDb,\n\tDeleteResult,\n\tDocument,\n\tObjectId,\n\tWithId,\n} from 'mongodb';\n\nimport type { MonqueEventMap } from '@/events';\nimport {\n\ttype EnqueueOptions,\n\ttype GetJobsFilter,\n\tisPersistedJob,\n\ttype Job,\n\ttype JobHandler,\n\tJobStatus,\n\ttype JobStatusType,\n\ttype PersistedJob,\n\ttype ScheduleOptions,\n} from '@/jobs';\nimport {\n\tConnectionError,\n\tcalculateBackoff,\n\tgetNextCronDate,\n\tMonqueError,\n\tWorkerRegistrationError,\n} from '@/shared';\nimport type { WorkerOptions, WorkerRegistration } from '@/workers';\n\nimport type { MonqueOptions } from './types.js';\n\n/**\n * Default configuration values\n */\nconst DEFAULTS = {\n\tcollectionName: 'monque_jobs',\n\tpollInterval: 1000,\n\tmaxRetries: 10,\n\tbaseRetryInterval: 1000,\n\tshutdownTimeout: 30000,\n\tdefaultConcurrency: 5,\n\tlockTimeout: 1_800_000, // 30 minutes\n\trecoverStaleJobs: true,\n\theartbeatInterval: 30000, // 30 seconds\n\tretentionInterval: 3600_000, // 1 hour\n} as const;\n\n/**\n * Monque - MongoDB-backed job scheduler\n *\n * A type-safe job scheduler with atomic locking, exponential backoff, cron scheduling,\n * stale job recovery, and event-driven observability. Built on native MongoDB driver.\n *\n * @example Complete lifecycle\n * ```;\ntypescript\n *\n\nimport { Monque } from '@monque/core';\n\n*\n\nimport { MongoClient } from 'mongodb';\n\n*\n *\nconst client = new MongoClient('mongodb://localhost:27017');\n* await client.connect()\n*\nconst db = client.db('myapp');\n*\n * // Create instance with options\n *\nconst monque = new Monque(db, {\n * collectionName: 'jobs',\n * pollInterval: 1000,\n * maxRetries: 10,\n * shutdownTimeout: 30000,\n * });\n*\n * // Initialize (sets up indexes and recovers stale jobs)\n * await monque.initialize()\n*\n * // Register workers with type safety\n *\ntype EmailJob = {};\n* to: string\n* subject: string\n* body: string\n* }\n *\n * monque.register<EmailJob>('send-email', async (job) =>\n{\n\t* await emailService.send(job.data.to, job.data.subject, job.data.body)\n\t*\n}\n)\n*\n * // Monitor events for observability\n * monque.on('job:complete', (\n{\n\tjob, duration;\n}\n) =>\n{\n * logger.info(`Job $job.namecompleted in $durationms`);\n * });\n *\n * monque.on('job:fail', ({ job, error, willRetry }) => {\n * logger.error(`Job $job.namefailed:`, error);\n * });\n *\n * // Start processing\n * monque.start();\n *\n * // Enqueue jobs\n * await monque.enqueue('send-email', {\n * to: 'user@example.com',\n * subject: 'Welcome!',\n * body: 'Thanks for signing up.'\n * });\n *\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await monque.stop();\n * await client.close();\n * process.exit(0);\n * });\n * ```\n */\nexport class Monque extends EventEmitter {\n\tprivate readonly db: Db;\n\tprivate readonly options: Required<Omit<MonqueOptions, 'maxBackoffDelay' | 'jobRetention'>> &\n\t\tPick<MonqueOptions, 'maxBackoffDelay' | 'jobRetention'>;\n\tprivate collection: Collection<Document> | null = null;\n\tprivate workers: Map<string, WorkerRegistration> = new Map();\n\tprivate pollIntervalId: ReturnType<typeof setInterval> | null = null;\n\tprivate heartbeatIntervalId: ReturnType<typeof setInterval> | null = null;\n\tprivate cleanupIntervalId: ReturnType<typeof setInterval> | null = null;\n\tprivate isRunning = false;\n\tprivate isInitialized = false;\n\n\t/**\n\t * MongoDB Change Stream for real-time job notifications.\n\t * When available, provides instant job processing without polling delay.\n\t */\n\tprivate changeStream: ChangeStream | null = null;\n\n\t/**\n\t * Number of consecutive reconnection attempts for change stream.\n\t * Used for exponential backoff during reconnection.\n\t */\n\tprivate changeStreamReconnectAttempts = 0;\n\n\t/**\n\t * Maximum reconnection attempts before falling back to polling-only mode.\n\t */\n\tprivate readonly maxChangeStreamReconnectAttempts = 3;\n\n\t/**\n\t * Debounce timer for change stream event processing.\n\t * Prevents claim storms when multiple events arrive in quick succession.\n\t */\n\tprivate changeStreamDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n\n\t/**\n\t * Whether the scheduler is currently using change streams for notifications.\n\t */\n\tprivate usingChangeStreams = false;\n\n\t/**\n\t * Timer ID for change stream reconnection with exponential backoff.\n\t * Tracked to allow cancellation during shutdown.\n\t */\n\tprivate changeStreamReconnectTimer: ReturnType<typeof setTimeout> | null = null;\n\n\tconstructor(db: Db, options: MonqueOptions = {}) {\n\t\tsuper();\n\t\tthis.db = db;\n\t\tthis.options = {\n\t\t\tcollectionName: options.collectionName ?? DEFAULTS.collectionName,\n\t\t\tpollInterval: options.pollInterval ?? DEFAULTS.pollInterval,\n\t\t\tmaxRetries: options.maxRetries ?? DEFAULTS.maxRetries,\n\t\t\tbaseRetryInterval: options.baseRetryInterval ?? DEFAULTS.baseRetryInterval,\n\t\t\tshutdownTimeout: options.shutdownTimeout ?? DEFAULTS.shutdownTimeout,\n\t\t\tdefaultConcurrency: options.defaultConcurrency ?? DEFAULTS.defaultConcurrency,\n\t\t\tlockTimeout: options.lockTimeout ?? DEFAULTS.lockTimeout,\n\t\t\trecoverStaleJobs: options.recoverStaleJobs ?? DEFAULTS.recoverStaleJobs,\n\t\t\tmaxBackoffDelay: options.maxBackoffDelay,\n\t\t\tschedulerInstanceId: options.schedulerInstanceId ?? randomUUID(),\n\t\t\theartbeatInterval: options.heartbeatInterval ?? DEFAULTS.heartbeatInterval,\n\t\t\tjobRetention: options.jobRetention,\n\t\t};\n\t}\n\n\t/**\n\t * Initialize the scheduler by setting up the MongoDB collection and indexes.\n\t * Must be called before start().\n\t *\n\t * @throws {ConnectionError} If collection or index creation fails\n\t */\n\tasync initialize(): Promise<void> {\n\t\tif (this.isInitialized) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tthis.collection = this.db.collection(this.options.collectionName);\n\n\t\t\t// Create indexes for efficient queries\n\t\t\tawait this.createIndexes();\n\n\t\t\t// Recover stale jobs if enabled\n\t\t\tif (this.options.recoverStaleJobs) {\n\t\t\t\tawait this.recoverStaleJobs();\n\t\t\t}\n\n\t\t\tthis.isInitialized = true;\n\t\t} catch (error) {\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : 'Unknown error during initialization';\n\t\t\tthrow new ConnectionError(`Failed to initialize Monque: ${message}`);\n\t\t}\n\t}\n\n\t/**\n\t * Create required MongoDB indexes for efficient job processing.\n\t *\n\t * The following indexes are created:\n\t * - `{status, nextRunAt}` - For efficient job polling queries\n\t * - `{name, uniqueKey}` - Partial unique index for deduplication (pending/processing only)\n\t * - `{name, status}` - For job lookup by type\n\t * - `{claimedBy, status}` - For finding jobs owned by a specific scheduler instance\n\t * - `{lastHeartbeat, status}` - For monitoring/debugging queries (e.g., inspecting heartbeat age)\n\t * - `{status, nextRunAt, claimedBy}` - For atomic claim queries (find unclaimed pending jobs)\n\t * - `{lockedAt, lastHeartbeat, status}` - Supports recovery scans and monitoring access patterns\n\t */\n\tprivate async createIndexes(): Promise<void> {\n\t\tif (!this.collection) {\n\t\t\tthrow new ConnectionError('Collection not initialized');\n\t\t}\n\n\t\t// Compound index for job polling - status + nextRunAt for efficient queries\n\t\tawait this.collection.createIndex({ status: 1, nextRunAt: 1 }, { background: true });\n\n\t\t// Partial unique index for deduplication - scoped by name + uniqueKey\n\t\t// Only enforced where uniqueKey exists and status is pending/processing\n\t\tawait this.collection.createIndex(\n\t\t\t{ name: 1, uniqueKey: 1 },\n\t\t\t{\n\t\t\t\tunique: true,\n\t\t\t\tpartialFilterExpression: {\n\t\t\t\t\tuniqueKey: { $exists: true },\n\t\t\t\t\tstatus: { $in: [JobStatus.PENDING, JobStatus.PROCESSING] },\n\t\t\t\t},\n\t\t\t\tbackground: true,\n\t\t\t},\n\t\t);\n\n\t\t// Index for job lookup by name\n\t\tawait this.collection.createIndex({ name: 1, status: 1 }, { background: true });\n\n\t\t// Compound index for finding jobs claimed by a specific scheduler instance.\n\t\t// Used for heartbeat updates and cleanup on shutdown.\n\t\tawait this.collection.createIndex({ claimedBy: 1, status: 1 }, { background: true });\n\n\t\t// Compound index for monitoring/debugging via heartbeat timestamps.\n\t\t// Note: stale recovery uses lockedAt + lockTimeout as the source of truth.\n\t\tawait this.collection.createIndex({ lastHeartbeat: 1, status: 1 }, { background: true });\n\n\t\t// Compound index for atomic claim queries.\n\t\t// Optimizes the findOneAndUpdate query that claims unclaimed pending jobs.\n\t\tawait this.collection.createIndex(\n\t\t\t{ status: 1, nextRunAt: 1, claimedBy: 1 },\n\t\t\t{ background: true },\n\t\t);\n\n\t\t// Expanded index that supports recovery scans (status + lockedAt) plus heartbeat monitoring patterns.\n\t\tawait this.collection.createIndex(\n\t\t\t{ status: 1, lockedAt: 1, lastHeartbeat: 1 },\n\t\t\t{ background: true },\n\t\t);\n\t}\n\n\t/**\n\t * Recover stale jobs that were left in 'processing' status.\n\t * A job is considered stale if its `lockedAt` timestamp exceeds the configured `lockTimeout`.\n\t * Stale jobs are reset to 'pending' so they can be picked up by workers again.\n\t */\n\tprivate async recoverStaleJobs(): Promise<void> {\n\t\tif (!this.collection) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst staleThreshold = new Date(Date.now() - this.options.lockTimeout);\n\n\t\tconst result = await this.collection.updateMany(\n\t\t\t{\n\t\t\t\tstatus: JobStatus.PROCESSING,\n\t\t\t\tlockedAt: { $lt: staleThreshold },\n\t\t\t},\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tstatus: JobStatus.PENDING,\n\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t},\n\t\t\t\t$unset: {\n\t\t\t\t\tlockedAt: '',\n\t\t\t\t\tclaimedBy: '',\n\t\t\t\t\tlastHeartbeat: '',\n\t\t\t\t\theartbeatInterval: '',\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tif (result.modifiedCount > 0) {\n\t\t\t// Emit event for recovered jobs\n\t\t\tthis.emit('stale:recovered', {\n\t\t\t\tcount: result.modifiedCount,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Clean up old completed and failed jobs based on retention policy.\n\t *\n\t * - Removes completed jobs older than `jobRetention.completed`\n\t * - Removes failed jobs older than `jobRetention.failed`\n\t *\n\t * The cleanup runs concurrently for both statuses if configured.\n\t *\n\t * @returns Promise resolving when all deletion operations complete\n\t */\n\tprivate async cleanupJobs(): Promise<void> {\n\t\tif (!this.collection || !this.options.jobRetention) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst { completed, failed } = this.options.jobRetention;\n\t\tconst now = Date.now();\n\t\tconst deletions: Promise<DeleteResult>[] = [];\n\n\t\tif (completed) {\n\t\t\tconst cutoff = new Date(now - completed);\n\t\t\tdeletions.push(\n\t\t\t\tthis.collection.deleteMany({\n\t\t\t\t\tstatus: JobStatus.COMPLETED,\n\t\t\t\t\tupdatedAt: { $lt: cutoff },\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tif (failed) {\n\t\t\tconst cutoff = new Date(now - failed);\n\t\t\tdeletions.push(\n\t\t\t\tthis.collection.deleteMany({\n\t\t\t\t\tstatus: JobStatus.FAILED,\n\t\t\t\t\tupdatedAt: { $lt: cutoff },\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tif (deletions.length > 0) {\n\t\t\tawait Promise.all(deletions);\n\t\t}\n\t}\n\n\t/**\n\t * Enqueue a job for processing.\n\t *\n\t * Jobs are stored in MongoDB and processed by registered workers. Supports\n\t * delayed execution via `runAt` and deduplication via `uniqueKey`.\n\t *\n\t * When a `uniqueKey` is provided, only one pending or processing job with that key\n\t * can exist. Completed or failed jobs don't block new jobs with the same key.\n\t *\n\t * Failed jobs are automatically retried with exponential backoff up to `maxRetries`\n\t * (default: 10 attempts). The delay between retries is calculated as `2^failCount × baseRetryInterval`.\n\t *\n\t * @template T - The job data payload type (must be JSON-serializable)\n\t * @param name - Job type identifier, must match a registered worker\n\t * @param data - Job payload, will be passed to the worker handler\n\t * @param options - Scheduling and deduplication options\n\t * @returns Promise resolving to the created or existing job document\n\t * @throws {ConnectionError} If database operation fails or scheduler not initialized\n\t *\n\t * @example Basic job enqueueing\n\t * ```typescript\n\t * await monque.enqueue('send-email', {\n\t * to: 'user@example.com',\n\t * subject: 'Welcome!',\n\t * body: 'Thanks for signing up.'\n\t * });\n\t * ```\n\t *\n\t * @example Delayed execution\n\t * ```typescript\n\t * const oneHourLater = new Date(Date.now() + 3600000);\n\t * await monque.enqueue('reminder', { message: 'Check in!' }, {\n\t * runAt: oneHourLater\n\t * });\n\t * ```\n\t *\n\t * @example Prevent duplicates with unique key\n\t * ```typescript\n\t * await monque.enqueue('sync-user', { userId: '123' }, {\n\t * uniqueKey: 'sync-user-123'\n\t * });\n\t * // Subsequent enqueues with same uniqueKey return existing pending/processing job\n\t * ```\n\t */\n\tasync enqueue<T>(name: string, data: T, options: EnqueueOptions = {}): Promise<PersistedJob<T>> {\n\t\tthis.ensureInitialized();\n\n\t\tconst now = new Date();\n\t\tconst job: Omit<Job<T>, '_id'> = {\n\t\t\tname,\n\t\t\tdata,\n\t\t\tstatus: JobStatus.PENDING,\n\t\t\tnextRunAt: options.runAt ?? now,\n\t\t\tfailCount: 0,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\n\t\tif (options.uniqueKey) {\n\t\t\tjob.uniqueKey = options.uniqueKey;\n\t\t}\n\n\t\ttry {\n\t\t\tif (options.uniqueKey) {\n\t\t\t\tif (!this.collection) {\n\t\t\t\t\tthrow new ConnectionError('Failed to enqueue job: collection not available');\n\t\t\t\t}\n\n\t\t\t\t// Use upsert with $setOnInsert for deduplication (scoped by name + uniqueKey)\n\t\t\t\tconst result = await this.collection.findOneAndUpdate(\n\t\t\t\t\t{\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tuniqueKey: options.uniqueKey,\n\t\t\t\t\t\tstatus: { $in: [JobStatus.PENDING, JobStatus.PROCESSING] },\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t$setOnInsert: job,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tupsert: true,\n\t\t\t\t\t\treturnDocument: 'after',\n\t\t\t\t\t},\n\t\t\t\t);\n\n\t\t\t\tif (!result) {\n\t\t\t\t\tthrow new ConnectionError('Failed to enqueue job: findOneAndUpdate returned no document');\n\t\t\t\t}\n\n\t\t\t\treturn this.documentToPersistedJob<T>(result as WithId<Document>);\n\t\t\t}\n\n\t\t\tconst result = await this.collection?.insertOne(job as Document);\n\n\t\t\tif (!result) {\n\t\t\t\tthrow new ConnectionError('Failed to enqueue job: collection not available');\n\t\t\t}\n\n\t\t\treturn { ...job, _id: result.insertedId } as PersistedJob<T>;\n\t\t} catch (error) {\n\t\t\tif (error instanceof ConnectionError) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst message = error instanceof Error ? error.message : 'Unknown error during enqueue';\n\t\t\tthrow new ConnectionError(\n\t\t\t\t`Failed to enqueue job: ${message}`,\n\t\t\t\terror instanceof Error ? { cause: error } : undefined,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Enqueue a job for immediate processing.\n\t *\n\t * Convenience method equivalent to `enqueue(name, data, { runAt: new Date() })`.\n\t * Jobs are picked up on the next poll cycle (typically within 1 second based on `pollInterval`).\n\t *\n\t * @template T - The job data payload type (must be JSON-serializable)\n\t * @param name - Job type identifier, must match a registered worker\n\t * @param data - Job payload, will be passed to the worker handler\n\t * @returns Promise resolving to the created job document\n\t * @throws {ConnectionError} If database operation fails or scheduler not initialized\n\t *\n\t * @example Send email immediately\n\t * ```typescript\n\t * await monque.now('send-email', {\n\t * to: 'admin@example.com',\n\t * subject: 'Alert',\n\t * body: 'Immediate attention required'\n\t * });\n\t * ```\n\t *\n\t * @example Process order in background\n\t * ```typescript\n\t * const order = await createOrder(data);\n\t * await monque.now('process-order', { orderId: order.id });\n\t * return order; // Return immediately, processing happens async\n\t * ```\n\t */\n\tasync now<T>(name: string, data: T): Promise<PersistedJob<T>> {\n\t\treturn this.enqueue(name, data, { runAt: new Date() });\n\t}\n\n\t/**\n\t * Schedule a recurring job with a cron expression.\n\t *\n\t * Creates a job that automatically re-schedules itself based on the cron pattern.\n\t * Uses standard 5-field cron format: minute, hour, day of month, month, day of week.\n\t * Also supports predefined expressions like `@daily`, `@weekly`, `@monthly`, etc.\n\t * After successful completion, the job is reset to `pending` status and scheduled\n\t * for its next run based on the cron expression.\n\t *\n\t * When a `uniqueKey` is provided, only one pending or processing job with that key\n\t * can exist. This prevents duplicate scheduled jobs on application restart.\n\t *\n\t * @template T - The job data payload type (must be JSON-serializable)\n\t * @param cron - Cron expression (5 fields or predefined expression)\n\t * @param name - Job type identifier, must match a registered worker\n\t * @param data - Job payload, will be passed to the worker handler on each run\n\t * @param options - Scheduling options (uniqueKey for deduplication)\n\t * @returns Promise resolving to the created job document with `repeatInterval` set\n\t * @throws {InvalidCronError} If cron expression is invalid\n\t * @throws {ConnectionError} If database operation fails or scheduler not initialized\n\t *\n\t * @example Hourly cleanup job\n\t * ```typescript\n\t * await monque.schedule('0 * * * *', 'cleanup-temp-files', {\n\t * directory: '/tmp/uploads'\n\t * });\n\t * ```\n\t *\n\t * @example Prevent duplicate scheduled jobs with unique key\n\t * ```typescript\n\t * await monque.schedule('0 * * * *', 'hourly-report', { type: 'sales' }, {\n\t * uniqueKey: 'hourly-report-sales'\n\t * });\n\t * // Subsequent calls with same uniqueKey return existing pending/processing job\n\t * ```\n\t *\n\t * @example Daily report at midnight (using predefined expression)\n\t * ```typescript\n\t * await monque.schedule('@daily', 'daily-report', {\n\t * reportType: 'sales',\n\t * recipients: ['analytics@example.com']\n\t * });\n\t * ```\n\t */\n\tasync schedule<T>(\n\t\tcron: string,\n\t\tname: string,\n\t\tdata: T,\n\t\toptions: ScheduleOptions = {},\n\t): Promise<PersistedJob<T>> {\n\t\tthis.ensureInitialized();\n\n\t\t// Validate cron and get next run date (throws InvalidCronError if invalid)\n\t\tconst nextRunAt = getNextCronDate(cron);\n\n\t\tconst now = new Date();\n\t\tconst job: Omit<Job<T>, '_id'> = {\n\t\t\tname,\n\t\t\tdata,\n\t\t\tstatus: JobStatus.PENDING,\n\t\t\tnextRunAt,\n\t\t\trepeatInterval: cron,\n\t\t\tfailCount: 0,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\n\t\tif (options.uniqueKey) {\n\t\t\tjob.uniqueKey = options.uniqueKey;\n\t\t}\n\n\t\ttry {\n\t\t\tif (options.uniqueKey) {\n\t\t\t\tif (!this.collection) {\n\t\t\t\t\tthrow new ConnectionError('Failed to schedule job: collection not available');\n\t\t\t\t}\n\n\t\t\t\t// Use upsert with $setOnInsert for deduplication (scoped by name + uniqueKey)\n\t\t\t\tconst result = await this.collection.findOneAndUpdate(\n\t\t\t\t\t{\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tuniqueKey: options.uniqueKey,\n\t\t\t\t\t\tstatus: { $in: [JobStatus.PENDING, JobStatus.PROCESSING] },\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t$setOnInsert: job,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tupsert: true,\n\t\t\t\t\t\treturnDocument: 'after',\n\t\t\t\t\t},\n\t\t\t\t);\n\n\t\t\t\tif (!result) {\n\t\t\t\t\tthrow new ConnectionError(\n\t\t\t\t\t\t'Failed to schedule job: findOneAndUpdate returned no document',\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn this.documentToPersistedJob<T>(result as WithId<Document>);\n\t\t\t}\n\n\t\t\tconst result = await this.collection?.insertOne(job as Document);\n\n\t\t\tif (!result) {\n\t\t\t\tthrow new ConnectionError('Failed to schedule job: collection not available');\n\t\t\t}\n\n\t\t\treturn { ...job, _id: result.insertedId } as PersistedJob<T>;\n\t\t} catch (error) {\n\t\t\tif (error instanceof MonqueError) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst message = error instanceof Error ? error.message : 'Unknown error during schedule';\n\t\t\tthrow new ConnectionError(\n\t\t\t\t`Failed to schedule job: ${message}`,\n\t\t\t\terror instanceof Error ? { cause: error } : undefined,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Register a worker to process jobs of a specific type.\n\t *\n\t * Workers can be registered before or after calling `start()`. Each worker\n\t * processes jobs concurrently up to its configured concurrency limit (default: 5).\n\t *\n\t * The handler function receives the full job object including metadata (`_id`, `status`,\n\t * `failCount`, etc.). If the handler throws an error, the job is retried with exponential\n\t * backoff up to `maxRetries` times. After exhausting retries, the job is marked as `failed`.\n\t *\n\t * Events are emitted during job processing: `job:start`, `job:complete`, `job:fail`, and `job:error`.\n\t *\n\t * **Duplicate Registration**: By default, registering a worker for a job name that already has\n\t * a worker will throw a `WorkerRegistrationError`. This fail-fast behavior prevents accidental\n\t * replacement of handlers. To explicitly replace a worker, pass `{ replace: true }`.\n\t *\n\t * @template T - The job data payload type for type-safe access to `job.data`\n\t * @param name - Job type identifier to handle\n\t * @param handler - Async function to execute for each job\n\t * @param options - Worker configuration\n\t * @param options.concurrency - Maximum concurrent jobs for this worker (default: `defaultConcurrency`)\n\t * @param options.replace - When `true`, replace existing worker instead of throwing error\n\t * @throws {WorkerRegistrationError} When a worker is already registered for `name` and `replace` is not `true`\n\t *\n\t * @example Basic email worker\n\t * ```typescript\n\t * interface EmailJob {\n\t * to: string;\n\t * subject: string;\n\t * body: string;\n\t * }\n\t *\n\t * monque.register<EmailJob>('send-email', async (job) => {\n\t * await emailService.send(job.data.to, job.data.subject, job.data.body);\n\t * });\n\t * ```\n\t *\n\t * @example Worker with custom concurrency\n\t * ```typescript\n\t * // Limit to 2 concurrent video processing jobs (resource-intensive)\n\t * monque.register('process-video', async (job) => {\n\t * await videoProcessor.transcode(job.data.videoId);\n\t * }, { concurrency: 2 });\n\t * ```\n\t *\n\t * @example Replacing an existing worker\n\t * ```typescript\n\t * // Replace the existing handler for 'send-email'\n\t * monque.register('send-email', newEmailHandler, { replace: true });\n\t * ```\n\t *\n\t * @example Worker with error handling\n\t * ```typescript\n\t * monque.register('sync-user', async (job) => {\n\t * try {\n\t * await externalApi.syncUser(job.data.userId);\n\t * } catch (error) {\n\t * // Job will retry with exponential backoff\n\t * // Delay = 2^failCount × baseRetryInterval (default: 1000ms)\n\t * throw new Error(`Sync failed: ${error.message}`);\n\t * }\n\t * });\n\t * ```\n\t */\n\tregister<T>(name: string, handler: JobHandler<T>, options: WorkerOptions = {}): void {\n\t\tconst concurrency = options.concurrency ?? this.options.defaultConcurrency;\n\n\t\t// Check for existing worker and throw unless replace is explicitly true\n\t\tif (this.workers.has(name) && options.replace !== true) {\n\t\t\tthrow new WorkerRegistrationError(\n\t\t\t\t`Worker already registered for job name \"${name}\". Use { replace: true } to replace.`,\n\t\t\t\tname,\n\t\t\t);\n\t\t}\n\n\t\tthis.workers.set(name, {\n\t\t\thandler: handler as JobHandler,\n\t\t\tconcurrency,\n\t\t\tactiveJobs: new Map(),\n\t\t});\n\t}\n\n\t/**\n\t * Start polling for and processing jobs.\n\t *\n\t * Begins polling MongoDB at the configured interval (default: 1 second) to pick up\n\t * pending jobs and dispatch them to registered workers. Must call `initialize()` first.\n\t * Workers can be registered before or after calling `start()`.\n\t *\n\t * Jobs are processed concurrently up to each worker's configured concurrency limit.\n\t * The scheduler continues running until `stop()` is called.\n\t *\n\t * @example Basic startup\n\t * ```typescript\n\t * const monque = new Monque(db);\n\t * await monque.initialize();\n\t *\n\t * monque.register('send-email', emailHandler);\n\t * monque.register('process-order', orderHandler);\n\t *\n\t * monque.start(); // Begin processing jobs\n\t * ```\n\t *\n\t * @example With event monitoring\n\t * ```typescript\n\t * monque.on('job:start', (job) => {\n\t * logger.info(`Starting job ${job.name}`);\n\t * });\n\t *\n\t * monque.on('job:complete', ({ job, duration }) => {\n\t * metrics.recordJobDuration(job.name, duration);\n\t * });\n\t *\n\t * monque.on('job:fail', ({ job, error, willRetry }) => {\n\t * logger.error(`Job ${job.name} failed:`, error);\n\t * if (!willRetry) {\n\t * alerting.sendAlert(`Job permanently failed: ${job.name}`);\n\t * }\n\t * });\n\t *\n\t * monque.start();\n\t * ```\n\t *\n\t * @throws {ConnectionError} If scheduler not initialized (call `initialize()` first)\n\t */\n\tstart(): void {\n\t\tif (this.isRunning) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.isInitialized) {\n\t\t\tthrow new ConnectionError('Monque not initialized. Call initialize() before start().');\n\t\t}\n\n\t\tthis.isRunning = true;\n\n\t\t// Set up change streams as the primary notification mechanism\n\t\tthis.setupChangeStream();\n\n\t\t// Set up polling as backup (runs at configured interval)\n\t\tthis.pollIntervalId = setInterval(() => {\n\t\t\tthis.poll().catch((error: unknown) => {\n\t\t\t\tthis.emit('job:error', { error: error as Error });\n\t\t\t});\n\t\t}, this.options.pollInterval);\n\n\t\t// Start heartbeat interval for claimed jobs\n\t\tthis.heartbeatIntervalId = setInterval(() => {\n\t\t\tthis.updateHeartbeats().catch((error: unknown) => {\n\t\t\t\tthis.emit('job:error', { error: error as Error });\n\t\t\t});\n\t\t}, this.options.heartbeatInterval);\n\n\t\t// Start cleanup interval if retention is configured\n\t\tif (this.options.jobRetention) {\n\t\t\tconst interval = this.options.jobRetention.interval ?? DEFAULTS.retentionInterval;\n\n\t\t\t// Run immediately on start\n\t\t\tthis.cleanupJobs().catch((error: unknown) => {\n\t\t\t\tthis.emit('job:error', { error: error as Error });\n\t\t\t});\n\n\t\t\tthis.cleanupIntervalId = setInterval(() => {\n\t\t\t\tthis.cleanupJobs().catch((error: unknown) => {\n\t\t\t\t\tthis.emit('job:error', { error: error as Error });\n\t\t\t\t});\n\t\t\t}, interval);\n\t\t}\n\n\t\t// Run initial poll immediately to pick up any existing jobs\n\t\tthis.poll().catch((error: unknown) => {\n\t\t\tthis.emit('job:error', { error: error as Error });\n\t\t});\n\t}\n\n\t/**\n\t * Stop the scheduler gracefully, waiting for in-progress jobs to complete.\n\t *\n\t * Stops polling for new jobs and waits for all active jobs to finish processing.\n\t * Times out after the configured `shutdownTimeout` (default: 30 seconds), emitting\n\t * a `job:error` event with a `ShutdownTimeoutError` containing incomplete jobs.\n\t * On timeout, jobs still in progress are left as `processing` for stale job recovery.\n\t *\n\t * It's safe to call `stop()` multiple times - subsequent calls are no-ops if already stopped.\n\t *\n\t * @returns Promise that resolves when all jobs complete or timeout is reached\n\t *\n\t * @example Graceful application shutdown\n\t * ```typescript\n\t * process.on('SIGTERM', async () => {\n\t * console.log('Shutting down gracefully...');\n\t * await monque.stop(); // Wait for jobs to complete\n\t * await mongoClient.close();\n\t * process.exit(0);\n\t * });\n\t * ```\n\t *\n\t * @example With timeout handling\n\t * ```typescript\n\t * monque.on('job:error', ({ error }) => {\n\t * if (error.name === 'ShutdownTimeoutError') {\n\t * logger.warn('Forced shutdown after timeout:', error.incompleteJobs);\n\t * }\n\t * });\n\t *\n\t * await monque.stop();\n\t * ```\n\t */\n\tasync stop(): Promise<void> {\n\t\tif (!this.isRunning) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.isRunning = false;\n\n\t\t// Close change stream\n\t\tawait this.closeChangeStream();\n\n\t\t// Clear debounce timer\n\t\tif (this.changeStreamDebounceTimer) {\n\t\t\tclearTimeout(this.changeStreamDebounceTimer);\n\t\t\tthis.changeStreamDebounceTimer = null;\n\t\t}\n\n\t\t// Clear reconnection timer\n\t\tif (this.changeStreamReconnectTimer) {\n\t\t\tclearTimeout(this.changeStreamReconnectTimer);\n\t\t\tthis.changeStreamReconnectTimer = null;\n\t\t}\n\n\t\tif (this.cleanupIntervalId) {\n\t\t\tclearInterval(this.cleanupIntervalId);\n\t\t\tthis.cleanupIntervalId = null;\n\t\t}\n\n\t\t// Clear polling interval\n\t\tif (this.pollIntervalId) {\n\t\t\tclearInterval(this.pollIntervalId);\n\t\t\tthis.pollIntervalId = null;\n\t\t}\n\n\t\t// Clear heartbeat interval\n\t\tif (this.heartbeatIntervalId) {\n\t\t\tclearInterval(this.heartbeatIntervalId);\n\t\t\tthis.heartbeatIntervalId = null;\n\t\t}\n\n\t\t// Wait for all active jobs to complete (with timeout)\n\t\tconst activeJobs = this.getActiveJobs();\n\t\tif (activeJobs.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Create a promise that resolves when all jobs are done\n\t\tlet checkInterval: ReturnType<typeof setInterval> | undefined;\n\t\tconst waitForJobs = new Promise<undefined>((resolve) => {\n\t\t\tcheckInterval = setInterval(() => {\n\t\t\t\tif (this.getActiveJobs().length === 0) {\n\t\t\t\t\tclearInterval(checkInterval);\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t}\n\t\t\t}, 100);\n\t\t});\n\n\t\t// Race between job completion and timeout\n\t\tconst timeout = new Promise<'timeout'>((resolve) => {\n\t\t\tsetTimeout(() => resolve('timeout'), this.options.shutdownTimeout);\n\t\t});\n\n\t\tlet result: undefined | 'timeout';\n\n\t\ttry {\n\t\t\tresult = await Promise.race([waitForJobs, timeout]);\n\t\t} finally {\n\t\t\tif (checkInterval) {\n\t\t\t\tclearInterval(checkInterval);\n\t\t\t}\n\t\t}\n\n\t\tif (result === 'timeout') {\n\t\t\tconst incompleteJobs = this.getActiveJobsList();\n\t\t\tconst { ShutdownTimeoutError } = await import('@/shared/errors.js');\n\n\t\t\tconst error = new ShutdownTimeoutError(\n\t\t\t\t`Shutdown timed out after ${this.options.shutdownTimeout}ms with ${incompleteJobs.length} incomplete jobs`,\n\t\t\t\tincompleteJobs,\n\t\t\t);\n\t\t\tthis.emit('job:error', { error });\n\t\t}\n\t}\n\n\t/**\n\t * Check if the scheduler is healthy (running and connected).\n\t *\n\t * Returns `true` when the scheduler is started, initialized, and has an active\n\t * MongoDB collection reference. Useful for health check endpoints and monitoring.\n\t *\n\t * A healthy scheduler:\n\t * - Has called `initialize()` successfully\n\t * - Has called `start()` and is actively polling\n\t * - Has a valid MongoDB collection reference\n\t *\n\t * @returns `true` if scheduler is running and connected, `false` otherwise\n\t *\n\t * @example Express health check endpoint\n\t * ```typescript\n\t * app.get('/health', (req, res) => {\n\t * const healthy = monque.isHealthy();\n\t * res.status(healthy ? 200 : 503).json({\n\t * status: healthy ? 'ok' : 'unavailable',\n\t * scheduler: healthy,\n\t * timestamp: new Date().toISOString()\n\t * });\n\t * });\n\t * ```\n\t *\n\t * @example Kubernetes readiness probe\n\t * ```typescript\n\t * app.get('/readyz', (req, res) => {\n\t * if (monque.isHealthy() && dbConnected) {\n\t * res.status(200).send('ready');\n\t * } else {\n\t * res.status(503).send('not ready');\n\t * }\n\t * });\n\t * ```\n\t *\n\t * @example Periodic health monitoring\n\t * ```typescript\n\t * setInterval(() => {\n\t * if (!monque.isHealthy()) {\n\t * logger.error('Scheduler unhealthy');\n\t * metrics.increment('scheduler.unhealthy');\n\t * }\n\t * }, 60000); // Check every minute\n\t * ```\n\t */\n\tisHealthy(): boolean {\n\t\treturn this.isRunning && this.isInitialized && this.collection !== null;\n\t}\n\n\t/**\n\t * Query jobs from the queue with optional filters.\n\t *\n\t * Provides read-only access to job data for monitoring, debugging, and\n\t * administrative purposes. Results are ordered by `nextRunAt` ascending.\n\t *\n\t * @template T - The expected type of the job data payload\n\t * @param filter - Optional filter criteria\n\t * @returns Promise resolving to array of matching jobs\n\t * @throws {ConnectionError} If scheduler not initialized\n\t *\n\t * @example Get all pending jobs\n\t * ```typescript\n\t * const pendingJobs = await monque.getJobs({ status: JobStatus.PENDING });\n\t * console.log(`${pendingJobs.length} jobs waiting`);\n\t * ```\n\t *\n\t * @example Get failed email jobs\n\t * ```typescript\n\t * const failedEmails = await monque.getJobs({\n\t * name: 'send-email',\n\t * status: JobStatus.FAILED,\n\t * });\n\t * for (const job of failedEmails) {\n\t * console.error(`Job ${job._id} failed: ${job.failReason}`);\n\t * }\n\t * ```\n\t *\n\t * @example Paginated job listing\n\t * ```typescript\n\t * const page1 = await monque.getJobs({ limit: 50, skip: 0 });\n\t * const page2 = await monque.getJobs({ limit: 50, skip: 50 });\n\t * ```\n\t *\n\t * @example Use with type guards from @monque/core\n\t * ```typescript\n\t * import { isPendingJob, isRecurringJob } from '@monque/core';\n\t *\n\t * const jobs = await monque.getJobs();\n\t * const pendingRecurring = jobs.filter(job => isPendingJob(job) && isRecurringJob(job));\n\t * ```\n\t */\n\tasync getJobs<T = unknown>(filter: GetJobsFilter = {}): Promise<PersistedJob<T>[]> {\n\t\tthis.ensureInitialized();\n\n\t\tif (!this.collection) {\n\t\t\tthrow new ConnectionError('Failed to query jobs: collection not available');\n\t\t}\n\n\t\tconst query: Document = {};\n\n\t\tif (filter.name !== undefined) {\n\t\t\tquery['name'] = filter.name;\n\t\t}\n\n\t\tif (filter.status !== undefined) {\n\t\t\tif (Array.isArray(filter.status)) {\n\t\t\t\tquery['status'] = { $in: filter.status };\n\t\t\t} else {\n\t\t\t\tquery['status'] = filter.status;\n\t\t\t}\n\t\t}\n\n\t\tconst limit = filter.limit ?? 100;\n\t\tconst skip = filter.skip ?? 0;\n\n\t\ttry {\n\t\t\tconst cursor = this.collection.find(query).sort({ nextRunAt: 1 }).skip(skip).limit(limit);\n\n\t\t\tconst docs = await cursor.toArray();\n\t\t\treturn docs.map((doc) => this.documentToPersistedJob<T>(doc));\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : 'Unknown error during getJobs';\n\t\t\tthrow new ConnectionError(\n\t\t\t\t`Failed to query jobs: ${message}`,\n\t\t\t\terror instanceof Error ? { cause: error } : undefined,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Get a single job by its MongoDB ObjectId.\n\t *\n\t * Useful for retrieving job details when you have a job ID from events,\n\t * logs, or stored references.\n\t *\n\t * @template T - The expected type of the job data payload\n\t * @param id - The job's ObjectId\n\t * @returns Promise resolving to the job if found, null otherwise\n\t * @throws {ConnectionError} If scheduler not initialized\n\t *\n\t * @example Look up job from event\n\t * ```typescript\n\t * monque.on('job:fail', async ({ job }) => {\n\t * // Later, retrieve the job to check its status\n\t * const currentJob = await monque.getJob(job._id);\n\t * console.log(`Job status: ${currentJob?.status}`);\n\t * });\n\t * ```\n\t *\n\t * @example Admin endpoint\n\t * ```typescript\n\t * app.get('/jobs/:id', async (req, res) => {\n\t * const job = await monque.getJob(new ObjectId(req.params.id));\n\t * if (!job) {\n\t * return res.status(404).json({ error: 'Job not found' });\n\t * }\n\t * res.json(job);\n\t * });\n\t * ```\n\t */\n\tasync getJob<T = unknown>(id: ObjectId): Promise<PersistedJob<T> | null> {\n\t\tthis.ensureInitialized();\n\n\t\tif (!this.collection) {\n\t\t\tthrow new ConnectionError('Failed to get job: collection not available');\n\t\t}\n\n\t\ttry {\n\t\t\tconst doc = await this.collection.findOne({ _id: id });\n\t\t\tif (!doc) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn this.documentToPersistedJob<T>(doc as WithId<Document>);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : 'Unknown error during getJob';\n\t\t\tthrow new ConnectionError(\n\t\t\t\t`Failed to get job: ${message}`,\n\t\t\t\terror instanceof Error ? { cause: error } : undefined,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Poll for available jobs and process them.\n\t *\n\t * Called at regular intervals (configured by `pollInterval`). For each registered worker,\n\t * attempts to acquire jobs up to the worker's available concurrency slots.\n\t * Aborts early if the scheduler is stopping (`isRunning` is false).\n\t *\n\t * @private\n\t */\n\tprivate async poll(): Promise<void> {\n\t\tif (!this.isRunning || !this.collection) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (const [name, worker] of this.workers) {\n\t\t\t// Check if worker has capacity\n\t\t\tconst availableSlots = worker.concurrency - worker.activeJobs.size;\n\n\t\t\tif (availableSlots <= 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Try to acquire jobs up to available slots\n\t\t\tfor (let i = 0; i < availableSlots; i++) {\n\t\t\t\tif (!this.isRunning) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst job = await this.acquireJob(name);\n\n\t\t\t\tif (job) {\n\t\t\t\t\tthis.processJob(job, worker).catch((error: unknown) => {\n\t\t\t\t\t\tthis.emit('job:error', { error: error as Error, job });\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t// No more jobs available for this worker\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Atomically acquire a pending job for processing using the claimedBy pattern.\n\t *\n\t * Uses MongoDB's `findOneAndUpdate` with atomic operations to ensure only one scheduler\n\t * instance can claim a job. The query ensures the job is:\n\t * - In pending status\n\t * - Has nextRunAt <= now\n\t * - Is not claimed by another instance (claimedBy is null/undefined)\n\t *\n\t * Returns `null` immediately if scheduler is stopping (`isRunning` is false).\n\t *\n\t * @private\n\t * @param name - The job type to acquire\n\t * @returns The acquired job with updated status, claimedBy, and heartbeat info, or `null` if no jobs available\n\t */\n\tprivate async acquireJob(name: string): Promise<PersistedJob | null> {\n\t\tif (!this.collection || !this.isRunning) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst now = new Date();\n\n\t\tconst result = await this.collection.findOneAndUpdate(\n\t\t\t{\n\t\t\t\tname,\n\t\t\t\tstatus: JobStatus.PENDING,\n\t\t\t\tnextRunAt: { $lte: now },\n\t\t\t\t$or: [{ claimedBy: null }, { claimedBy: { $exists: false } }],\n\t\t\t},\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tstatus: JobStatus.PROCESSING,\n\t\t\t\t\tclaimedBy: this.options.schedulerInstanceId,\n\t\t\t\t\tlockedAt: now,\n\t\t\t\t\tlastHeartbeat: now,\n\t\t\t\t\theartbeatInterval: this.options.heartbeatInterval,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tsort: { nextRunAt: 1 },\n\t\t\t\treturnDocument: 'after',\n\t\t\t},\n\t\t);\n\n\t\tif (!result) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn this.documentToPersistedJob(result as WithId<Document>);\n\t}\n\n\t/**\n\t * Execute a job using its registered worker handler.\n\t *\n\t * Tracks the job as active during processing, emits lifecycle events, and handles\n\t * both success and failure cases. On success, calls `completeJob()`. On failure,\n\t * calls `failJob()` which implements exponential backoff retry logic.\n\t *\n\t * @private\n\t * @param job - The job to process\n\t * @param worker - The worker registration containing the handler and active job tracking\n\t */\n\tprivate async processJob(job: PersistedJob, worker: WorkerRegistration): Promise<void> {\n\t\tconst jobId = job._id.toString();\n\t\tworker.activeJobs.set(jobId, job);\n\n\t\tconst startTime = Date.now();\n\t\tthis.emit('job:start', job);\n\n\t\ttry {\n\t\t\tawait worker.handler(job);\n\n\t\t\t// Job completed successfully\n\t\t\tconst duration = Date.now() - startTime;\n\t\t\tawait this.completeJob(job);\n\t\t\tthis.emit('job:complete', { job, duration });\n\t\t} catch (error) {\n\t\t\t// Job failed\n\t\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\t\tawait this.failJob(job, err);\n\n\t\t\tconst willRetry = job.failCount + 1 < this.options.maxRetries;\n\t\t\tthis.emit('job:fail', { job, error: err, willRetry });\n\t\t} finally {\n\t\t\tworker.activeJobs.delete(jobId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark a job as completed successfully.\n\t *\n\t * For recurring jobs (with `repeatInterval`), schedules the next run based on the cron\n\t * expression and resets `failCount` to 0. For one-time jobs, sets status to `completed`.\n\t * Clears `lockedAt` and `failReason` fields in both cases.\n\t *\n\t * @private\n\t * @param job - The job that completed successfully\n\t */\n\tprivate async completeJob(job: Job): Promise<void> {\n\t\tif (!this.collection || !isPersistedJob(job)) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (job.repeatInterval) {\n\t\t\t// Recurring job - schedule next run\n\t\t\tconst nextRunAt = getNextCronDate(job.repeatInterval);\n\t\t\tawait this.collection.updateOne(\n\t\t\t\t{ _id: job._id },\n\t\t\t\t{\n\t\t\t\t\t$set: {\n\t\t\t\t\t\tstatus: JobStatus.PENDING,\n\t\t\t\t\t\tnextRunAt,\n\t\t\t\t\t\tfailCount: 0,\n\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t},\n\t\t\t\t\t$unset: {\n\t\t\t\t\t\tlockedAt: '',\n\t\t\t\t\t\tclaimedBy: '',\n\t\t\t\t\t\tlastHeartbeat: '',\n\t\t\t\t\t\theartbeatInterval: '',\n\t\t\t\t\t\tfailReason: '',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t} else {\n\t\t\t// One-time job - mark as completed\n\t\t\tawait this.collection.updateOne(\n\t\t\t\t{ _id: job._id },\n\t\t\t\t{\n\t\t\t\t\t$set: {\n\t\t\t\t\t\tstatus: JobStatus.COMPLETED,\n\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t},\n\t\t\t\t\t$unset: {\n\t\t\t\t\t\tlockedAt: '',\n\t\t\t\t\t\tclaimedBy: '',\n\t\t\t\t\t\tlastHeartbeat: '',\n\t\t\t\t\t\theartbeatInterval: '',\n\t\t\t\t\t\tfailReason: '',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\tjob.status = JobStatus.COMPLETED;\n\t\t}\n\t}\n\n\t/**\n\t * Handle job failure with exponential backoff retry logic.\n\t *\n\t * Increments `failCount` and calculates next retry time using exponential backoff:\n\t * `nextRunAt = 2^failCount × baseRetryInterval` (capped by optional `maxBackoffDelay`).\n\t *\n\t * If `failCount >= maxRetries`, marks job as permanently `failed`. Otherwise, resets\n\t * to `pending` status for retry. Stores error message in `failReason` field.\n\t *\n\t * @private\n\t * @param job - The job that failed\n\t * @param error - The error that caused the failure\n\t */\n\tprivate async failJob(job: Job, error: Error): Promise<void> {\n\t\tif (!this.collection || !isPersistedJob(job)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst newFailCount = job.failCount + 1;\n\n\t\tif (newFailCount >= this.options.maxRetries) {\n\t\t\t// Permanent failure\n\t\t\tawait this.collection.updateOne(\n\t\t\t\t{ _id: job._id },\n\t\t\t\t{\n\t\t\t\t\t$set: {\n\t\t\t\t\t\tstatus: JobStatus.FAILED,\n\t\t\t\t\t\tfailCount: newFailCount,\n\t\t\t\t\t\tfailReason: error.message,\n\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t},\n\t\t\t\t\t$unset: {\n\t\t\t\t\t\tlockedAt: '',\n\t\t\t\t\t\tclaimedBy: '',\n\t\t\t\t\t\tlastHeartbeat: '',\n\t\t\t\t\t\theartbeatInterval: '',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t} else {\n\t\t\t// Schedule retry with exponential backoff\n\t\t\tconst nextRunAt = calculateBackoff(\n\t\t\t\tnewFailCount,\n\t\t\t\tthis.options.baseRetryInterval,\n\t\t\t\tthis.options.maxBackoffDelay,\n\t\t\t);\n\n\t\t\tawait this.collection.updateOne(\n\t\t\t\t{ _id: job._id },\n\t\t\t\t{\n\t\t\t\t\t$set: {\n\t\t\t\t\t\tstatus: JobStatus.PENDING,\n\t\t\t\t\t\tfailCount: newFailCount,\n\t\t\t\t\t\tfailReason: error.message,\n\t\t\t\t\t\tnextRunAt,\n\t\t\t\t\t\tupdatedAt: new Date(),\n\t\t\t\t\t},\n\t\t\t\t\t$unset: {\n\t\t\t\t\t\tlockedAt: '',\n\t\t\t\t\t\tclaimedBy: '',\n\t\t\t\t\t\tlastHeartbeat: '',\n\t\t\t\t\t\theartbeatInterval: '',\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Ensure the scheduler is initialized before operations.\n\t *\n\t * @private\n\t * @throws {ConnectionError} If scheduler not initialized or collection unavailable\n\t */\n\tprivate ensureInitialized(): void {\n\t\tif (!this.isInitialized || !this.collection) {\n\t\t\tthrow new ConnectionError('Monque not initialized. Call initialize() first.');\n\t\t}\n\t}\n\n\t/**\n\t * Update heartbeats for all jobs claimed by this scheduler instance.\n\t *\n\t * This method runs periodically while the scheduler is running to indicate\n\t * that jobs are still being actively processed.\n\t *\n\t * `lastHeartbeat` is primarily an observability signal (monitoring/debugging).\n\t * Stale recovery is based on `lockedAt` + `lockTimeout`.\n\t *\n\t * @private\n\t */\n\tprivate async updateHeartbeats(): Promise<void> {\n\t\tif (!this.collection || !this.isRunning) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst now = new Date();\n\n\t\tawait this.collection.updateMany(\n\t\t\t{\n\t\t\t\tclaimedBy: this.options.schedulerInstanceId,\n\t\t\t\tstatus: JobStatus.PROCESSING,\n\t\t\t},\n\t\t\t{\n\t\t\t\t$set: {\n\t\t\t\t\tlastHeartbeat: now,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t}\n\n\t/**\n\t * Set up MongoDB Change Stream for real-time job notifications.\n\t *\n\t * Change streams provide instant notifications when jobs are inserted or when\n\t * job status changes to pending (e.g., after a retry). This eliminates the\n\t * polling delay for reactive job processing.\n\t *\n\t * The change stream watches for:\n\t * - Insert operations (new jobs)\n\t * - Update operations where status field changes\n\t *\n\t * If change streams are unavailable (e.g., standalone MongoDB), the system\n\t * gracefully falls back to polling-only mode.\n\t *\n\t * @private\n\t */\n\tprivate setupChangeStream(): void {\n\t\tif (!this.collection || !this.isRunning) {\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\t// Create change stream with pipeline to filter relevant events\n\t\t\tconst pipeline = [\n\t\t\t\t{\n\t\t\t\t\t$match: {\n\t\t\t\t\t\t$or: [\n\t\t\t\t\t\t\t{ operationType: 'insert' },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\toperationType: 'update',\n\t\t\t\t\t\t\t\t'updateDescription.updatedFields.status': { $exists: true },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t];\n\n\t\t\tthis.changeStream = this.collection.watch(pipeline, {\n\t\t\t\tfullDocument: 'updateLookup',\n\t\t\t});\n\n\t\t\t// Handle change events\n\t\t\tthis.changeStream.on('change', (change) => {\n\t\t\t\tthis.handleChangeStreamEvent(change);\n\t\t\t});\n\n\t\t\t// Handle errors with reconnection\n\t\t\tthis.changeStream.on('error', (error: Error) => {\n\t\t\t\tthis.emit('changestream:error', { error });\n\t\t\t\tthis.handleChangeStreamError(error);\n\t\t\t});\n\n\t\t\t// Mark as connected\n\t\t\tthis.usingChangeStreams = true;\n\t\t\tthis.changeStreamReconnectAttempts = 0;\n\t\t\tthis.emit('changestream:connected', undefined);\n\t\t} catch (error) {\n\t\t\t// Change streams not available (e.g., standalone MongoDB)\n\t\t\tthis.usingChangeStreams = false;\n\t\t\tconst reason = error instanceof Error ? error.message : 'Unknown error';\n\t\t\tthis.emit('changestream:fallback', { reason });\n\t\t}\n\t}\n\n\t/**\n\t * Handle a change stream event by triggering a debounced poll.\n\t *\n\t * Events are debounced to prevent \"claim storms\" when multiple changes arrive\n\t * in rapid succession (e.g., bulk job inserts). A 100ms debounce window\n\t * collects multiple events and triggers a single poll.\n\t *\n\t * @private\n\t * @param change - The change stream event document\n\t */\n\tprivate handleChangeStreamEvent(change: ChangeStreamDocument<Document>): void {\n\t\tif (!this.isRunning) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Trigger poll on insert (new job) or update where status changes\n\t\tconst isInsert = change.operationType === 'insert';\n\t\tconst isUpdate = change.operationType === 'update';\n\n\t\t// Get fullDocument if available (for insert or with updateLookup option)\n\t\tconst fullDocument = 'fullDocument' in change ? change.fullDocument : undefined;\n\t\tconst isPendingStatus = fullDocument?.['status'] === JobStatus.PENDING;\n\n\t\t// For inserts: always trigger since new pending jobs need processing\n\t\t// For updates: trigger if status changed to pending (retry/release scenario)\n\t\tconst shouldTrigger = isInsert || (isUpdate && isPendingStatus);\n\n\t\tif (shouldTrigger) {\n\t\t\t// Debounce poll triggers to avoid claim storms\n\t\t\tif (this.changeStreamDebounceTimer) {\n\t\t\t\tclearTimeout(this.changeStreamDebounceTimer);\n\t\t\t}\n\n\t\t\tthis.changeStreamDebounceTimer = setTimeout(() => {\n\t\t\t\tthis.changeStreamDebounceTimer = null;\n\t\t\t\tthis.poll().catch((error: unknown) => {\n\t\t\t\t\tthis.emit('job:error', { error: error as Error });\n\t\t\t\t});\n\t\t\t}, 100);\n\t\t}\n\t}\n\n\t/**\n\t * Handle change stream errors with exponential backoff reconnection.\n\t *\n\t * Attempts to reconnect up to `maxChangeStreamReconnectAttempts` times with\n\t * exponential backoff (base 1000ms). After exhausting retries, falls back to\n\t * polling-only mode.\n\t *\n\t * @private\n\t * @param error - The error that caused the change stream failure\n\t */\n\tprivate handleChangeStreamError(error: Error): void {\n\t\tif (!this.isRunning) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.changeStreamReconnectAttempts++;\n\n\t\tif (this.changeStreamReconnectAttempts > this.maxChangeStreamReconnectAttempts) {\n\t\t\t// Fall back to polling-only mode\n\t\t\tthis.usingChangeStreams = false;\n\t\t\tthis.emit('changestream:fallback', {\n\t\t\t\treason: `Exhausted ${this.maxChangeStreamReconnectAttempts} reconnection attempts: ${error.message}`,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Exponential backoff: 1s, 2s, 4s\n\t\tconst delay = 2 ** (this.changeStreamReconnectAttempts - 1) * 1000;\n\n\t\t// Clear any existing reconnect timer before scheduling a new one\n\t\tif (this.changeStreamReconnectTimer) {\n\t\t\tclearTimeout(this.changeStreamReconnectTimer);\n\t\t}\n\n\t\tthis.changeStreamReconnectTimer = setTimeout(() => {\n\t\t\tthis.changeStreamReconnectTimer = null;\n\t\t\tif (this.isRunning) {\n\t\t\t\t// Close existing change stream before reconnecting\n\t\t\t\tif (this.changeStream) {\n\t\t\t\t\tthis.changeStream.close().catch(() => {});\n\t\t\t\t\tthis.changeStream = null;\n\t\t\t\t}\n\t\t\t\tthis.setupChangeStream();\n\t\t\t}\n\t\t}, delay);\n\t}\n\n\t/**\n\t * Close the change stream cursor and emit closed event.\n\t *\n\t * @private\n\t */\n\tprivate async closeChangeStream(): Promise<void> {\n\t\tif (this.changeStream) {\n\t\t\ttry {\n\t\t\t\tawait this.changeStream.close();\n\t\t\t} catch {\n\t\t\t\t// Ignore close errors during shutdown\n\t\t\t}\n\t\t\tthis.changeStream = null;\n\n\t\t\tif (this.usingChangeStreams) {\n\t\t\t\tthis.emit('changestream:closed', undefined);\n\t\t\t}\n\t\t}\n\n\t\tthis.usingChangeStreams = false;\n\t\tthis.changeStreamReconnectAttempts = 0;\n\t}\n\n\t/**\n\t * Get array of active job IDs across all workers.\n\t *\n\t * @private\n\t * @returns Array of job ID strings currently being processed\n\t */\n\tprivate getActiveJobs(): string[] {\n\t\tconst activeJobs: string[] = [];\n\t\tfor (const worker of this.workers.values()) {\n\t\t\tactiveJobs.push(...worker.activeJobs.keys());\n\t\t}\n\t\treturn activeJobs;\n\t}\n\n\t/**\n\t * Get list of active job documents (for shutdown timeout error).\n\t *\n\t * @private\n\t * @returns Array of active Job objects\n\t */\n\tprivate getActiveJobsList(): Job[] {\n\t\tconst activeJobs: Job[] = [];\n\t\tfor (const worker of this.workers.values()) {\n\t\t\tactiveJobs.push(...worker.activeJobs.values());\n\t\t}\n\t\treturn activeJobs;\n\t}\n\n\t/**\n\t * Convert a MongoDB document to a typed PersistedJob object.\n\t *\n\t * Maps raw MongoDB document fields to the strongly-typed `PersistedJob<T>` interface,\n\t * ensuring type safety and handling optional fields (`lockedAt`, `failReason`, etc.).\n\t *\n\t * @private\n\t * @template T - The job data payload type\n\t * @param doc - The raw MongoDB document with `_id`\n\t * @returns A strongly-typed PersistedJob object with guaranteed `_id`\n\t */\n\tprivate documentToPersistedJob<T>(doc: WithId<Document>): PersistedJob<T> {\n\t\tconst job: PersistedJob<T> = {\n\t\t\t_id: doc._id,\n\t\t\tname: doc['name'] as string,\n\t\t\tdata: doc['data'] as T,\n\t\t\tstatus: doc['status'] as JobStatusType,\n\t\t\tnextRunAt: doc['nextRunAt'] as Date,\n\t\t\tfailCount: doc['failCount'] as number,\n\t\t\tcreatedAt: doc['createdAt'] as Date,\n\t\t\tupdatedAt: doc['updatedAt'] as Date,\n\t\t};\n\n\t\t// Only set optional properties if they exist\n\t\tif (doc['lockedAt'] !== undefined) {\n\t\t\tjob.lockedAt = doc['lockedAt'] as Date | null;\n\t\t}\n\t\tif (doc['claimedBy'] !== undefined) {\n\t\t\tjob.claimedBy = doc['claimedBy'] as string | null;\n\t\t}\n\t\tif (doc['lastHeartbeat'] !== undefined) {\n\t\t\tjob.lastHeartbeat = doc['lastHeartbeat'] as Date | null;\n\t\t}\n\t\tif (doc['heartbeatInterval'] !== undefined) {\n\t\t\tjob.heartbeatInterval = doc['heartbeatInterval'] as number;\n\t\t}\n\t\tif (doc['failReason'] !== undefined) {\n\t\t\tjob.failReason = doc['failReason'] as string;\n\t\t}\n\t\tif (doc['repeatInterval'] !== undefined) {\n\t\t\tjob.repeatInterval = doc['repeatInterval'] as string;\n\t\t}\n\t\tif (doc['uniqueKey'] !== undefined) {\n\t\t\tjob.uniqueKey = doc['uniqueKey'] as string;\n\t\t}\n\n\t\treturn job;\n\t}\n\n\t/**\n\t * Type-safe event emitter methods\n\t */\n\toverride emit<K extends keyof MonqueEventMap>(event: K, payload: MonqueEventMap[K]): boolean {\n\t\treturn super.emit(event, payload);\n\t}\n\n\toverride on<K extends keyof MonqueEventMap>(\n\t\tevent: K,\n\t\tlistener: (payload: MonqueEventMap[K]) => void,\n\t): this {\n\t\treturn super.on(event, listener);\n\t}\n\n\toverride once<K extends keyof MonqueEventMap>(\n\t\tevent: K,\n\t\tlistener: (payload: MonqueEventMap[K]) => void,\n\t): this {\n\t\treturn super.once(event, listener);\n\t}\n\n\toverride off<K extends keyof MonqueEventMap>(\n\t\tevent: K,\n\t\tlistener: (payload: MonqueEventMap[K]) => void,\n\t): this {\n\t\treturn super.off(event, listener);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,YAAY;CAExB,SAAS;CAET,YAAY;CAEZ,WAAW;CAEX,QAAQ;CACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACSD,SAAgB,eAAkB,KAAqC;AACtE,QAAO,SAAS,OAAO,IAAI,QAAQ,UAAa,IAAI,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA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AAM,CAAC;AAE7C,SAAO;;;;;;;;CASR,AAAQ,oBAA2B;EAClC,MAAM,aAAoB,EAAE;AAC5B,OAAK,MAAM,UAAU,KAAK,QAAQ,QAAQ,CACzC,YAAW,KAAK,GAAG,OAAO,WAAW,QAAQ,CAAC;AAE/C,SAAO;;;;;;;;;;;;;CAcR,AAAQ,uBAA0B,KAAwC;EACzE,MAAM,MAAuB;GAC5B,KAAK,IAAI;GACT,MAAM,IAAI;GACV,MAAM,IAAI;GACV,QAAQ,IAAI;GACZ,WAAW,IAAI;GACf,WAAW,IAAI;GACf,WAAW,IAAI;GACf,WAAW,IAAI;GACf;AAGD,MAAI,IAAI,gBAAgB,OACvB,KAAI,WAAW,IAAI;AAEpB,MAAI,IAAI,iBAAiB,OACxB,KAAI,YAAY,IAAI;AAErB,MAAI,IAAI,qBAAqB,OAC5B,KAAI,gBAAgB,IAAI;AAEzB,MAAI,IAAI,yBAAyB,OAChC,KAAI,oBAAoB,IAAI;AAE7B,MAAI,IAAI,kBAAkB,OACzB,KAAI,aAAa,IAAI;AAEtB,MAAI,IAAI,sBAAsB,OAC7B,KAAI,iBAAiB,IAAI;AAE1B,MAAI,IAAI,iBAAiB,OACxB,KAAI,YAAY,IAAI;AAGrB,SAAO;;;;;CAMR,AAAS,KAAqC,OAAU,SAAqC;AAC5F,SAAO,MAAM,KAAK,OAAO,QAAQ;;CAGlC,AAAS,GACR,OACA,UACO;AACP,SAAO,MAAM,GAAG,OAAO,SAAS;;CAGjC,AAAS,KACR,OACA,UACO;AACP,SAAO,MAAM,KAAK,OAAO,SAAS;;CAGnC,AAAS,IACR,OACA,UACO;AACP,SAAO,MAAM,IAAI,OAAO,SAAS"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@monque/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "MongoDB-backed job scheduler with atomic locking, exponential backoff, and cron scheduling",
|
|
5
5
|
"author": "Maurice de Bruyn <debruyn.maurice@gmail.com>",
|
|
6
6
|
"repository": {
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"type": "module",
|
|
17
17
|
"packageManager": "bun@1.3.5",
|
|
18
18
|
"engines": {
|
|
19
|
-
"node": ">=
|
|
19
|
+
"node": ">=22.0.0"
|
|
20
20
|
},
|
|
21
21
|
"publishConfig": {
|
|
22
22
|
"access": "public"
|
|
@@ -79,13 +79,13 @@
|
|
|
79
79
|
"@faker-js/faker": "^10.2.0",
|
|
80
80
|
"@testcontainers/mongodb": "^11.11.0",
|
|
81
81
|
"@total-typescript/ts-reset": "^0.6.1",
|
|
82
|
-
"@types/bun": "^1.3.
|
|
83
|
-
"@vitest/coverage-v8": "^4.0.
|
|
82
|
+
"@types/bun": "^1.3.6",
|
|
83
|
+
"@vitest/coverage-v8": "^4.0.17",
|
|
84
84
|
"fishery": "^2.4.0",
|
|
85
85
|
"mongodb": "^7.0.0",
|
|
86
86
|
"publint": "^0.3.16",
|
|
87
|
-
"tsdown": "^0.
|
|
87
|
+
"tsdown": "^0.19.0",
|
|
88
88
|
"typescript": "^5.9.3",
|
|
89
|
-
"vitest": "^4.0.
|
|
89
|
+
"vitest": "^4.0.17"
|
|
90
90
|
}
|
|
91
91
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors-BX3oWYfZ.cjs","names":["expression: string","incompleteJobs: Job[]","jobName: string"],"sources":["../src/shared/errors.ts"],"sourcesContent":["import type { Job } from '@/jobs';\n\n/**\n * Base error class for all Monque-related errors.\n *\n * @example\n * ```typescript\n * try {\n * await monque.enqueue('job', data);\n * } catch (error) {\n * if (error instanceof MonqueError) {\n * console.error('Monque error:', error.message);\n * }\n * }\n * ```\n */\nexport class MonqueError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = 'MonqueError';\n\t\t// Maintains proper stack trace for where our error was thrown (only available on V8)\n\t\t/* istanbul ignore next -- @preserve captureStackTrace is always available in Node.js */\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, MonqueError);\n\t\t}\n\t}\n}\n\n/**\n * Error thrown when an invalid cron expression is provided.\n *\n * @example\n * ```typescript\n * try {\n * await monque.schedule('invalid cron', 'job', data);\n * } catch (error) {\n * if (error instanceof InvalidCronError) {\n * console.error('Invalid expression:', error.expression);\n * }\n * }\n * ```\n */\nexport class InvalidCronError extends MonqueError {\n\tconstructor(\n\t\tpublic readonly expression: string,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'InvalidCronError';\n\t\t/* istanbul ignore next -- @preserve captureStackTrace is always available in Node.js */\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, InvalidCronError);\n\t\t}\n\t}\n}\n\n/**\n * Error thrown when there's a database connection issue.\n *\n * @example\n * ```typescript\n * try {\n * await monque.enqueue('job', data);\n * } catch (error) {\n * if (error instanceof ConnectionError) {\n * console.error('Database connection lost');\n * }\n * }\n * ```\n */\nexport class ConnectionError extends MonqueError {\n\tconstructor(message: string, options?: { cause?: Error }) {\n\t\tsuper(message);\n\t\tthis.name = 'ConnectionError';\n\t\tif (options?.cause) {\n\t\t\tthis.cause = options.cause;\n\t\t}\n\t\t/* istanbul ignore next -- @preserve captureStackTrace is always available in Node.js */\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, ConnectionError);\n\t\t}\n\t}\n}\n\n/**\n * Error thrown when graceful shutdown times out.\n * Includes information about jobs that were still in progress.\n *\n * @example\n * ```typescript\n * try {\n * await monque.stop();\n * } catch (error) {\n * if (error instanceof ShutdownTimeoutError) {\n * console.error('Incomplete jobs:', error.incompleteJobs.length);\n * }\n * }\n * ```\n */\nexport class ShutdownTimeoutError extends MonqueError {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly incompleteJobs: Job[],\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'ShutdownTimeoutError';\n\t\t/* istanbul ignore next -- @preserve captureStackTrace is always available in Node.js */\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, ShutdownTimeoutError);\n\t\t}\n\t}\n}\n\n/**\n * Error thrown when attempting to register a worker for a job name\n * that already has a registered worker, without explicitly allowing replacement.\n *\n * @example\n * ```typescript\n * try {\n * monque.worker('send-email', handler1);\n * monque.worker('send-email', handler2); // throws\n * } catch (error) {\n * if (error instanceof WorkerRegistrationError) {\n * console.error('Worker already registered for:', error.jobName);\n * }\n * }\n *\n * // To intentionally replace a worker:\n * monque.worker('send-email', handler2, { replace: true });\n * ```\n */\nexport class WorkerRegistrationError extends MonqueError {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly jobName: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'WorkerRegistrationError';\n\t\t/* istanbul ignore next -- @preserve captureStackTrace is always available in Node.js */\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, WorkerRegistrationError);\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,IAAa,cAAb,MAAa,oBAAoB,MAAM;CACtC,YAAY,SAAiB;AAC5B,QAAM,QAAQ;AACd,OAAK,OAAO;;AAGZ,MAAI,MAAM,kBACT,OAAM,kBAAkB,MAAM,YAAY;;;;;;;;;;;;;;;;;AAmB7C,IAAa,mBAAb,MAAa,yBAAyB,YAAY;CACjD,YACC,AAAgBA,YAChB,SACC;AACD,QAAM,QAAQ;EAHE;AAIhB,OAAK,OAAO;;AAEZ,MAAI,MAAM,kBACT,OAAM,kBAAkB,MAAM,iBAAiB;;;;;;;;;;;;;;;;;AAmBlD,IAAa,kBAAb,MAAa,wBAAwB,YAAY;CAChD,YAAY,SAAiB,SAA6B;AACzD,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,MAAI,SAAS,MACZ,MAAK,QAAQ,QAAQ;;AAGtB,MAAI,MAAM,kBACT,OAAM,kBAAkB,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;AAoBjD,IAAa,uBAAb,MAAa,6BAA6B,YAAY;CACrD,YACC,SACA,AAAgBC,gBACf;AACD,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;AAEZ,MAAI,MAAM,kBACT,OAAM,kBAAkB,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;AAwBtD,IAAa,0BAAb,MAAa,gCAAgC,YAAY;CACxD,YACC,SACA,AAAgBC,SACf;AACD,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;AAEZ,MAAI,MAAM,kBACT,OAAM,kBAAkB,MAAM,wBAAwB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors-DW20rHWR.mjs","names":["expression: string","incompleteJobs: Job[]","jobName: string"],"sources":["../src/shared/errors.ts"],"sourcesContent":["import type { Job } from '@/jobs';\n\n/**\n * Base error class for all Monque-related errors.\n *\n * @example\n * ```typescript\n * try {\n * await monque.enqueue('job', data);\n * } catch (error) {\n * if (error instanceof MonqueError) {\n * console.error('Monque error:', error.message);\n * }\n * }\n * ```\n */\nexport class MonqueError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = 'MonqueError';\n\t\t// Maintains proper stack trace for where our error was thrown (only available on V8)\n\t\t/* istanbul ignore next -- @preserve captureStackTrace is always available in Node.js */\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, MonqueError);\n\t\t}\n\t}\n}\n\n/**\n * Error thrown when an invalid cron expression is provided.\n *\n * @example\n * ```typescript\n * try {\n * await monque.schedule('invalid cron', 'job', data);\n * } catch (error) {\n * if (error instanceof InvalidCronError) {\n * console.error('Invalid expression:', error.expression);\n * }\n * }\n * ```\n */\nexport class InvalidCronError extends MonqueError {\n\tconstructor(\n\t\tpublic readonly expression: string,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'InvalidCronError';\n\t\t/* istanbul ignore next -- @preserve captureStackTrace is always available in Node.js */\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, InvalidCronError);\n\t\t}\n\t}\n}\n\n/**\n * Error thrown when there's a database connection issue.\n *\n * @example\n * ```typescript\n * try {\n * await monque.enqueue('job', data);\n * } catch (error) {\n * if (error instanceof ConnectionError) {\n * console.error('Database connection lost');\n * }\n * }\n * ```\n */\nexport class ConnectionError extends MonqueError {\n\tconstructor(message: string, options?: { cause?: Error }) {\n\t\tsuper(message);\n\t\tthis.name = 'ConnectionError';\n\t\tif (options?.cause) {\n\t\t\tthis.cause = options.cause;\n\t\t}\n\t\t/* istanbul ignore next -- @preserve captureStackTrace is always available in Node.js */\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, ConnectionError);\n\t\t}\n\t}\n}\n\n/**\n * Error thrown when graceful shutdown times out.\n * Includes information about jobs that were still in progress.\n *\n * @example\n * ```typescript\n * try {\n * await monque.stop();\n * } catch (error) {\n * if (error instanceof ShutdownTimeoutError) {\n * console.error('Incomplete jobs:', error.incompleteJobs.length);\n * }\n * }\n * ```\n */\nexport class ShutdownTimeoutError extends MonqueError {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly incompleteJobs: Job[],\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'ShutdownTimeoutError';\n\t\t/* istanbul ignore next -- @preserve captureStackTrace is always available in Node.js */\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, ShutdownTimeoutError);\n\t\t}\n\t}\n}\n\n/**\n * Error thrown when attempting to register a worker for a job name\n * that already has a registered worker, without explicitly allowing replacement.\n *\n * @example\n * ```typescript\n * try {\n * monque.worker('send-email', handler1);\n * monque.worker('send-email', handler2); // throws\n * } catch (error) {\n * if (error instanceof WorkerRegistrationError) {\n * console.error('Worker already registered for:', error.jobName);\n * }\n * }\n *\n * // To intentionally replace a worker:\n * monque.worker('send-email', handler2, { replace: true });\n * ```\n */\nexport class WorkerRegistrationError extends MonqueError {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic readonly jobName: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'WorkerRegistrationError';\n\t\t/* istanbul ignore next -- @preserve captureStackTrace is always available in Node.js */\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, WorkerRegistrationError);\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,IAAa,cAAb,MAAa,oBAAoB,MAAM;CACtC,YAAY,SAAiB;AAC5B,QAAM,QAAQ;AACd,OAAK,OAAO;;AAGZ,MAAI,MAAM,kBACT,OAAM,kBAAkB,MAAM,YAAY;;;;;;;;;;;;;;;;;AAmB7C,IAAa,mBAAb,MAAa,yBAAyB,YAAY;CACjD,YACC,AAAgBA,YAChB,SACC;AACD,QAAM,QAAQ;EAHE;AAIhB,OAAK,OAAO;;AAEZ,MAAI,MAAM,kBACT,OAAM,kBAAkB,MAAM,iBAAiB;;;;;;;;;;;;;;;;;AAmBlD,IAAa,kBAAb,MAAa,wBAAwB,YAAY;CAChD,YAAY,SAAiB,SAA6B;AACzD,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,MAAI,SAAS,MACZ,MAAK,QAAQ,QAAQ;;AAGtB,MAAI,MAAM,kBACT,OAAM,kBAAkB,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;AAoBjD,IAAa,uBAAb,MAAa,6BAA6B,YAAY;CACrD,YACC,SACA,AAAgBC,gBACf;AACD,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;AAEZ,MAAI,MAAM,kBACT,OAAM,kBAAkB,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;AAwBtD,IAAa,0BAAb,MAAa,gCAAgC,YAAY;CACxD,YACC,SACA,AAAgBC,SACf;AACD,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;AAEZ,MAAI,MAAM,kBACT,OAAM,kBAAkB,MAAM,wBAAwB"}
|