-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.ts
More file actions
527 lines (450 loc) · 12.1 KB
/
main.ts
File metadata and controls
527 lines (450 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
import type { BackoffStrategy as BackoffStrategyClass } from '../strategies/backoff_strategy.js'
import type { Adapter } from '../contracts/adapter.js'
import type { AcquiredJob } from '../contracts/adapter.js'
import type { Logger } from '../logger.js'
import { Job } from '../job.js'
export type { Logger }
/**
* Duration can be specified as milliseconds (number) or as a human-readable string.
*
* Supported string formats: '1s', '5m', '2h', '1d', etc.
*
* @example
* ```typescript
* const timeout: Duration = '30s' // 30 seconds
* const delay: Duration = 5000 // 5000 milliseconds
* const interval: Duration = '5m' // 5 minutes
* ```
*/
export type Duration = number | string
/**
* Retention policy for completed/failed jobs.
*
* - `true` (default): Remove job immediately
* - `false`: Keep job in history indefinitely
* - `{ age?, count? }`: Keep with pruning by age and/or count
*/
export type JobRetention = boolean | { age?: Duration; count?: number }
/**
* Possible statuses for a job in the queue.
*/
export type JobStatus = 'pending' | 'active' | 'delayed' | 'completed' | 'failed'
/**
* Result returned when dispatching a job.
*
* @example
* ```typescript
* const { jobId } = await SendEmailJob.dispatch(payload)
* console.log(`Dispatched job: ${jobId}`)
* ```
*/
export interface DispatchResult {
/** Unique identifier for this specific job instance */
jobId: string
}
/**
* Result returned when dispatching multiple jobs at once.
*
* @example
* ```typescript
* const { jobIds } = await SendEmailJob.dispatchMany(payloads)
* console.log(`Dispatched ${jobIds.length} jobs`)
* ```
*/
export interface DispatchManyResult {
/** Unique identifiers for all dispatched job instances */
jobIds: string[]
}
/**
* Internal representation of a job in the queue.
*
* This is used by adapters to store and retrieve job data.
* Not typically used directly by application code.
*/
export interface JobData {
/**
* Unique identifier for this job.
*/
id: string
/**
* Job class name.
*/
name: string
/**
* Serialized job payload.
*/
payload: any
/**
* Number of execution attempts so far.
*/
attempts: number
/**
* Job priority (lower = higher priority).
*
* @default 0
*/
priority?: number
/**
* When to retry this job next (for failed jobs).
*/
nextRetryAt?: Date
/**
* Number of times this job was recovered from stalled state.
*/
stalledCount?: number
/**
* Optional group identifier for organizing related jobs.
*
* Jobs with the same groupId can be filtered and displayed together
* in monitoring UIs. Useful for batch operations like newsletters
* or bulk exports.
*
* @example
* ```typescript
* await SendEmailJob.dispatch({ to: 'user@example.com' })
* .group('newsletter-jan-2025')
* .run()
* ```
*/
groupId?: string
/**
* Serialized trace context for distributed tracing.
* Injected by OTel plugin at dispatch time.
*/
traceContext?: Record<string, string>
}
/**
* Record of a job's current state, including history for completed/failed jobs.
*/
export interface JobRecord {
/** Current status of the job */
status: JobStatus
/** Original job data */
data: JobData
/** Timestamp when the job finished (for completed/failed jobs) */
finishedAt?: number
/** Error message (for failed jobs) */
error?: string
/** Serialized job output */
output?: any
}
/**
* Static options for a Job class.
*
* Define these as a static property on your Job class to configure
* default behavior for all instances.
*
* @example
* ```typescript
* class SendEmailJob extends Job<EmailPayload> {
* static options: JobOptions = {
* name: 'SendEmailJob',
* queue: 'emails',
* maxRetries: 3,
* timeout: '30s',
* }
* }
* ```
*/
export interface JobOptions {
/**
* Unique name for this job class.
*
* Used to identify the job when dispatching and processing.
*
* @default constructor.name
*/
name?: string
/**
* Queue name for this job.
*
* @default 'default'
*/
queue?: string
/**
* Adapter name or factory to use for this job.
*/
adapter?: string | (() => Adapter)
/**
* Maximum retry attempts before permanent failure.
*
* @default 3
*/
maxRetries?: number
/**
* Job priority (lower = higher priority).
*
* @default 0
*/
priority?: number
/**
* Retry configuration (backoff strategy, delays, etc.).
*/
retry?: RetryConfig
/**
* Maximum execution time before timeout.
*
* @default undefined (no timeout)
*/
timeout?: Duration
/**
* Whether to mark job as failed on timeout.
*
* @default true
*/
failOnTimeout?: boolean
removeOnComplete?: JobRetention
removeOnFail?: JobRetention
}
/**
* Context information available to a job during execution.
*
* Provides metadata about the current job execution, including
* retry information, queue details, and timing.
*
* @example
* ```typescript
* class MyJob extends Job<Payload> {
* async execute() {
* console.log(`Attempt ${this.context.attempt} of job ${this.context.jobId}`)
* console.log(`Running on queue: ${this.context.queue}`)
* }
* }
* ```
*/
export interface JobContext {
/** Unique identifier for this job */
jobId: string
/** Job class name */
name: string
/** Current attempt number (1-based: first attempt = 1) */
attempt: number
/** Queue name this job is being processed from */
queue: string
/** Job priority (lower number = higher priority) */
priority: number
/** When this job was acquired by the worker for processing */
acquiredAt: Date
/** Number of times this job has been recovered from stalled state */
stalledCount: number
}
/**
* Type representing a Job class constructor.
*
* The constructor accepts any arguments for dependency injection.
* Payload and context are provided separately via `$hydrate()`.
*/
export type JobClass<T extends Job = Job> = (new (...args: unknown[]) => T) & {
options?: JobOptions
}
/**
* Factory function for custom job instantiation.
*
* Use this to integrate with IoC containers for dependency injection.
* The factory receives only the job class and should return an instance
* with all dependencies injected. The worker will call `$hydrate()` separately
* to provide payload, context, and signal.
*
* @param JobClass - The job class to instantiate
* @returns The job instance, or a Promise resolving to the instance
*
* @example
* ```typescript
* // With AdonisJS IoC container
* await QueueManager.init({
* default: 'redis',
* adapters: { redis: redis() },
* jobFactory: async (JobClass) => {
* return app.container.make(JobClass)
* }
* })
* ```
*/
export type JobFactory = (JobClass: JobClass) => Job | Promise<Job>
export interface RetryConfig {
maxRetries?: number
backoff?: () => BackoffStrategyClass
}
export type BackoffStrategy = 'exponential' | 'linear' | 'fixed'
export interface BackoffConfig {
strategy: BackoffStrategy
baseDelay: Duration
maxDelay?: Duration
multiplier?: number
jitter?: boolean
}
export interface QueueConfig {
adapter?: string
retry?: RetryConfig
defaultJobOptions?: JobOptions
}
export interface WorkerConfig {
/**
* Maximum number of jobs to process concurrently.
* @default 1
*/
concurrency?: number
/**
* Delay between queue polls when idle (no jobs available).
* @default '2s'
*/
idleDelay?: Duration
/**
* Maximum duration a job can run before being timed out.
* Can be overridden per job via JobOptions.timeout.
* @default undefined (no timeout)
*/
timeout?: Duration
/**
* Duration after which an active job is considered stalled.
* A stalled job is one that was acquired but the worker stopped
* responding (e.g., due to a crash).
* @default '30s'
*/
stalledThreshold?: Duration
/**
* How often to check for stalled jobs.
* @default '30s'
*/
stalledInterval?: Duration
/**
* Maximum number of times a job can be recovered from stalled state
* before being marked as failed permanently.
* @default 1
*/
maxStalledCount?: number
/**
* Whether to automatically stop the worker on SIGINT/SIGTERM signals.
* When enabled, the worker will wait for running jobs to complete
* before stopping.
* @default true
*/
gracefulShutdown?: boolean
/**
* Callback invoked when a shutdown signal is received.
* Called before the worker starts stopping.
*/
onShutdownSignal?: () => void | Promise<void>
}
export type WorkerCycle =
| { type: 'started'; queue: string; job: JobData }
| { type: 'completed'; queue: string; job: JobData }
| { type: 'idle'; suggestedDelay: Duration }
| { type: 'error'; error: Error; suggestedDelay: Duration }
export type AdapterFactory<T extends Adapter = Adapter> = () => T
/**
* Status of a schedule.
*/
export type ScheduleStatus = 'active' | 'paused'
/**
* Configuration for creating a schedule.
* Used by ScheduleBuilder to collect schedule options before creation.
*/
export interface ScheduleConfig {
/** Optional ID for the schedule (UUID if not set). Used for upsert. */
id?: string
/** Job class name */
name: string
/** Job payload */
payload: any
/** Cron expression (mutually exclusive with everyMs) */
cronExpression?: string
/** Interval in milliseconds (mutually exclusive with cronExpression) */
everyMs?: number
/** IANA timezone for cron evaluation */
timezone: string
/** Start boundary - no jobs dispatched before this */
from?: Date
/** End boundary - no jobs dispatched after this */
to?: Date
/** Maximum number of runs (null = unlimited) */
limit?: number
}
/**
* Persisted schedule data.
* Represents a schedule stored in the adapter.
*/
export interface ScheduleData {
/** Unique identifier */
id: string
/** Job class name */
name: string
/** Job payload */
payload: any
/** Cron expression (null if using interval) */
cronExpression: string | null
/** Interval in milliseconds (null if using cron) */
everyMs: number | null
/** IANA timezone */
timezone: string
/** Start boundary - no jobs dispatched before this */
from: Date | null
/** End boundary - no jobs dispatched after this */
to: Date | null
/** Maximum number of runs */
limit: number | null
/** Number of times this schedule has run */
runCount: number
/** Next scheduled run time */
nextRunAt: Date | null
/** Last run time */
lastRunAt: Date | null
/** Current status */
status: ScheduleStatus
/** When the schedule was created */
createdAt: Date
}
/**
* Result returned when creating a schedule.
*/
export interface ScheduleResult {
/** Unique identifier for the schedule */
scheduleId: string
}
/**
* Options for listing schedules.
*/
export interface ScheduleListOptions {
/** Filter by status */
status?: ScheduleStatus
}
export interface QueueManagerConfig {
default: string
adapters: Record<string, AdapterFactory>
retry?: RetryConfig
defaultJobOptions?: JobOptions
queues?: Record<string, QueueConfig>
worker?: WorkerConfig
locations?: string[]
logger?: Logger
/**
* Custom factory function for job instantiation.
*
* Use this to integrate with IoC containers for dependency injection.
* When provided, this factory is called instead of `new JobClass()`.
* The worker will call `$hydrate()` on the returned instance to provide
* payload, context, and signal.
*
* @example
* ```typescript
* await QueueManager.init({
* default: 'redis',
* adapters: { redis: redis() },
* jobFactory: async (JobClass) => {
* return app.container.make(JobClass)
* }
* })
* ```
*/
jobFactory?: JobFactory
/**
* Wraps internal adapter operations (Redis, Knex calls) to suppress
* or customize instrumentation. Used by OTel to suppress child spans.
*/
internalOperationWrapper?: <T>(fn: () => Promise<T>) => Promise<T>
/**
* Wraps job execution to inject tracing context or custom behavior.
* Called around `runtime.execute()` for each job attempt.
*/
executionWrapper?: <T>(fn: () => Promise<T>, job: AcquiredJob, queue: string) => Promise<T>
}