@riktajs/queue 0.10.2 → 0.10.3

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.
Files changed (64) hide show
  1. package/dist/index.cjs +16251 -0
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/index.d.cts +946 -0
  4. package/dist/index.d.ts +945 -21
  5. package/dist/index.js +16177 -29
  6. package/dist/index.js.map +1 -1
  7. package/package.json +13 -6
  8. package/dist/config/queue.config.d.ts +0 -43
  9. package/dist/config/queue.config.d.ts.map +0 -1
  10. package/dist/config/queue.config.js +0 -82
  11. package/dist/config/queue.config.js.map +0 -1
  12. package/dist/constants.d.ts +0 -33
  13. package/dist/constants.d.ts.map +0 -1
  14. package/dist/constants.js +0 -37
  15. package/dist/constants.js.map +0 -1
  16. package/dist/decorators/events.decorator.d.ts +0 -85
  17. package/dist/decorators/events.decorator.d.ts.map +0 -1
  18. package/dist/decorators/events.decorator.js +0 -120
  19. package/dist/decorators/events.decorator.js.map +0 -1
  20. package/dist/decorators/index.d.ts +0 -8
  21. package/dist/decorators/index.d.ts.map +0 -1
  22. package/dist/decorators/index.js +0 -8
  23. package/dist/decorators/index.js.map +0 -1
  24. package/dist/decorators/process.decorator.d.ts +0 -41
  25. package/dist/decorators/process.decorator.d.ts.map +0 -1
  26. package/dist/decorators/process.decorator.js +0 -61
  27. package/dist/decorators/process.decorator.js.map +0 -1
  28. package/dist/decorators/processor.decorator.d.ts +0 -41
  29. package/dist/decorators/processor.decorator.d.ts.map +0 -1
  30. package/dist/decorators/processor.decorator.js +0 -59
  31. package/dist/decorators/processor.decorator.js.map +0 -1
  32. package/dist/decorators/queue.decorator.d.ts +0 -35
  33. package/dist/decorators/queue.decorator.d.ts.map +0 -1
  34. package/dist/decorators/queue.decorator.js +0 -49
  35. package/dist/decorators/queue.decorator.js.map +0 -1
  36. package/dist/events/queue-events.d.ts +0 -32
  37. package/dist/events/queue-events.d.ts.map +0 -1
  38. package/dist/events/queue-events.js +0 -103
  39. package/dist/events/queue-events.js.map +0 -1
  40. package/dist/index.d.ts.map +0 -1
  41. package/dist/monitoring/bull-board.d.ts +0 -77
  42. package/dist/monitoring/bull-board.d.ts.map +0 -1
  43. package/dist/monitoring/bull-board.js +0 -112
  44. package/dist/monitoring/bull-board.js.map +0 -1
  45. package/dist/providers/queue.provider.d.ts +0 -113
  46. package/dist/providers/queue.provider.d.ts.map +0 -1
  47. package/dist/providers/queue.provider.js +0 -383
  48. package/dist/providers/queue.provider.js.map +0 -1
  49. package/dist/services/queue.service.d.ts +0 -133
  50. package/dist/services/queue.service.d.ts.map +0 -1
  51. package/dist/services/queue.service.js +0 -192
  52. package/dist/services/queue.service.js.map +0 -1
  53. package/dist/types.d.ts +0 -133
  54. package/dist/types.d.ts.map +0 -1
  55. package/dist/types.js +0 -5
  56. package/dist/types.js.map +0 -1
  57. package/dist/utils/connection.d.ts +0 -47
  58. package/dist/utils/connection.d.ts.map +0 -1
  59. package/dist/utils/connection.js +0 -102
  60. package/dist/utils/connection.js.map +0 -1
  61. package/dist/utils/validation.d.ts +0 -137
  62. package/dist/utils/validation.d.ts.map +0 -1
  63. package/dist/utils/validation.js +0 -156
  64. package/dist/utils/validation.js.map +0 -1
