{{ message }}
Repository navigation
Expand file tree
/
Copy pathjob_runtime.ts
More file actions
389 lines (339 loc) · 11.8 KB
/
Copy pathjob_runtime.ts
File metadata and controls
389 lines (339 loc) · 11.8 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
import * as errors from './exceptions.js'
import { DEFAULT_PRIORITY, UNKNOWN_JOB_RETRY_DELAY } from './constants.js'
import { executeChannel } from './tracing_channels.js'
import type { Job } from './job.js'
import type { AcquiredJob } from './contracts/adapter.js'
import type { QueueConfigResolver, ResolvedJobOptions } from './queue_config_resolver.js'
import type {
JobClass,
JobContext,
JobFactory,
JobOptions,
JobRetention,
QueueManagerConfig,
RetryConfig,
} from './types/main.js'
import type { JobExecuteMessage } from './types/tracing_channels.js'
import { parseTimeout } from './utils.js'
type PermanentFailureReason = 'timeout' | 'no-retries' | 'max-attempts' | 'stalled'
/**
* A timed out handler that had not settled when the timeout fired. The
* attempt is over, but the handler keeps running until it returns: callers
* wait for this promise before they run anything in its place.
*/
type TimedOutExecution = { timedOutExecution?: Promise<void> }
export type JobExecutionOutcome =
| { type: 'completed'; removeOnComplete?: JobRetention }
| ({
type: 'retry'
retryAt?: Date
/** Set when the job goes back to the queue because no class has its name. */
jobNotFound?: true
} & TimedOutExecution)
| ({
type: 'failed'
reason: PermanentFailureReason
error: Error
removeOnFail?: JobRetention
failedHookError?: Error
} & TimedOutExecution)
| {
type: 'initialization-failed'
error: Error
removeOnFail?: JobRetention
}
export interface JobExecuteOptions {
/**
* A job whose name has no registered class goes back to the queue, to run
* again 30 seconds later, while it has fewer attempts than this. During a
* rolling deploy, an old worker can take a job dispatched by new code: a
* worker that knows it runs it later. Defaults to 0: the job fails.
*/
unknownJobRetries?: number
}
type JobExecutionRuntimeDependencies = {
/** Returns undefined when no class is registered under the name. */
resolveJob: (jobName: string) => JobClass | undefined | Promise<JobClass | undefined>
configResolver: QueueConfigResolver
jobFactory?: JobFactory
executionWrapper?: NonNullable<QueueManagerConfig['executionWrapper']>
}
type FailureDecision =
| { type: 'retry'; retryAt?: Date }
| {
type: 'failed'
reason: PermanentFailureReason
hookError: Error
}
/**
* No class is registered under the job name. Only the runtime throws it, so
* it cannot be confused with an E_JOB_NOT_FOUND from the job's own code.
*/
class JobNotRegistered extends errors.E_JOB_NOT_FOUND {}
const noopExecutionWrapper: NonNullable<QueueManagerConfig['executionWrapper']> = async (run) =>
run()
/**
* Execute one in-process Job attempt through a single lifecycle interface.
*
* Resolution, instantiation, context construction, hydration, timeout,
* tracing, failure hooks, and retry classification live behind this seam.
* Callers retain only their adapter-specific scheduling and persistence work.
*/
export class JobExecutionRuntime {
readonly #resolveJob: JobExecutionRuntimeDependencies['resolveJob']
readonly #configResolver: QueueConfigResolver
readonly #jobFactory?: JobFactory
readonly #executionWrapper: NonNullable<QueueManagerConfig['executionWrapper']>
constructor({
resolveJob,
configResolver,
jobFactory,
executionWrapper,
}: JobExecutionRuntimeDependencies) {
this.#resolveJob = resolveJob
this.#configResolver = configResolver
this.#jobFactory = jobFactory
this.#executionWrapper = executionWrapper ?? noopExecutionWrapper
}
/**
* Execute a single acquired Job attempt and return the adapter-facing outcome.
*/
execute(
job: AcquiredJob,
queue: string,
options: JobExecuteOptions = {}
): Promise<JobExecutionOutcome> {
const executeMessage: JobExecuteMessage = { job, queue }
const startTime = performance.now()
const run = () =>
executeChannel.tracePromise(async () => {
try {
return await this.#executeAttempt(job, queue, executeMessage, options)
} finally {
executeMessage.duration = Number((performance.now() - startTime).toFixed(2))
}
}, executeMessage)
return this.#executionWrapper(run, job, queue)
}
/**
* Fail a Job that stalled more than `maxStalledCount` times, without running it.
*
* The `failed()` hook receives `E_JOB_STALLED`, and the outcome carries the
* Job's own retention so the caller finalizes it like any permanent failure.
* The attempt is not traced, since the Job does not execute.
*/
async failStalled(
job: AcquiredJob,
queue: string,
maxStalledCount: number
): Promise<JobExecutionOutcome> {
let instance: Job
let options: JobOptions
try {
;({ instance, options } = await this.#instantiate(job))
} catch (error) {
return {
type: 'initialization-failed',
error: error as Error,
removeOnFail: this.#configResolver.resolveJobOptions(queue).removeOnFail,
}
}
const error = new errors.E_JOB_STALLED([job.name, maxStalledCount])
const retention = this.#configResolver.resolveJobOptions(queue, options)
instance.$hydrate(job.payload, this.#createContext(job, queue))
let failedHookError: Error | undefined
try {
await instance.failed?.(error)
} catch (hookError) {
failedHookError = hookError as Error
}
return {
type: 'failed',
reason: 'stalled',
error,
removeOnFail: retention.removeOnFail,
failedHookError,
}
}
async #instantiate(job: AcquiredJob): Promise<{ instance: Job; options: JobOptions }> {
const JobClass = await this.#resolveJob(job.name)
if (!JobClass) throw new JobNotRegistered([job.name])
const instance = this.#jobFactory ? await this.#jobFactory(JobClass) : new JobClass()
return { instance, options: JobClass.options || {} }
}
async #executeAttempt(
job: AcquiredJob,
queue: string,
executeMessage: JobExecuteMessage,
executeOptions: JobExecuteOptions
): Promise<JobExecutionOutcome> {
let instance: Job
let options: JobOptions | undefined
let timeout: number | undefined
try {
;({ instance, options } = await this.#instantiate(job))
// An invalid Job.options.timeout fails the Job without retrying it.
// Registration rejects one, but a job registered with hotReload is
// imported again for every execution, after that check.
timeout = parseTimeout(this.#configResolver.resolveJobOptions(queue, options).timeout)
} catch (error) {
const initializationError = error as Error
executeMessage.error = initializationError
// Only a name with no class goes back to the queue: an E_JOB_NOT_FOUND
// thrown while loading or constructing a registered job, for another
// name, fails it like any other initialization error.
if (
error instanceof JobNotRegistered &&
job.attempts < (executeOptions.unknownJobRetries ?? 0)
) {
const retryAt = new Date(Date.now() + UNKNOWN_JOB_RETRY_DELAY)
executeMessage.status = 'retrying'
executeMessage.nextRetryAt = retryAt
return { type: 'retry', retryAt, jobNotFound: true }
}
executeMessage.status = 'failed'
return {
type: 'initialization-failed',
error: initializationError,
removeOnFail: this.#configResolver.resolveJobOptions(queue, options).removeOnFail,
}
}
const context = this.#createContext(job, queue)
const resolvedOptions = this.#configResolver.resolveJobOptions(queue, options)
const retryConfig = this.#configResolver.resolveRetryConfig(queue, options)
const timedOut: TimedOutExecution = {}
try {
await this.#executeJob(instance, job.payload, context, timeout, timedOut)
executeMessage.status = 'completed'
return { type: 'completed', removeOnComplete: resolvedOptions.removeOnComplete }
} catch (error) {
const executionError = error as Error
const decision = this.#resolveFailure(
job.name,
resolvedOptions,
retryConfig,
executionError,
job.attempts
)
executeMessage.error = executionError
if (decision.type === 'retry') {
executeMessage.status = 'retrying'
executeMessage.nextRetryAt = decision.retryAt
return { ...decision, ...timedOut }
}
executeMessage.status = 'failed'
let failedHookError: Error | undefined
try {
await instance.failed?.(decision.hookError)
} catch (error) {
failedHookError = error as Error
}
return {
type: 'failed',
reason: decision.reason,
error: executionError,
removeOnFail: resolvedOptions.removeOnFail,
failedHookError,
...timedOut,
}
}
}
#createContext(job: AcquiredJob, queue: string): JobContext {
return {
jobId: job.id,
name: job.name,
attempt: job.attempts + 1,
queue,
priority: job.priority ?? DEFAULT_PRIORITY,
acquiredAt: new Date(job.acquiredAt),
stalledCount: job.stalledCount ?? 0,
...(job.scheduleId ? { scheduleId: job.scheduleId } : {}),
}
}
async #executeJob(
instance: Job,
payload: unknown,
context: JobContext,
timeout: number | undefined,
timedOut: TimedOutExecution
): Promise<void> {
if (timeout === undefined) {
instance.$hydrate(payload, context)
return instance.execute()
}
const signal = AbortSignal.timeout(timeout)
instance.$hydrate(payload, context, signal)
const { abortPromise, cleanupAbortListener } = this.#createTimeoutAbortRace(
signal,
instance.constructor.name,
timeout
)
// Unset when execute() throws synchronously: nothing keeps running then.
let execution: Promise<void> | undefined
try {
execution = instance.execute()
await Promise.race([execution, abortPromise])
} catch (error) {
// Cancellation is cooperative: a handler that has not settled yet keeps
// running, so the caller must keep its slot until it returns.
if (execution && error instanceof errors.E_JOB_TIMEOUT) {
timedOut.timedOutExecution = Promise.resolve(execution).then(
() => {},
() => {}
)
}
throw error
} finally {
cleanupAbortListener()
}
}
#resolveFailure(
jobName: string,
options: ResolvedJobOptions,
retryConfig: RetryConfig,
error: Error,
attempts: number
): FailureDecision {
if (error instanceof errors.E_JOB_TIMEOUT && options.failOnTimeout) {
return { type: 'failed', reason: 'timeout', hookError: error }
}
if (typeof retryConfig.maxRetries === 'undefined' || retryConfig.maxRetries <= 0) {
return { type: 'failed', reason: 'no-retries', hookError: error }
}
if (attempts >= retryConfig.maxRetries) {
return {
type: 'failed',
reason: 'max-attempts',
hookError: new errors.E_JOB_MAX_ATTEMPTS_REACHED([jobName], { cause: error }),
}
}
if (retryConfig.backoff) {
return {
type: 'retry',
retryAt: retryConfig.backoff().getNextRetryAt(attempts + 1),
}
}
return { type: 'retry' }
}
#createTimeoutAbortRace(signal: AbortSignal, runtimeJobName: string, timeout: number) {
let abortHandler: (() => void) | undefined
const abortPromise = new Promise<never>((_, reject) => {
abortHandler = () => {
reject(new errors.E_JOB_TIMEOUT([runtimeJobName, timeout]))
}
if (signal.aborted) {
abortHandler()
return
}
signal.addEventListener('abort', abortHandler, { once: true })
})
return {
abortPromise,
cleanupAbortListener: () => {
if (abortHandler) {
signal.removeEventListener('abort', abortHandler)
}
},
}
}
}
You can’t perform that action at this time.
