-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjob_dispatcher.ts
More file actions
276 lines (246 loc) · 7.34 KB
/
job_dispatcher.ts
File metadata and controls
276 lines (246 loc) · 7.34 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
import debug from './debug.js'
import { randomUUID } from 'node:crypto'
import { QueueManager } from './queue_manager.js'
import { dispatchChannel } from './tracing_channels.js'
import type { Adapter } from './contracts/adapter.js'
import type { DispatchResult, Duration } from './types/main.js'
import type { JobDispatchMessage } from './types/tracing_channels.js'
import { setTimeout } from 'node:timers/promises'
import { parse } from './utils.js'
import { E_JOB_EXECUTION_FAILED, E_JOB_EXECUTION_NOT_FOUND } from './exceptions.ts'
/**
* Fluent builder for dispatching jobs to the queue.
*
* Provides a chainable API for configuring job options before dispatch.
* Usually created via `Job.dispatch()` rather than directly.
*
* ```
* Job.dispatch(payload)
* .toQueue('emails') // optional: target queue
* .priority(1) // optional: 1-10, lower = higher priority
* .in('5m') // optional: delay before processing
* .with('redis') // optional: specific adapter
* .run() // dispatch the job
* ```
*
* @typeParam T - The payload type for this job
*
* @example
* ```typescript
* // Simple dispatch (auto-runs via thenable)
* await SendEmailJob.dispatch({ to: 'user@example.com', subject: 'Hello' })
*
* // With options
* const jobId = await SendEmailJob.dispatch({ to: 'user@example.com' })
* .toQueue('high-priority')
* .priority(1)
* .run()
*
* // Delayed job
* await ReminderJob.dispatch({ userId: 123 }).in('24h')
* ```
*/
export class JobDispatcher<TPayload, TOutput> {
readonly #name: string
readonly #payload: TPayload
#queue: string = 'default'
#adapter?: string | (() => Adapter)
#delay?: Duration
#priority?: number
#groupId?: string
/**
* Create a new job dispatcher.
*
* @param name - The job class name (used to locate the class at runtime)
* @param payload - The data to pass to the job
*/
constructor(name: string, payload: TPayload) {
this.#name = name
this.#payload = payload
}
/**
* Set the target queue for this job.
*
* @param queue - Queue name (default: 'default')
* @returns This dispatcher for chaining
*
* @example
* ```typescript
* await SendEmailJob.dispatch(payload).toQueue('emails')
* ```
*/
toQueue(queue: string): this {
this.#queue = queue
return this
}
/**
* Delay the job execution.
*
* The job will be stored in a delayed state and moved to pending
* after the delay expires.
*
* @param delay - Delay as milliseconds or duration string ('5s', '1h', '7d')
* @returns This dispatcher for chaining
*
* @example
* ```typescript
* // Send reminder in 24 hours
* await ReminderJob.dispatch(payload).in('24h')
*
* // Process in 5 minutes
* await CleanupJob.dispatch(payload).in('5m')
* ```
*/
in(delay: Duration): this {
this.#delay = delay
return this
}
/**
* Set the job priority.
*
* Lower numbers = higher priority. Jobs with lower priority values
* are processed before jobs with higher values.
*
* @param priority - Priority level (1-10, default: 5)
* @returns This dispatcher for chaining
*
* @example
* ```typescript
* // High priority job
* await UrgentJob.dispatch(payload).priority(1)
*
* // Low priority job
* await BackgroundJob.dispatch(payload).priority(10)
* ```
*/
priority(priority: number): this {
this.#priority = priority
return this
}
/**
* Assign this job to a group.
*
* Jobs with the same groupId can be filtered and displayed together
* in monitoring UIs. Useful for batch operations like newsletters
* or bulk exports.
*
* @param groupId - Group identifier
* @returns This dispatcher for chaining
*
* @example
* ```typescript
* // Group newsletter jobs together
* await SendEmailJob.dispatch({ to: 'user@example.com' })
* .group('newsletter-jan-2025')
* .run()
* ```
*/
group(groupId: string): this {
this.#groupId = groupId
return this
}
/**
* Use a specific adapter for this job.
*
* @param adapter - Adapter name or factory function
* @returns This dispatcher for chaining
*
* @example
* ```typescript
* // Use named adapter
* await Job.dispatch(payload).with('redis')
*
* // Use custom adapter instance
* await Job.dispatch(payload).with(() => new CustomAdapter())
* ```
*/
with(adapter: string | (() => Adapter)) {
this.#adapter = adapter
return this
}
/**
* Dispatch the job to the queue.
*
* @returns A DispatchResult containing the jobId
*
* @example
* ```typescript
* const { jobId } = await SendEmailJob.dispatch(payload).run()
* console.log(`Dispatched job: ${jobId}`)
* ```
*/
async run(): Promise<DispatchResult> {
const id = randomUUID()
debug('dispatching job %s with id %s using payload %s', this.#name, id, this.#payload)
const adapter = this.#getAdapterInstance()
const wrapInternal = QueueManager.getInternalOperationWrapper()
const parsedDelay = this.#delay ? parse(this.#delay) : undefined
const jobData = {
id,
name: this.#name,
payload: this.#payload,
attempts: 0,
priority: this.#priority,
groupId: this.#groupId,
}
const message: JobDispatchMessage = { jobs: [jobData], queue: this.#queue, delay: parsedDelay }
await dispatchChannel.tracePromise(async () => {
if (parsedDelay !== undefined) {
await wrapInternal(() => adapter.pushLaterOn(this.#queue, jobData, parsedDelay))
} else {
await wrapInternal(() => adapter.pushOn(this.#queue, jobData))
}
}, message)
return { jobId: id }
}
/**
* Dispatch the job to the queue and
* await for job to complete or fail.
*
* @param pollingInterval - Interval between each check
* @param signal - Optional signal to abort waiting
* @returns The job output
*/
async wait(pollingInterval: Duration = 2000, signal?: AbortSignal): Promise<TOutput> {
const adapter = this.#getAdapterInstance()
const dispatchResult = await this.run()
while (true) {
signal?.throwIfAborted()
await setTimeout(parse(pollingInterval))
const job = await adapter.getJob(dispatchResult.jobId, this.#queue)
if (!job) {
throw new E_JOB_EXECUTION_NOT_FOUND([dispatchResult.jobId])
}
if (job.status === 'completed') {
return job.output
}
if (job.status === 'failed') {
throw new E_JOB_EXECUTION_FAILED([dispatchResult.jobId], { cause: job.error })
}
}
}
/**
* Thenable implementation for auto-dispatch when awaited.
*
* Allows `await Job.dispatch(payload)` without explicit `.run()`.
*
* @param onFulfilled - Success callback
* @param onRejected - Error callback
* @returns Promise resolving to the DispatchResult
*/
then<TResult1 = DispatchResult, TResult2 = never>(
onFulfilled?: ((value: DispatchResult) => TResult1 | PromiseLike<TResult1>) | null,
onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null
): Promise<TResult1 | TResult2> {
return this.run().then(onFulfilled, onRejected)
}
#getAdapterInstance(): Adapter {
if (!this.#adapter) {
return QueueManager.use()
}
if (typeof this.#adapter === 'string') {
return QueueManager.use(this.#adapter)
}
return this.#adapter()
}
}