-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathworkflow-execution.ts
More file actions
238 lines (212 loc) · 8.04 KB
/
Copy pathworkflow-execution.ts
File metadata and controls
238 lines (212 loc) · 8.04 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
import { createLogger, runWithRequestContext } from '@sim/logger'
import { toError } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { task } from '@trigger.dev/sdk'
import { releaseExecutionSlot } from '@/lib/billing/calculations/usage-reservation'
import {
assertBillingAttributionSnapshot,
type BillingAttributionSnapshot,
} from '@/lib/billing/core/billing-attribution'
import type { AsyncExecutionCorrelation } from '@/lib/core/async-jobs/types'
import { createTimeoutAbortController, getTimeoutErrorMessage } from '@/lib/core/execution-limits'
import { preprocessExecution } from '@/lib/execution/preprocessing'
import { LoggingSession } from '@/lib/logs/execution/logging-session'
import { buildTraceSpans } from '@/lib/logs/execution/trace-spans/trace-spans'
import { cleanupExecutionBase64Cache } from '@/lib/uploads/utils/user-file-base64.server'
import {
executeWorkflowCore,
wasExecutionFinalizedByCore,
} from '@/lib/workflows/executor/execution-core'
import { handlePostExecutionPauseState } from '@/lib/workflows/executor/pause-persistence'
import { WORKFLOW_EXECUTION_CONCURRENCY_LIMIT } from '@/background/concurrency-limits'
import { ExecutionSnapshot } from '@/executor/execution/snapshot'
import type { ExecutionMetadata } from '@/executor/execution/types'
import { hasExecutionResult } from '@/executor/utils/errors'
import type { CoreTriggerType } from '@/stores/logs/filters/types'
const logger = createLogger('TriggerWorkflowExecution')
export function buildWorkflowCorrelation(
payload: WorkflowExecutionPayload
): AsyncExecutionCorrelation {
const executionId = payload.executionId || generateId()
const requestId = payload.requestId || payload.correlation?.requestId || executionId.slice(0, 8)
return {
executionId,
requestId,
source: 'workflow',
workflowId: payload.workflowId,
triggerType: payload.triggerType || payload.correlation?.triggerType || 'api',
}
}
export type WorkflowExecutionPayload = {
workflowId: string
userId: string
billingAttribution: BillingAttributionSnapshot
workspaceId: string
input?: any
triggerType?: CoreTriggerType
executionId?: string
requestId?: string
correlation?: AsyncExecutionCorrelation
metadata?: Record<string, any>
callChain?: string[]
executionMode?: 'sync' | 'stream' | 'async'
/** Upstream preprocessing already consumed rate-limit quota and owns the usage reservation. */
admissionCompleted?: boolean
}
/**
* Background workflow execution job
* @see preprocessExecution For detailed information on preprocessing checks
* @see executeWorkflowCore For the core workflow execution logic
*/
export async function executeWorkflowJob(payload: WorkflowExecutionPayload) {
const workflowId = payload.workflowId
const correlation = buildWorkflowCorrelation(payload)
const executionId = correlation.executionId
const requestId = correlation.requestId
let billingAttribution: BillingAttributionSnapshot
try {
billingAttribution = assertBillingAttributionSnapshot(payload.billingAttribution)
if (
billingAttribution.actorUserId !== payload.userId ||
billingAttribution.workspaceId !== payload.workspaceId
) {
throw new Error('Workflow job billing attribution does not match its actor and workspace')
}
} catch (error) {
await releaseExecutionSlot(executionId)
throw error
}
return runWithRequestContext({ requestId }, async () => {
logger.info(`[${requestId}] Starting workflow execution job: ${workflowId}`, {
userId: payload.userId,
triggerType: payload.triggerType,
executionId,
})
const triggerType = (correlation.triggerType || 'api') as CoreTriggerType
const loggingSession = new LoggingSession(workflowId, executionId, triggerType, requestId)
try {
const preprocessResult = await preprocessExecution({
workflowId: payload.workflowId,
userId: payload.userId,
triggerType: triggerType,
executionId: executionId,
requestId: requestId,
checkRateLimit: payload.admissionCompleted !== true,
checkDeployment: true,
skipUsageLimits: payload.admissionCompleted === true,
loggingSession: loggingSession,
triggerData: { correlation },
billingAttribution,
})
if (!preprocessResult.success) {
logger.error(`[${requestId}] Preprocessing failed: ${preprocessResult.error?.message}`, {
workflowId,
statusCode: preprocessResult.error?.statusCode,
})
throw new Error(preprocessResult.error?.message || 'Preprocessing failed')
}
const actorUserId = preprocessResult.actorUserId!
const workspaceId = preprocessResult.workflowRecord?.workspaceId
if (!workspaceId) {
throw new Error(`Workflow ${workflowId} has no associated workspace`)
}
logger.info(`[${requestId}] Preprocessing passed. Using actor: ${actorUserId}`)
const workflow = preprocessResult.workflowRecord!
const metadata: ExecutionMetadata = {
requestId,
executionId,
workflowId,
workspaceId,
userId: actorUserId,
billingAttribution: preprocessResult.billingAttribution,
sessionUserId: undefined,
workflowUserId: workflow.userId,
triggerType: payload.triggerType || 'api',
useDraftState: false,
startTime: new Date().toISOString(),
isClientSession: false,
callChain: payload.callChain,
correlation,
executionMode: payload.executionMode ?? 'async',
}
const snapshot = new ExecutionSnapshot(
metadata,
workflow,
payload.input,
workflow.variables || {},
[]
)
const timeoutController = createTimeoutAbortController(
preprocessResult.executionTimeout?.async
)
let result
try {
result = await executeWorkflowCore({
snapshot,
callbacks: {},
loggingSession,
includeFileBase64: true,
base64MaxBytes: undefined,
abortSignal: timeoutController.signal,
})
} finally {
timeoutController.cleanup()
}
if (
result.status === 'cancelled' &&
timeoutController.isTimedOut() &&
timeoutController.timeoutMs
) {
const timeoutErrorMessage = getTimeoutErrorMessage(null, timeoutController.timeoutMs)
logger.info(`[${requestId}] Workflow execution timed out`, {
timeoutMs: timeoutController.timeoutMs,
})
await loggingSession.markAsFailed(timeoutErrorMessage)
} else {
await handlePostExecutionPauseState({ result, workflowId, executionId, loggingSession })
}
await loggingSession.waitForPostExecution()
logger.info(`[${requestId}] Workflow execution completed: ${workflowId}`, {
success: result.success,
executionTime: result.metadata?.duration,
executionId,
})
return {
success: result.success,
workflowId: payload.workflowId,
executionId,
output: result.output,
executedAt: new Date().toISOString(),
metadata: payload.metadata,
}
} catch (error: unknown) {
logger.error(`[${requestId}] Workflow execution failed: ${workflowId}`, {
error: toError(error).message,
executionId,
})
if (wasExecutionFinalizedByCore(error, executionId)) {
throw error
}
const executionResult = hasExecutionResult(error) ? error.executionResult : undefined
const { traceSpans } = executionResult ? buildTraceSpans(executionResult) : { traceSpans: [] }
await loggingSession.safeCompleteWithError({
error: {
message: toError(error).message,
stackTrace: error instanceof Error ? error.stack : undefined,
},
traceSpans,
})
throw error
} finally {
void cleanupExecutionBase64Cache(executionId)
}
})
}
export const workflowExecutionTask = task({
id: 'workflow-execution',
machine: 'medium-1x',
queue: {
concurrencyLimit: WORKFLOW_EXECUTION_CONCURRENCY_LIMIT,
},
run: executeWorkflowJob,
})