@@ -0,0 +1,946 @@
1
+ import { QueueOptions, JobsOptions, WorkerOptions, RepeatOptions, Queue as Queue$1, Job } from 'bullmq';
2
+ export { Queue as BullQueue, Job, QueueEvents, Worker } from 'bullmq';
3
+ import { z, ZodSchema, ZodError } from 'zod';
4
+ export { z } from 'zod';
5
+ import { OnProviderInit, OnProviderDestroy } from '@riktajs/core';
6
+ import { FastifyRequest, FastifyInstance } from 'fastify';
7
+ import { Redis, Cluster } from 'ioredis';
8
+ export { Redis } from 'ioredis';
9
+
10
+ /**
11
+ * Constants and DI tokens for @riktajs/queue
12
+ */
13
+ /** Metadata keys for decorator reflection */
14
+ declare const METADATA_KEY: {
15
+ /** Queue class decorator options */
16
+ readonly QUEUE_OPTIONS: "riktajs:queue:options";
17
+ /** Processor class decorator options */
18
+ readonly PROCESSOR_OPTIONS: "riktajs:queue:processor:options";
19
+ /** Job handler method metadata */
20
+ readonly JOB_HANDLERS: "riktajs:queue:job:handlers";
21
+ /** Event handler method metadata */
22
+ readonly EVENT_HANDLERS: "riktajs:queue:event:handlers";
23
+ };
24
+ /** DI token for the QueueProvider */
25
+ declare const QUEUE_PROVIDER: unique symbol;
26
+ /** DI token for the QueueService */
27
+ declare const QUEUE_SERVICE: unique symbol;
28
+ /** DI token for the Redis connection */
29
+ declare const QUEUE_REDIS_CONNECTION: unique symbol;
30
+ /** DI token for the queue configuration */
31
+ declare const QUEUE_CONFIG: unique symbol;
32
+ /**
33
+ * Get the DI token for a named queue
34
+ * @param name - The queue name
35
+ */
36
+ declare function getQueueToken(name: string): symbol;
37
+ /**
38
+ * Get the DI token for a named worker
39
+ * @param name - The queue name
40
+ */
41
+ declare function getWorkerToken(name: string): symbol;
42
+
43
+ /**
44
+ * Type definitions for @riktajs/queue
45
+ */
46
+
47
+ /** Redis connection configuration */
48
+ interface RedisConnectionOptions {
49
+ /** Redis host */
50
+ host?: string;
51
+ /** Redis port */
52
+ port?: number;
53
+ /** Redis password */
54
+ password?: string;
55
+ /** Redis username */
56
+ username?: string;
57
+ /** Redis database number */
58
+ db?: number;
59
+ /** Enable TLS */
60
+ tls?: boolean;
61
+ /** Cluster mode configuration */
62
+ cluster?: {
63
+ nodes: Array<{
64
+ host: string;
65
+ port: number;
66
+ }>;
67
+ };
68
+ }
69
+ /** Options for @Queue decorator */
70
+ interface QueueDecoratorOptions {
71
+ /** Queue name (required) */
72
+ name: string;
73
+ /** BullMQ queue options */
74
+ options?: Omit<QueueOptions, 'connection'>;
75
+ /** Default job options */
76
+ defaultJobOptions?: JobsOptions;
77
+ }
78
+ /** Options for @Processor decorator */
79
+ interface ProcessorOptions {
80
+ /** The queue name to process */
81
+ queueName: string;
82
+ /** Worker concurrency */
83
+ concurrency?: number;
84
+ /** Rate limiter configuration */
85
+ rateLimiter?: {
86
+ /** Maximum jobs per duration */
87
+ max: number;
88
+ /** Duration in milliseconds */
89
+ duration: number;
90
+ };
91
+ /** Additional BullMQ worker options */
92
+ workerOptions?: Omit<WorkerOptions, 'connection' | 'concurrency' | 'limiter'>;
93
+ }
94
+ /** Metadata for a job handler method */
95
+ interface JobHandlerMeta {
96
+ /** Job name */
97
+ name: string;
98
+ /** Method name on the processor class */
99
+ methodName: string;
100
+ /** Validation schema (Zod) */
101
+ schema?: unknown;
102
+ }
103
+ /** Queue event names */
104
+ type QueueEventName$1 = 'job:added' | 'job:completed' | 'job:failed' | 'job:progress' | 'job:stalled' | 'job:delayed' | 'job:removed' | 'worker:ready' | 'worker:closed' | 'worker:error';
105
+ /** Metadata for an event handler method */
106
+ interface EventHandlerMeta {
107
+ /** Event name */
108
+ event: QueueEventName$1;
109
+ /** Method name on the processor class */
110
+ methodName: string;
111
+ }
112
+ /** Event payload for queue events */
113
+ interface QueueEventPayload<TData = unknown, TResult = unknown> {
114
+ /** Queue name */
115
+ queueName: string;
116
+ /** Job ID */
117
+ jobId: string;
118
+ /** Job name */
119
+ jobName: string;
120
+ /** Job data */
121
+ data: TData;
122
+ /** Job return value (for completed events) */
123
+ returnValue?: TResult;
124
+ /** Number of attempts made */
125
+ attemptsMade?: number;
126
+ /** Error message (for failed events) */
127
+ error?: string;
128
+ /** Progress value (for progress events) */
129
+ progress?: number | object;
130
+ /** Timestamp */
131
+ timestamp: number;
132
+ }
133
+ /** Options for adding a job */
134
+ interface AddJobOptions extends JobsOptions {
135
+ /** Deduplicate by this key */
136
+ deduplicationKey?: string;
137
+ }
138
+ /** Repeat options for scheduled jobs */
139
+ interface ScheduleOptions extends RepeatOptions {
140
+ /** Job ID for the repeatable job */
141
+ jobId?: string;
142
+ }
143
+ /** Queue configuration from environment/config */
144
+ interface QueueConfig {
145
+ /** Redis connection options */
146
+ redis: RedisConnectionOptions;
147
+ /** Default worker concurrency */
148
+ defaultConcurrency?: number;
149
+ /** Default rate limiter */
150
+ defaultRateLimiter?: {
151
+ max: number;
152
+ duration: number;
153
+ };
154
+ /** Bull Board dashboard path */
155
+ dashboardPath?: string;
156
+ /** Enable dashboard (default: false in production) */
157
+ dashboardEnabled?: boolean;
158
+ /** Graceful shutdown timeout in ms */
159
+ shutdownTimeout?: number;
160
+ }
161
+ /** Provider options for creating QueueProvider */
162
+ interface QueueProviderOptions {
163
+ /** Queue configuration */
164
+ config?: Partial<QueueConfig>;
165
+ /** Auto-initialize on provider init */
166
+ autoInitialize?: boolean;
167
+ /** Retry connection attempts */
168
+ retryAttempts?: number;
169
+ /** Delay between retries in ms */
170
+ retryDelay?: number;
171
+ }
172
+
173
+ /**
174
+ * Queue configuration schema and loader
175
+ */
176
+
177
+ /** Zod schema for queue configuration */
178
+ declare const QueueConfigSchema: z.ZodObject<{
179
+ redis: z.ZodObject<{
180
+ host: z.ZodDefault<z.ZodString>;
181
+ port: z.ZodDefault<z.ZodNumber>;
182
+ password: z.ZodOptional<z.ZodString>;
183
+ db: z.ZodDefault<z.ZodNumber>;
184
+ username: z.ZodOptional<z.ZodString>;
185
+ tls: z.ZodOptional<z.ZodBoolean>;
186
+ cluster: z.ZodOptional<z.ZodObject<{
187
+ nodes: z.ZodArray<z.ZodObject<{
188
+ host: z.ZodString;
189
+ port: z.ZodNumber;
190
+ }, z.core.$strip>>;
191
+ }, z.core.$strip>>;
192
+ }, z.core.$strip>;
193
+ defaultConcurrency: z.ZodDefault<z.ZodNumber>;
194
+ defaultRateLimiter: z.ZodOptional<z.ZodObject<{
195
+ max: z.ZodNumber;
196
+ duration: z.ZodNumber;
197
+ }, z.core.$strip>>;
198
+ dashboardPath: z.ZodDefault<z.ZodString>;
199
+ dashboardEnabled: z.ZodDefault<z.ZodBoolean>;
200
+ shutdownTimeout: z.ZodDefault<z.ZodNumber>;
201
+ }, z.core.$strip>;
202
+ type QueueConfigInput = z.input<typeof QueueConfigSchema>;
203
+ /**
204
+ * Load queue configuration from environment variables
205
+ * @param overrides - Optional configuration overrides
206
+ */
207
+ declare function loadQueueConfig(overrides?: Partial<QueueConfigInput>): QueueConfig;
208
+ /**
209
+ * Error thrown when queue configuration is invalid
210
+ */
211
+ declare class QueueConfigError extends Error {
212
+ constructor(message: string);
213
+ }
214
+
215
+ /**
216
+ * @Queue decorator - marks a class as a queue definition
217
+ */
218
+
219
+ /**
220
+ * Decorator to define a queue
221
+ *
222
+ * @param options - Queue configuration options
223
+ * @returns ClassDecorator
224
+ *
225
+ * @example
226
+ * ```typescript
227
+ * @Queue({ name: 'email-queue' })
228
+ * class EmailQueue {}
229
+ * ```
230
+ */
231
+ declare function Queue(options: QueueDecoratorOptions): ClassDecorator;
232
+ /**
233
+ * Get queue options from a decorated class
234
+ * @param target - The decorated class
235
+ */
236
+ declare function getQueueOptions(target: Function): QueueDecoratorOptions | undefined;
237
+ /**
238
+ * Check if a class is decorated with @Queue
239
+ * @param target - The class to check
240
+ */
241
+ declare function isQueue(target: Function): boolean;
242
+ /**
243
+ * Error thrown when @Queue decorator is used incorrectly
244
+ */
245
+ declare class QueueDecoratorError extends Error {
246
+ constructor(message: string);
247
+ }
248
+
249
+ /**
250
+ * @Processor decorator - marks a class as a job processor
251
+ */
252
+
253
+ /**
254
+ * Decorator to define a job processor for a queue
255
+ *
256
+ * @param queueName - The name of the queue to process
257
+ * @param options - Optional processor configuration
258
+ * @returns ClassDecorator
259
+ *
260
+ * @example
261
+ * ```typescript
262
+ * @Processor('email-queue', { concurrency: 5 })
263
+ * class EmailProcessor {
264
+ * @Process('send')
265
+ * async handleSendEmail(job: Job) {
266
+ * // process job
267
+ * }
268
+ * }
269
+ * ```
270
+ */
271
+ declare function Processor(queueName: string, options?: Omit<ProcessorOptions, 'queueName'>): ClassDecorator;
272
+ /**
273
+ * Get processor options from a decorated class
274
+ * @param target - The decorated class
275
+ */
276
+ declare function getProcessorOptions(target: Function): ProcessorOptions | undefined;
277
+ /**
278
+ * Check if a class is decorated with @Processor
279
+ * @param target - The class to check
280
+ */
281
+ declare function isProcessor(target: Function): boolean;
282
+ /**
283
+ * Error thrown when @Processor decorator is used incorrectly
284
+ */
285
+ declare class ProcessorDecoratorError extends Error {
286
+ constructor(message: string);
287
+ }
288
+
289
+ /**
290
+ * @Process decorator - marks a method as a job handler
291
+ */
292
+
293
+ /**
294
+ * Decorator to define a job handler method
295
+ *
296
+ * @param jobName - The name of the job to handle (default: method name)
297
+ * @returns MethodDecorator
298
+ *
299
+ * @example
300
+ * ```typescript
301
+ * @Processor('email-queue')
302
+ * class EmailProcessor {
303
+ * @Process('send')
304
+ * async handleSendEmail(job: Job<EmailData>) {
305
+ * await sendEmail(job.data);
306
+ * return { sent: true };
307
+ * }
308
+ *
309
+ * @Process() // Uses method name as job name
310
+ * async welcome(job: Job<WelcomeData>) {
311
+ * // ...
312
+ * }
313
+ * }
314
+ * ```
315
+ */
316
+ declare function Process(jobName?: string): MethodDecorator;
317
+ /**
318
+ * Get all job handlers from a processor class
319
+ * @param target - The processor class
320
+ */
321
+ declare function getJobHandlers(target: Function): JobHandlerMeta[];
322
+ /**
323
+ * Check if a method is decorated with @Process
324
+ * @param target - The class
325
+ * @param methodName - The method name
326
+ */
327
+ declare function isJobHandler(target: Function, methodName: string): boolean;
328
+
329
+ /**
330
+ * Event decorators for job lifecycle events
331
+ */
332
+
333
+ /**
334
+ * Decorator for handling job completion events
335
+ *
336
+ * @example
337
+ * ```typescript
338
+ * @Processor('my-queue')
339
+ * class MyProcessor {
340
+ * @OnJobComplete()
341
+ * async handleComplete(job: Job, result: unknown) {
342
+ * console.log(`Job ${job.id} completed with:`, result);
343
+ * }
344
+ * }
345
+ * ```
346
+ */
347
+ declare function OnJobComplete(): MethodDecorator;
348
+ /**
349
+ * Decorator for handling job failure events
350
+ *
351
+ * @example
352
+ * ```typescript
353
+ * @Processor('my-queue')
354
+ * class MyProcessor {
355
+ * @OnJobFailed()
356
+ * async handleFailed(job: Job, error: Error) {
357
+ * console.error(`Job ${job.id} failed:`, error);
358
+ * }
359
+ * }
360
+ * ```
361
+ */
362
+ declare function OnJobFailed(): MethodDecorator;
363
+ /**
364
+ * Decorator for handling job progress events
365
+ *
366
+ * @example
367
+ * ```typescript
368
+ * @Processor('my-queue')
369
+ * class MyProcessor {
370
+ * @OnJobProgress()
371
+ * async handleProgress(job: Job, progress: number | object) {
372
+ * console.log(`Job ${job.id} progress:`, progress);
373
+ * }
374
+ * }
375
+ * ```
376
+ */
377
+ declare function OnJobProgress(): MethodDecorator;
378
+ /**
379
+ * Decorator for handling job stalled events
380
+ *
381
+ * @example
382
+ * ```typescript
383
+ * @Processor('my-queue')
384
+ * class MyProcessor {
385
+ * @OnJobStalled()
386
+ * async handleStalled(jobId: string) {
387
+ * console.warn(`Job ${jobId} stalled`);
388
+ * }
389
+ * }
390
+ * ```
391
+ */
392
+ declare function OnJobStalled(): MethodDecorator;
393
+ /**
394
+ * Decorator for handling worker ready events
395
+ */
396
+ declare function OnWorkerReady(): MethodDecorator;
397
+ /**
398
+ * Decorator for handling worker error events
399
+ */
400
+ declare function OnWorkerError(): MethodDecorator;
401
+ /**
402
+ * Get all event handlers from a processor class
403
+ * @param target - The processor class
404
+ */
405
+ declare function getEventHandlers(target: Function): EventHandlerMeta[];
406
+ /**
407
+ * Get event handlers for a specific event
408
+ * @param target - The processor class
409
+ * @param event - The event name
410
+ */
411
+ declare function getEventHandlersFor(target: Function, event: QueueEventName$1): EventHandlerMeta[];
412
+
413
+ /**
414
+ * QueueProvider - Main provider for queue lifecycle management
415
+ *
416
+ * Implements OnProviderInit and OnProviderDestroy for Rikta lifecycle integration.
417
+ * Not @Injectable - use createQueueProvider() factory function.
418
+ */
419
+
420
+ /**
421
+ * QueueProvider manages the lifecycle of all queues and workers.
422
+ *
423
+ * @example
424
+ * ```typescript
425
+ * const provider = createQueueProvider({
426
+ * config: { redis: { host: 'localhost', port: 6379 } }
427
+ * });
428
+ *
429
+ * // In Rikta bootstrap:
430
+ * await app.register(provider);
431
+ * ```
432
+ */
433
+ declare class QueueProvider implements OnProviderInit, OnProviderDestroy {
434
+ private connectionManager;
435
+ private config;
436
+ private queues;
437
+ private workers;
438
+ private processorClasses;
439
+ private initialized;
440
+ private eventBus;
441
+ private options;
442
+ /**
443
+ * Configure the provider with options
444
+ */
445
+ configure(options: QueueProviderOptions): this;
446
+ /**
447
+ * Register processor classes for auto-discovery
448
+ */
449
+ registerProcessors(...processors: Function[]): this;
450
+ /**
451
+ * Set EventBus for event emission (optional)
452
+ */
453
+ setEventBus(eventBus: unknown): this;
454
+ /**
455
+ * Initialize all queues and workers (called by Rikta lifecycle)
456
+ */
457
+ onProviderInit(): Promise<void>;
458
+ /**
459
+ * Gracefully shutdown all workers and close connections
460
+ */
461
+ onProviderDestroy(): Promise<void>;
462
+ /**
463
+ * Get a queue by name
464
+ */
465
+ getQueue(name: string): Queue$1 | undefined;
466
+ /**
467
+ * Get all registered queues
468
+ */
469
+ getAllQueues(): Queue$1[];
470
+ /**
471
+ * Check if the provider is initialized
472
+ */
473
+ isInitialized(): boolean;
474
+ /**
475
+ * Get configuration
476
+ */
477
+ getConfig(): QueueConfig;
478
+ private testConnection;
479
+ private discoverAndRegisterProcessors;
480
+ private registerProcessor;
481
+ private createQueue;
482
+ private attachWorkerEvents;
483
+ private handleEvent;
484
+ /**
485
+ * Create a processor instance using the DI Container to support @Autowired
486
+ */
487
+ private createProcessorInstance;
488
+ /**
489
+ * Register QueueProvider and QueueService in the DI container.
490
+ * Called early so processors can inject QueueService via @Autowired.
491
+ * Individual queues and workers are registered as they are created.
492
+ */
493
+ private registerInContainer;
494
+ /**
495
+ * Register a queue and its worker in the DI container.
496
+ * Called when a queue is created during processor registration.
497
+ */
498
+ private registerQueueInContainer;
499
+ /**
500
+ * Register a worker in the DI container.
501
+ * Called when a worker is created during processor registration.
502
+ */
503
+ private registerWorkerInContainer;
504
+ private delay;
505
+ }
506
+ /**
507
+ * Factory function to create a QueueProvider
508
+ */
509
+ declare function createQueueProvider(options?: QueueProviderOptions): QueueProvider;
510
+ /**
511
+ * Error thrown when queue initialization fails
512
+ */
513
+ declare class QueueInitializationError extends Error {
514
+ readonly cause?: Error | undefined;
515
+ constructor(message: string, cause?: Error | undefined);
516
+ }
517
+ /**
518
+ * Error thrown when a duplicate queue is detected
519
+ */
520
+ declare class DuplicateQueueError extends Error {
521
+ constructor(queueName: string);
522
+ }
523
+
524
+ /**
525
+ * QueueService - Injectable service for adding jobs to queues
526
+ */
527
+
528
+ /**
529
+ * Service for adding jobs to queues from anywhere in the application.
530
+ *
531
+ * @example
532
+ * ```typescript
533
+ * @Injectable()
534
+ * class NotificationService {
535
+ * @Autowired()
536
+ * private queueService!: QueueService;
537
+ *
538
+ * async sendNotification(userId: string, message: string) {
539
+ * await this.queueService.addJob('notifications', 'send', {
540
+ * userId,
541
+ * message,
542
+ * });
543
+ * }
544
+ * }
545
+ * ```
546
+ */
547
+ declare class QueueService {
548
+ private readonly provider;
549
+ constructor(provider: QueueProvider);
550
+ /**
551
+ * Add a job to a queue
552
+ *
553
+ * @param queueName - Name of the queue
554
+ * @param jobName - Name of the job (matches @Process decorator)
555
+ * @param data - Job payload data
556
+ * @param options - Optional job options
557
+ * @returns The created job
558
+ */
559
+ addJob<TData = unknown, TResult = unknown>(queueName: string, jobName: string, data: TData, options?: AddJobOptions): Promise<Job<TData, TResult>>;
560
+ /**
561
+ * Add multiple jobs to a queue in bulk
562
+ *
563
+ * @param queueName - Name of the queue
564
+ * @param jobs - Array of jobs to add
565
+ * @returns Array of created jobs
566
+ */
567
+ addJobs<TData = unknown, TResult = unknown>(queueName: string, jobs: Array<{
568
+ name: string;
569
+ data: TData;
570
+ options?: JobsOptions;
571
+ }>): Promise<Job<TData, TResult>[]>;
572
+ /**
573
+ * Add a delayed job
574
+ *
575
+ * @param queueName - Name of the queue
576
+ * @param jobName - Name of the job
577
+ * @param data - Job payload data
578
+ * @param delay - Delay in milliseconds
579
+ * @param options - Optional job options
580
+ */
581
+ addDelayedJob<TData = unknown, TResult = unknown>(queueName: string, jobName: string, data: TData, delay: number, options?: JobsOptions): Promise<Job<TData, TResult>>;
582
+ /**
583
+ * Add a repeatable job (scheduled)
584
+ *
585
+ * @param queueName - Name of the queue
586
+ * @param jobName - Name of the job
587
+ * @param data - Job payload data
588
+ * @param repeat - Repeat options (cron pattern, interval, etc.)
589
+ * @param options - Optional schedule options
590
+ */
591
+ addRepeatableJob<TData = unknown, TResult = unknown>(queueName: string, jobName: string, data: TData, repeat: RepeatOptions, options?: ScheduleOptions): Promise<Job<TData, TResult>>;
592
+ /**
593
+ * Remove a repeatable job
594
+ *
595
+ * @param queueName - Name of the queue
596
+ * @param jobName - Name of the job
597
+ * @param repeat - The repeat options used when creating the job
598
+ */
599
+ removeRepeatableJob(queueName: string, jobName: string, repeat: RepeatOptions): Promise<boolean>;
600
+ /**
601
+ * Get a job by ID
602
+ *
603
+ * @param queueName - Name of the queue
604
+ * @param jobId - Job ID
605
+ */
606
+ getJob<TData = unknown, TResult = unknown>(queueName: string, jobId: string): Promise<Job<TData, TResult> | undefined>;
607
+ /**
608
+ * Get queue statistics
609
+ *
610
+ * @param queueName - Name of the queue
611
+ */
612
+ getQueueStats(queueName: string): Promise<{
613
+ waiting: number;
614
+ active: number;
615
+ completed: number;
616
+ failed: number;
617
+ delayed: number;
618
+ paused: number;
619
+ }>;
620
+ /**
621
+ * Pause a queue
622
+ */
623
+ pauseQueue(queueName: string): Promise<void>;
624
+ /**
625
+ * Resume a queue
626
+ */
627
+ resumeQueue(queueName: string): Promise<void>;
628
+ /**
629
+ * Clear all jobs from a queue
630
+ *
631
+ * @param queueName - Name of the queue
632
+ * @param status - Which jobs to clear (default: all)
633
+ */
634
+ clearQueue(queueName: string, status?: 'completed' | 'failed' | 'delayed' | 'wait' | 'active'): Promise<void>;
635
+ /**
636
+ * Get all queue names
637
+ */
638
+ getQueueNames(): string[];
639
+ private getQueueOrThrow;
640
+ }
641
+ /**
642
+ * Error thrown when a queue is not found
643
+ */
644
+ declare class QueueNotFoundError extends Error {
645
+ constructor(queueName: string);
646
+ }
647
+ /**
648
+ * Error thrown when job validation fails
649
+ */
650
+ declare class JobValidationError extends Error {
651
+ readonly errors: unknown[];
652
+ constructor(message: string, errors: unknown[]);
653
+ }
654
+
655
+ /**
656
+ * Queue events integration with Rikta's EventBus
657
+ */
658
+ /** Event names for queue events */
659
+ type QueueEventName = 'job:added' | 'job:completed' | 'job:failed' | 'job:progress' | 'job:stalled' | 'job:delayed' | 'job:removed' | 'worker:ready' | 'worker:closed' | 'worker:error';
660
+ /** Event bus event names with prefix */
661
+ declare const QUEUE_EVENTS: {
662
+ readonly JOB_ADDED: "queue:job:added";
663
+ readonly JOB_COMPLETED: "queue:job:completed";
664
+ readonly JOB_FAILED: "queue:job:failed";
665
+ readonly JOB_PROGRESS: "queue:job:progress";
666
+ readonly JOB_STALLED: "queue:job:stalled";
667
+ readonly JOB_DELAYED: "queue:job:delayed";
668
+ readonly JOB_REMOVED: "queue:job:removed";
669
+ readonly WORKER_READY: "queue:worker:ready";
670
+ readonly WORKER_CLOSED: "queue:worker:closed";
671
+ readonly WORKER_ERROR: "queue:worker:error";
672
+ };
673
+ /**
674
+ * Map internal event names to EventBus event names
675
+ */
676
+ declare function getEventBusEventName(event: QueueEventName): string;
677
+ /**
678
+ * Publish a queue event to the EventBus
679
+ *
680
+ * @param eventBus - Rikta's EventBus instance
681
+ * @param event - The event name
682
+ * @param queueName - The queue name
683
+ * @param args - Event arguments (job, result, error, etc.)
684
+ */
685
+ declare function publishQueueEvent(eventBus: unknown, event: QueueEventName, queueName: string, ...args: unknown[]): Promise<void>;
686
+
687
+ /**
688
+ * Bull Board integration for queue monitoring
689
+ *
690
+ * This module provides optional Bull Board dashboard integration.
691
+ * Bull Board packages are NOT included as dependencies - install them separately:
692
+ *
693
+ * npm install @bull-board/api @bull-board/fastify
694
+ *
695
+ * @example
696
+ * ```typescript
697
+ * import { registerBullBoard } from '@riktajs/queue';
698
+ *
699
+ * // In your Rikta bootstrap:
700
+ * const app = await Rikta.create();
701
+ *
702
+ * // After queue provider is initialized:
703
+ * await registerBullBoard(app.server, {
704
+ * queues: queueProvider.getAllQueues(),
705
+ * path: '/admin/queues',
706
+ * auth: async (req) => {
707
+ * // Your auth logic here
708
+ * return req.headers.authorization === 'Bearer secret';
709
+ * },
710
+ * });
711
+ * ```
712
+ */
713
+
714
+ /** Options for Bull Board registration */
715
+ interface BullBoardOptions {
716
+ /** Queues to display in the dashboard */
717
+ queues: Queue$1[];
718
+ /** Base path for the dashboard (default: '/admin/queues') */
719
+ path?: string;
720
+ /** Authentication function - return true to allow access */
721
+ auth?: (request: FastifyRequest) => boolean | Promise<boolean>;
722
+ /** Whether to use read-only mode */
723
+ readOnly?: boolean;
724
+ }
725
+ /** Result of Bull Board registration */
726
+ interface BullBoardResult {
727
+ /** The path where the dashboard is mounted */
728
+ path: string;
729
+ /** Function to add more queues dynamically */
730
+ addQueue: (queue: Queue$1) => void;
731
+ /** Function to remove a queue from the dashboard */
732
+ removeQueue: (queueName: string) => void;
733
+ }
734
+ /**
735
+ * Register Bull Board dashboard with Fastify
736
+ *
737
+ * @param app - Fastify instance
738
+ * @param options - Dashboard configuration
739
+ * @returns Bull Board control object
740
+ *
741
+ * @throws BullBoardNotInstalledError if @bull-board packages are not installed
742
+ *
743
+ * @example
744
+ * ```typescript
745
+ * const board = await registerBullBoard(app.server, {
746
+ * queues: queueProvider.getAllQueues(),
747
+ * path: '/admin/queues',
748
+ * auth: (req) => checkAdminAuth(req),
749
+ * });
750
+ *
751
+ * // Add more queues later
752
+ * board.addQueue(newQueue);
753
+ * ```
754
+ */
755
+ declare function registerBullBoard(app: FastifyInstance, options: BullBoardOptions): Promise<BullBoardResult>;
756
+ /**
757
+ * Error thrown when Bull Board packages are not installed
758
+ */
759
+ declare class BullBoardNotInstalledError extends Error {
760
+ constructor();
761
+ }
762
+
763
+ /**
764
+ * Redis connection utilities
765
+ */
766
+
767
+ /**
768
+ * Create a Redis client based on configuration
769
+ * @param config - Redis connection options
770
+ */
771
+ declare function createRedisClient(config: RedisConnectionOptions): Redis | Cluster;
772
+ /**
773
+ * Error thrown when Redis connection fails
774
+ */
775
+ declare class QueueConnectionError extends Error {
776
+ readonly host?: string | undefined;
777
+ readonly port?: number | undefined;
778
+ readonly cause?: Error | undefined;
779
+ constructor(message: string, host?: string | undefined, port?: number | undefined, cause?: Error | undefined);
780
+ }
781
+ /**
782
+ * Manages a shared Redis connection for all queues
783
+ */
784
+ declare class RedisConnectionManager {
785
+ private client;
786
+ private config;
787
+ /**
788
+ * Initialize the connection manager with configuration
789
+ */
790
+ configure(config: RedisConnectionOptions): this;
791
+ /**
792
+ * Get or create the Redis client
793
+ */
794
+ getClient(): Redis | Cluster;
795
+ /**
796
+ * Check if client is connected
797
+ */
798
+ isConnected(): boolean;
799
+ /**
800
+ * Close the Redis connection
801
+ */
802
+ close(): Promise<void>;
803
+ /**
804
+ * Disconnect immediately (force)
805
+ */
806
+ disconnect(): void;
807
+ }
808
+
809
+ /**
810
+ * Zod validation utilities for job payloads
811
+ */
812
+
813
+ /**
814
+ * Creates a wrapper around a Zod schema for job validation
815
+ *
816
+ * @param schema - The Zod schema to use for validation
817
+ * @returns A wrapped schema with job-specific utilities
818
+ *
819
+ * @example
820
+ * ```typescript
821
+ * const EmailJobSchema = createJobSchema(z.object({
822
+ * to: z.string().email(),
823
+ * subject: z.string().min(1),
824
+ * body: z.string(),
825
+ * }));
826
+ *
827
+ * // Validate job data
828
+ * const result = EmailJobSchema.validate({ to: 'test@example.com', subject: 'Hello', body: 'World' });
829
+ * ```
830
+ */
831
+ declare function createJobSchema<T>(schema: ZodSchema<T>): JobSchema<T>;
832
+ /**
833
+ * Wrapper class for Zod schemas with job-specific utilities
834
+ */
835
+ declare class JobSchema<T> {
836
+ private readonly schema;
837
+ constructor(schema: ZodSchema<T>);
838
+ /**
839
+ * Get the underlying Zod schema
840
+ */
841
+ getSchema(): ZodSchema<T>;
842
+ /**
843
+ * Validate job data
844
+ * @throws JobValidationError if validation fails
845
+ */
846
+ validate(data: unknown): T;
847
+ /**
848
+ * Validate job data, returning undefined on failure
849
+ */
850
+ validateSafe(data: unknown): T | undefined;
851
+ /**
852
+ * Check if data is valid without throwing
853
+ */
854
+ isValid(data: unknown): data is T;
855
+ /**
856
+ * Get validation errors for data
857
+ */
858
+ getErrors(data: unknown): string[];
859
+ /**
860
+ * Parse and transform data with defaults
861
+ */
862
+ parse(data: unknown): T;
863
+ }
864
+ /**
865
+ * Error thrown when job schema validation fails
866
+ */
867
+ declare class JobSchemaValidationError extends Error {
868
+ readonly zodError: ZodError;
869
+ constructor(message: string, zodError: ZodError);
870
+ /**
871
+ * Get formatted validation errors
872
+ */
873
+ getErrors(): Array<{
874
+ path: string;
875
+ message: string;
876
+ }>;
877
+ }
878
+
879
+ /**
880
+ * Common job schemas for typical use cases
881
+ */
882
+ declare const CommonJobSchemas: {
883
+ /**
884
+ * Email job schema
885
+ */
886
+ email: z.ZodObject<{
887
+ to: z.ZodString;
888
+ cc: z.ZodOptional<z.ZodArray<z.ZodString>>;
889
+ bcc: z.ZodOptional<z.ZodArray<z.ZodString>>;
890
+ subject: z.ZodString;
891
+ body: z.ZodString;
892
+ html: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
893
+ attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
894
+ filename: z.ZodString;
895
+ content: z.ZodString;
896
+ contentType: z.ZodOptional<z.ZodString>;
897
+ }, z.core.$strip>>>;
898
+ }, z.core.$strip>;
899
+ /**
900
+ * Notification job schema
901
+ */
902
+ notification: z.ZodObject<{
903
+ userId: z.ZodString;
904
+ title: z.ZodString;
905
+ message: z.ZodString;
906
+ type: z.ZodDefault<z.ZodEnum<{
907
+ error: "error";
908
+ success: "success";
909
+ info: "info";
910
+ warning: "warning";
911
+ }>>;
912
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
913
+ }, z.core.$strip>;
914
+ /**
915
+ * File processing job schema
916
+ */
917
+ fileProcessing: z.ZodObject<{
918
+ fileId: z.ZodString;
919
+ filePath: z.ZodString;
920
+ operation: z.ZodEnum<{
921
+ resize: "resize";
922
+ compress: "compress";
923
+ convert: "convert";
924
+ thumbnail: "thumbnail";
925
+ }>;
926
+ options: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
927
+ }, z.core.$strip>;
928
+ /**
929
+ * Webhook job schema
930
+ */
931
+ webhook: z.ZodObject<{
932
+ url: z.ZodString;
933
+ method: z.ZodDefault<z.ZodEnum<{
934
+ DELETE: "DELETE";
935
+ GET: "GET";
936
+ PATCH: "PATCH";
937
+ POST: "POST";
938
+ PUT: "PUT";
939
+ }>>;
940
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
941
+ body: z.ZodOptional<z.ZodUnknown>;
942
+ timeout: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
943
+ }, z.core.$strip>;
944
+ };
945
+
946
+ export { type AddJobOptions, BullBoardNotInstalledError, type BullBoardOptions, type BullBoardResult, CommonJobSchemas, DuplicateQueueError, type EventHandlerMeta, type JobHandlerMeta, JobSchema, JobSchemaValidationError, JobValidationError, METADATA_KEY, OnJobComplete, OnJobFailed, OnJobProgress, OnJobStalled, OnWorkerError, OnWorkerReady, Process, Processor, ProcessorDecoratorError, type ProcessorOptions, QUEUE_CONFIG, QUEUE_EVENTS, QUEUE_PROVIDER, QUEUE_REDIS_CONNECTION, QUEUE_SERVICE, Queue, type QueueConfig, QueueConfigError, type QueueConfigInput, QueueConfigSchema, QueueConnectionError, QueueDecoratorError, type QueueDecoratorOptions, type QueueEventName, type QueueEventPayload, QueueInitializationError, QueueNotFoundError, QueueProvider, type QueueProviderOptions, QueueService, RedisConnectionManager, type RedisConnectionOptions, type ScheduleOptions, createJobSchema, createQueueProvider, createRedisClient, getEventBusEventName, getEventHandlers, getEventHandlersFor, getJobHandlers, getProcessorOptions, getQueueOptions, getQueueToken, getWorkerToken, isJobHandler, isProcessor, isQueue, loadQueueConfig, publishQueueEvent, registerBullBoard };