UNPKG

@sidequest/engine

Version:

@sidequest/engine is the core engine of SideQuest, a distributed background job processing system for Node.js and TypeScript.

162 lines (159 loc) 6.62 kB
import { Backend, NewJobData } from '@sidequest/backend'; import { TimePeriod, BackoffStrategy, JobClassType, UniquenessConfig, JobData } from '@sidequest/core'; import { ScheduledTask } from 'node-cron'; /** * Configuration for job uniqueness constraints. * * @remarks * Controls how jobs are deduplicated to prevent multiple instances of the same job from running. * * - When `true`: Jobs are made unique based on their type/name only * - When `false`: No uniqueness constraint is applied * - When an object: Provides fine-grained control over uniqueness behavior * * @example * ```typescript * // Simple uniqueness * const unique: UniquenessInput = true; * * // No uniqueness * const notUnique: UniquenessInput = false; * * // Advanced uniqueness with arguments consideration * const advancedUnique: UniquenessInput = { * withArgs: true, * period: { hours: 1 } * }; * ``` */ type UniquenessInput = boolean | { withArgs?: boolean; period?: TimePeriod; }; interface JobBuilderDefaults { /** Default queue name for jobs built with the JobBuilder */ queue?: string; /** Default timeout in milliseconds for jobs built with the JobBuilder */ timeout?: number; /** Default uniqueness configuration for jobs built with the JobBuilder */ uniqueness?: UniquenessInput; /** Default maximum attempts for jobs built with the JobBuilder */ maxAttempts?: number; /** Default available at date for jobs built with the JobBuilder */ availableAt?: Date; /** Default retry delay in milliseconds for jobs built with the JobBuilder */ retryDelay?: number; /** Default backoff strategy for jobs built with the JobBuilder */ backoffStrategy?: BackoffStrategy; } /** * Builder for creating and enqueuing jobs with custom configuration. * @template T The job class type. */ declare class JobBuilder<T extends JobClassType> { protected backend: Backend; protected JobClass: T; protected defaults?: JobBuilderDefaults | undefined; protected manualJobResolution: boolean; protected constructorArgs?: ConstructorParameters<T>; protected queueName?: string; protected jobTimeout?: number; protected uniquenessConfig?: UniquenessConfig; protected jobMaxAttempts?: number; protected jobAvailableAt?: Date; protected jobRetryDelay?: number; protected jobBackoffStrategy?: BackoffStrategy; /** * Creates a new JobBuilder for the given job class. * @param JobClass The job class constructor. */ constructor(backend: Backend, JobClass: T, defaults?: JobBuilderDefaults | undefined, manualJobResolution?: boolean); /** * Sets the constructor arguments for the job. * @param args The constructor arguments. * @returns This builder instance. */ with(...args: ConstructorParameters<T>): this; /** * Sets the queue name for the job. * @param queue The queue name. * @returns This builder instance. */ queue(queue: string): this; /** * Sets the timeout for the job in milliseconds. * @param ms Timeout in milliseconds. * @returns This builder instance. */ timeout(ms: number): this; /** * Sets the uniqueness configuration for the job. * @param value Boolean or uniqueness config object. If true, uses an alive job uniqueness strategy (see {@link AliveJobUniqueness}). * If false, disables uniqueness. If an object, uses the custom uniqueness strategy. * @param value.withArgs If true, uniqueness is based on job class and job arguments. * If false, uniqueness is based only on the job class. * @param value.period If a period is provided, uses a fixed window uniqueness strategy (see {@link FixedWindowUniqueness}). * @returns This builder instance. * @see {@link UniquenessInput} for more details. */ unique(value: UniquenessInput): this; /** * Sets the maximum number of attempts for the job. * @param value The max attempts. * @returns This builder instance. */ maxAttempts(value: number): this; /** * Sets the time when the job becomes available. * @param value The available date. * @returns This builder instance. */ availableAt(value: Date): this; /** * Delay before retrying a failed job, in milliseconds. * * If "backoff_strategy" is "exponential", this value is used as the base delay for calculating exponential backoff. * * @param value The retry delay in milliseconds. * @returns This builder instance. */ retryDelay(value: number): this; /** * Strategy used for calculating backoff delays between retries. * - "exponential": Delays increase exponentially with each attempt. * - "fixed": Delays remain constant for each attempt. * * @param value The backoff strategy. * @returns This builder instance. */ backoffStrategy(value: BackoffStrategy): this; protected build(...args: Parameters<InstanceType<T>["run"]>): Promise<NewJobData>; /** * Enqueues the job with the specified arguments. * @param args Arguments to pass to the job's run method. * @returns A promise resolving to the created job data. */ enqueue(...args: Parameters<InstanceType<T>["run"]>): Promise<JobData>; /** * Registers a recurring schedule to enqueue the job automatically based on a cron expression. * * This sets up an in-memory schedule that enqueues the job with the provided arguments * every time the cron expression is triggered. * * @remarks * - The schedule is **not persisted** to any database. It will be lost if the process restarts and must be re-registered at startup. * - You must call this method during application initialization to ensure the job is scheduled correctly. * - Uses node-cron's `noOverlap: true` option to prevent concurrent executions. * - The scheduled task is registered with the CronRegistry for proper cleanup during shutdown. * * @param cronExpression - A valid cron expression (node-cron compatible) that defines when the job should be enqueued. * @param args - Arguments to be passed to the job's `run` method on each scheduled execution. * * @returns The underlying `ScheduledTask` instance created by node-cron. * * @throws {Error} If the cron expression is invalid. */ schedule(cronExpression: string, ...args: Parameters<InstanceType<T>["run"]>): Promise<ScheduledTask>; } export { JobBuilder }; export type { JobBuilderDefaults, UniquenessInput };