-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathgetRunTaskFunction.ts
More file actions
211 lines (190 loc) · 6.13 KB
/
getRunTaskFunction.ts
File metadata and controls
211 lines (190 loc) · 6.13 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
import ObjectIdImport from 'bson-objectid'
import type { Job } from '../../../../index.js'
import type { PayloadRequest } from '../../../../types/index.js'
import type {
RetryConfig,
RunInlineTaskFunction,
RunTaskFunction,
RunTaskFunctions,
TaskConfig,
TaskHandler,
TaskHandlerResult,
TaskType,
} from '../../../config/types/taskTypes.js'
import type {
JobLog,
SingleTaskStatus,
WorkflowConfig,
WorkflowTypes,
} from '../../../config/types/workflowTypes.js'
import type { UpdateJobFunction } from './getUpdateJobFunction.js'
import { JobCancelledError, TaskError } from '../../../errors/index.js'
import { getCurrentDate } from '../../../utilities/getCurrentDate.js'
import { getTaskHandlerFromConfig } from './importHandlerPath.js'
const ObjectId = 'default' in ObjectIdImport ? ObjectIdImport.default : ObjectIdImport
export type TaskParent = {
taskID: string
taskSlug: string
}
export const getRunTaskFunction = <TIsInline extends boolean>(
job: Job,
workflowConfig: WorkflowConfig,
req: PayloadRequest,
isInline: TIsInline,
updateJob: UpdateJobFunction,
parent?: TaskParent,
): TIsInline extends true ? RunInlineTaskFunction : RunTaskFunctions => {
const jobConfig = req.payload.config.jobs
const runTask: <TTaskSlug extends string>(
taskSlug: TTaskSlug,
) => TTaskSlug extends 'inline' ? RunInlineTaskFunction : RunTaskFunction<TTaskSlug> = (
taskSlug,
) =>
(async (
taskID: Parameters<RunInlineTaskFunction>[0],
{
input,
retries,
// Only available for inline tasks:
task,
}: Parameters<RunInlineTaskFunction>[1] & Parameters<RunTaskFunction<string>>[1],
) => {
const executedAt = getCurrentDate()
let taskConfig: TaskConfig | undefined
if (!isInline) {
taskConfig = (jobConfig.tasks?.length &&
jobConfig.tasks.find((t) => t.slug === taskSlug)) as TaskConfig<string>
if (!taskConfig) {
throw new Error(`Task ${taskSlug} not found in workflow ${job.workflowSlug}`)
}
}
const retriesConfigFromPropsNormalized =
retries == undefined || retries == null
? {}
: typeof retries === 'number'
? { attempts: retries }
: retries
const retriesConfigFromTaskConfigNormalized = taskConfig
? typeof taskConfig.retries === 'number'
? { attempts: taskConfig.retries }
: taskConfig.retries
: {}
const finalRetriesConfig: RetryConfig = {
...retriesConfigFromTaskConfigNormalized,
...retriesConfigFromPropsNormalized, // Retry config from props takes precedence
}
const taskStatus: null | SingleTaskStatus<string> = job?.taskStatus?.[taskSlug]
? job.taskStatus[taskSlug][taskID]!
: null
// Handle restoration of task if it succeeded in a previous run
if (taskStatus && taskStatus.complete === true) {
let shouldRestore = true
if (finalRetriesConfig?.shouldRestore === false) {
shouldRestore = false
} else if (typeof finalRetriesConfig?.shouldRestore === 'function') {
shouldRestore = await finalRetriesConfig.shouldRestore({
input,
job,
req,
taskStatus,
})
}
if (shouldRestore) {
return taskStatus.output
}
}
const runner = isInline
? (task as TaskHandler<TaskType>)
: await getTaskHandlerFromConfig(taskConfig)
if (!runner || typeof runner !== 'function') {
throw new TaskError({
executedAt,
input,
job,
message: isInline
? `Inline task with ID ${taskID} does not have a valid handler.`
: `Task with slug ${taskSlug} in workflow ${job.workflowSlug} does not have a valid handler.`,
parent,
retriesConfig: finalRetriesConfig,
taskConfig,
taskID,
taskSlug,
taskStatus,
workflowConfig,
})
}
let output: TaskHandlerResult<string>['output']
try {
output = (
await runner({
inlineTask: getRunTaskFunction(job, workflowConfig, req, true, updateJob, {
taskID,
taskSlug,
}),
input,
job: job as unknown as Job<WorkflowTypes>,
req,
tasks: getRunTaskFunction(job, workflowConfig, req, false, updateJob, {
taskID,
taskSlug,
}),
})
)?.output
} catch (err: any) {
if (err instanceof JobCancelledError) {
// Re-throw JobCancelledError to be handled by the top-level error handler
throw err
}
throw new TaskError({
executedAt,
input: input!,
job,
message: err.message || 'Task handler threw an error',
output,
parent,
retriesConfig: finalRetriesConfig,
taskConfig,
taskID,
taskSlug,
taskStatus,
workflowConfig,
})
}
if (taskConfig?.onSuccess) {
await taskConfig.onSuccess({
input,
job,
req,
taskStatus,
})
}
const newLogItem: JobLog = {
id: new ObjectId().toHexString(),
completedAt: getCurrentDate().toISOString(),
executedAt: executedAt.toISOString(),
input,
output,
parent: jobConfig.addParentToTaskLog ? parent : undefined,
state: 'succeeded',
taskID,
taskSlug,
}
await updateJob({
log: {
$push: newLogItem,
} as any,
// Set to null to skip main row update on postgres. 2 => 1 db round trips
updatedAt: null as any,
})
return output
}) as any
if (isInline) {
return runTask('inline') as TIsInline extends true ? RunInlineTaskFunction : RunTaskFunctions
} else {
const tasks: RunTaskFunctions = {}
for (const task of jobConfig.tasks ?? []) {
tasks[task.slug] = runTask(task.slug) as RunTaskFunction<string>
}
return tasks as TIsInline extends true ? RunInlineTaskFunction : RunTaskFunctions
}
}