-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathstep-handler.ts
More file actions
869 lines (812 loc) · 32.1 KB
/
step-handler.ts
File metadata and controls
869 lines (812 loc) · 32.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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
import { waitUntil } from '@vercel/functions';
import {
EntityConflictError,
FatalError,
RetryableError,
RunExpiredError,
StepNotRegisteredError,
ThrottleError,
TooEarlyError,
WorkflowRuntimeError,
WorkflowWorldError,
} from '@workflow/errors';
import { pluralize } from '@workflow/utils';
import { getPort } from '@workflow/utils/get-port';
import { SPEC_VERSION_CURRENT, StepInvokePayloadSchema } from '@workflow/world';
import { importKey } from '../encryption.js';
import { runtimeLogger, stepLogger } from '../logger.js';
import { getStepFunction } from '../private.js';
import {
dehydrateStepReturnValue,
hydrateStepArguments,
} from '../serialization.js';
import { contextStorage } from '../step/context-storage.js';
import * as Attribute from '../telemetry/semantic-conventions.js';
import {
getSpanKind,
linkToCurrentContext,
serializeTraceCarrier,
trace,
withTraceContext,
} from '../telemetry.js';
import {
getErrorName,
getErrorStack,
normalizeUnknownError,
} from '../types.js';
import { MAX_QUEUE_DELIVERIES } from './constants.js';
import {
getQueueOverhead,
getWorkflowQueueName,
handleHealthCheckMessage,
parseHealthCheckPayload,
queueMessage,
withHealthCheck,
} from './helpers.js';
import { getWorld, getWorldHandlers } from './world.js';
const DEFAULT_STEP_MAX_RETRIES = 3;
const { createQueueHandler, specVersion: worldSpecVersion } =
getWorldHandlers();
const stepHandler = createQueueHandler(
'__wkf_step_',
async (message_, metadata) => {
// Check if this is a health check message
// NOTE: Health check messages are intentionally unauthenticated for monitoring purposes.
// They only write a simple status response to a stream and do not expose sensitive data.
// The stream name includes a unique correlationId that must be known by the caller.
const healthCheck = parseHealthCheckPayload(message_);
if (healthCheck) {
await handleHealthCheckMessage(healthCheck, 'step', worldSpecVersion);
return;
}
const {
workflowName,
workflowRunId,
workflowStartedAt,
stepId,
traceCarrier: traceContext,
requestedAt,
} = StepInvokePayloadSchema.parse(message_);
const { requestId } = metadata;
// --- Max delivery check ---
// Enforce max delivery limit before any infrastructure calls.
// This prevents runaway steps from consuming infinite queue deliveries.
// At this point, we want to do the minimal amount of work (no fetching
// of the step details, etc. We simply attempt to mark the step as failed
// and enqueue the workflow once, and if either of those fails, the message
// is still consumed but with adequate logging that an error occurred.
if (metadata.attempt > MAX_QUEUE_DELIVERIES) {
runtimeLogger.error(
`Step handler exceeded max deliveries (${metadata.attempt}/${MAX_QUEUE_DELIVERIES})`,
{
workflowRunId,
stepId,
stepName: metadata.queueName.slice('__wkf_step_'.length),
attempt: metadata.attempt,
}
);
try {
const world = getWorld();
await world.events.create(
workflowRunId,
{
eventType: 'step_failed',
specVersion: SPEC_VERSION_CURRENT,
correlationId: stepId,
eventData: {
error: `Step exceeded maximum queue deliveries (${metadata.attempt}/${MAX_QUEUE_DELIVERIES})`,
},
},
{ requestId }
);
// Re-queue the workflow to handle the failed step
await queueMessage(world, getWorkflowQueueName(workflowName), {
runId: workflowRunId,
traceCarrier: await serializeTraceCarrier(),
requestedAt: new Date(),
});
} catch (err) {
if (EntityConflictError.is(err) || RunExpiredError.is(err)) {
return;
}
// Can't even mark the step as failed. Consume the message to stop
// further retries. The run will remain in its current state.
runtimeLogger.error(
`Failed to mark step as failed after ${metadata.attempt} delivery attempts. ` +
`A persistent error is preventing the step from being terminated. ` +
`The run will remain in its current state until manually resolved. ` +
`This is most likely due to a persistent outage of the workflow backend ` +
`or a bug in the workflow runtime and should be reported to the Workflow team.`,
{
workflowRunId,
stepId,
attempt: metadata.attempt,
error: err instanceof Error ? err.message : String(err),
}
);
}
return;
}
const spanLinks = await linkToCurrentContext();
// Execute step within the propagated trace context
return await withTraceContext(traceContext, async () => {
// Extract the step name from the topic name
const stepName = metadata.queueName.slice('__wkf_step_'.length);
const world = getWorld();
const isVercel = process.env.VERCEL_URL !== undefined;
// Resolve local async values concurrently before entering the trace span
const [port, spanKind] = await Promise.all([
isVercel ? undefined : getPort(),
getSpanKind('CONSUMER'),
]);
return trace(
`STEP ${stepName}`,
{ kind: spanKind, links: spanLinks },
async (span) => {
span?.setAttributes({
...Attribute.StepName(stepName),
...Attribute.StepAttempt(metadata.attempt),
// Standard OTEL messaging conventions
...Attribute.MessagingSystem('vercel-queue'),
...Attribute.MessagingDestinationName(metadata.queueName),
...Attribute.MessagingMessageId(metadata.messageId),
...Attribute.MessagingOperationType('process'),
...getQueueOverhead({ requestedAt }),
});
// Note: Step function validation happens after step_started so we can
// properly fail the step (not the run) if the function is not registered.
// This allows the workflow to handle the step failure gracefully.
const stepFn = getStepFunction(stepName);
span?.setAttributes({
...Attribute.WorkflowName(workflowName),
...Attribute.WorkflowRunId(workflowRunId),
...Attribute.StepId(stepId),
...Attribute.StepTracePropagated(!!traceContext),
});
// step_started validates state and returns the step entity, so no separate
// world.steps.get() call is needed. The server checks:
// - Step not in terminal state (returns 409)
// - retryAfter timestamp reached (returns 425 with Retry-After header)
// - Workflow still active (returns 410 if completed)
let step;
try {
const startResult = await world.events.create(
workflowRunId,
{
eventType: 'step_started',
specVersion: SPEC_VERSION_CURRENT,
correlationId: stepId,
},
{ requestId }
);
if (!startResult.step) {
throw new WorkflowRuntimeError(
`step_started event for "${stepId}" did not return step entity`
);
}
step = startResult.step;
} catch (err) {
if (ThrottleError.is(err)) {
const retryRetryAfter = Math.max(
1,
typeof err.retryAfter === 'number' ? err.retryAfter : 1
);
runtimeLogger.info(
'Throttled again on retry, deferring to queue',
{
retryAfterSeconds: retryRetryAfter,
}
);
return { timeoutSeconds: retryRetryAfter };
}
if (RunExpiredError.is(err)) {
runtimeLogger.info(
`Workflow run "${workflowRunId}" has already completed, skipping step "${stepId}": ${err.message}`
);
return;
}
if (EntityConflictError.is(err)) {
runtimeLogger.debug(
'Step in terminal state, re-enqueuing workflow',
{
stepName,
stepId,
workflowRunId,
error: err.message,
}
);
span?.setAttributes({
...Attribute.StepSkipped(true),
...Attribute.StepSkipReason('completed'),
});
span?.addEvent?.('step.skipped', {
'skip.reason': 'terminal_state',
'step.name': stepName,
'step.id': stepId,
});
await queueMessage(world, getWorkflowQueueName(workflowName), {
runId: workflowRunId,
traceCarrier: await serializeTraceCarrier(),
requestedAt: new Date(),
});
return;
}
// Too early: retryAfter timestamp not reached yet
// Return timeout to queue so it retries later
if (TooEarlyError.is(err)) {
const timeoutSeconds = Math.max(1, err.retryAfter ?? 1);
span?.setAttributes({
...Attribute.StepRetryTimeoutSeconds(timeoutSeconds),
});
// Add span event for delayed retry
span?.addEvent?.('step.delayed', {
'delay.reason': 'retry_after_not_reached',
'delay.timeout_seconds': timeoutSeconds,
});
runtimeLogger.debug('Step retryAfter timestamp not yet reached', {
stepName,
stepId,
retryAfterSeconds: err.retryAfter,
timeoutSeconds,
});
return { timeoutSeconds };
}
// Re-throw other errors
throw err;
}
runtimeLogger.debug('Step execution details', {
stepName,
stepId: step.stepId,
status: step.status,
attempt: step.attempt,
});
span?.setAttributes({
...Attribute.StepStatus(step.status),
});
// Validate step function exists AFTER step_started so we can
// properly fail the step (not the run) if the function is missing.
// This allows the workflow to handle the step failure gracefully,
// similar to how FatalError is handled.
if (!stepFn || typeof stepFn !== 'function') {
const err = new StepNotRegisteredError(stepName);
runtimeLogger.error(
'Step function not registered, failing step (not run)',
{
workflowRunId,
stepName,
stepId,
error: err.message,
}
);
// Fail the step via event (event-sourced architecture)
// This matches the FatalError pattern - fail the step and re-queue workflow
try {
await world.events.create(
workflowRunId,
{
eventType: 'step_failed',
specVersion: SPEC_VERSION_CURRENT,
correlationId: stepId,
eventData: {
error: err.message,
stack: err.stack,
},
},
{ requestId }
);
} catch (stepFailErr) {
if (EntityConflictError.is(stepFailErr)) {
runtimeLogger.info(
'Tried failing step for missing function, but step has already finished.',
{
workflowRunId,
stepId,
stepName,
message: stepFailErr.message,
}
);
return;
}
throw stepFailErr;
}
span?.setAttributes({
...Attribute.StepStatus('failed'),
...Attribute.StepFatalError(true),
});
// Re-invoke the workflow to handle the failed step
await queueMessage(world, getWorkflowQueueName(workflowName), {
runId: workflowRunId,
traceCarrier: await serializeTraceCarrier(),
requestedAt: new Date(),
});
return;
}
const maxRetries = stepFn.maxRetries ?? DEFAULT_STEP_MAX_RETRIES;
span?.setAttributes({
...Attribute.StepMaxRetries(maxRetries),
});
let result: unknown;
// Check max retries AFTER step_started (attempt was just incremented)
// step.attempt tracks how many times step_started has been called.
// Note: maxRetries is the number of RETRIES after the first attempt, so total attempts = maxRetries + 1
// Use > here (not >=) because this guards against re-invocation AFTER all attempts are used.
// The post-failure check uses >= to decide whether to retry after a failure.
if (step.attempt > maxRetries + 1) {
const retryCount = step.attempt - 1;
const errorMessage = `Step "${stepName}" exceeded max retries (${retryCount} ${pluralize('retry', 'retries', retryCount)})`;
stepLogger.error('Step exceeded max retries', {
workflowRunId,
stepName,
retryCount,
});
// Fail the step via event (event-sourced architecture)
try {
await world.events.create(
workflowRunId,
{
eventType: 'step_failed',
specVersion: SPEC_VERSION_CURRENT,
correlationId: stepId,
eventData: {
error: errorMessage,
stack: step.error?.stack,
},
},
{ requestId }
);
} catch (err) {
if (EntityConflictError.is(err)) {
runtimeLogger.info(
'Tried failing step, but step has already finished.',
{
workflowRunId,
stepId,
stepName,
message: err.message,
}
);
return;
}
throw err;
}
span?.setAttributes({
...Attribute.StepStatus('failed'),
...Attribute.StepRetryExhausted(true),
});
// Re-invoke the workflow to handle the failed step
await queueMessage(world, getWorkflowQueueName(workflowName), {
runId: workflowRunId,
traceCarrier: await serializeTraceCarrier(),
requestedAt: new Date(),
});
return;
}
// --- Infrastructure: prepare step input ---
// Network/server errors propagate to the queue handler for retry.
// WorkflowRuntimeError (data integrity issues) are fatal — retrying
// won't fix them, so we re-queue the workflow to surface the error.
// step_started already validated the step is in valid state (pending/running)
// and returned the updated step entity with incremented attempt
// step.attempt is now the current attempt number (after increment)
const attempt = step.attempt;
if (!step.startedAt) {
const errorMessage = `Step "${stepId}" has no "startedAt" timestamp`;
runtimeLogger.error('Fatal runtime error during step setup', {
workflowRunId,
stepId,
error: errorMessage,
});
try {
await world.events.create(
workflowRunId,
{
eventType: 'step_failed',
specVersion: SPEC_VERSION_CURRENT,
correlationId: stepId,
eventData: {
error: errorMessage,
stack: new Error(errorMessage).stack ?? '',
},
},
{ requestId }
);
} catch (failErr) {
if (EntityConflictError.is(failErr)) {
return;
}
throw failErr;
}
// Re-queue the workflow so it can process the step failure
await queueMessage(world, getWorkflowQueueName(workflowName), {
runId: workflowRunId,
traceCarrier: await serializeTraceCarrier(),
requestedAt: new Date(),
});
return;
}
// Capture startedAt for use in async callback (TypeScript narrowing doesn't persist)
const stepStartedAt = step.startedAt;
// Hydrate the step input arguments, closure variables, and thisVal
// NOTE: This captures only the synchronous portion of hydration. Any async
// operations (e.g., stream loading) are added to `ops` and executed later
// via Promise.all(ops) - their timing is not included in this measurement.
const ops: Promise<void>[] = [];
const rawKey = await world.getEncryptionKeyForRun?.(workflowRunId);
const encryptionKey = rawKey ? await importKey(rawKey) : undefined;
const hydratedInput = await trace(
'step.hydrate',
{},
async (hydrateSpan) => {
const startTime = Date.now();
const result = await hydrateStepArguments(
step.input,
workflowRunId,
encryptionKey,
ops
);
const durationMs = Date.now() - startTime;
hydrateSpan?.setAttributes({
...Attribute.StepArgumentsCount(result.args.length),
...Attribute.QueueDeserializeTimeMs(durationMs),
});
return result;
}
);
const args = hydratedInput.args;
const thisVal = hydratedInput.thisVal ?? null;
// --- User code execution ---
// Only errors from stepFn.apply() (user step code) should produce
// step_failed/step_retrying. Infrastructure errors (network, server)
// must propagate to the queue handler for automatic retry.
let userCodeError: unknown;
let userCodeFailed = false;
const executionStartTime = Date.now();
try {
result = await trace('step.execute', {}, async () => {
return await contextStorage.run(
{
stepMetadata: {
stepName,
stepId,
stepStartedAt: new Date(+stepStartedAt),
attempt,
},
workflowMetadata: {
workflowName,
workflowRunId,
workflowStartedAt: new Date(+workflowStartedAt),
// TODO: there should be a getUrl method on the world interface itself. This
// solution only works for vercel + local worlds.
url: isVercel
? `https://${process.env.VERCEL_URL}`
: `http://localhost:${port ?? 3000}`,
},
ops,
closureVars: hydratedInput.closureVars,
encryptionKey,
},
() => stepFn.apply(thisVal, args)
);
});
} catch (err) {
userCodeError = err;
userCodeFailed = true;
}
const executionTimeMs = Date.now() - executionStartTime;
span?.setAttributes({
...Attribute.QueueExecutionTimeMs(executionTimeMs),
});
// --- Handle user code errors ---
if (userCodeFailed) {
const err = userCodeError;
// Infrastructure errors that somehow surfaced through user code
// should propagate to the queue handler for retry, not consume
// step attempts.
if (RunExpiredError.is(err)) {
// Workflow has already completed, so no-op
stepLogger.info('Workflow run already completed, skipping step', {
workflowRunId,
stepId,
message: err.message,
});
return;
}
if (WorkflowWorldError.is(err)) {
if (err.status !== undefined && err.status >= 500) {
throw err;
}
}
const normalizedError = await normalizeUnknownError(err);
const normalizedStack =
normalizedError.stack || getErrorStack(err) || '';
// Record exception for OTEL error tracking
if (err instanceof Error) {
span?.recordException?.(err);
}
// Determine error category and retryability
const isFatal = FatalError.is(err);
const isRetryable = RetryableError.is(err);
const errorCategory = isFatal
? 'fatal'
: isRetryable
? 'retryable'
: 'transient';
span?.setAttributes({
...Attribute.StepErrorName(getErrorName(err)),
...Attribute.StepErrorMessage(normalizedError.message),
...Attribute.ErrorType(getErrorName(err)),
...Attribute.ErrorCategory(errorCategory),
...Attribute.ErrorRetryable(!isFatal),
});
if (isFatal) {
stepLogger.error(
'Encountered FatalError while executing step, bubbling up to parent workflow',
{
workflowRunId,
stepName,
errorStack: normalizedStack,
}
);
// Fail the step via event (event-sourced architecture)
try {
await world.events.create(
workflowRunId,
{
eventType: 'step_failed',
specVersion: SPEC_VERSION_CURRENT,
correlationId: stepId,
eventData: {
error: normalizedError.message,
stack: normalizedStack,
},
},
{ requestId }
);
} catch (stepFailErr) {
if (EntityConflictError.is(stepFailErr)) {
runtimeLogger.info(
'Tried failing step, but step has already finished.',
{
workflowRunId,
stepId,
stepName,
message: stepFailErr.message,
}
);
return;
}
throw stepFailErr;
}
span?.setAttributes({
...Attribute.StepStatus('failed'),
...Attribute.StepFatalError(true),
});
} else {
const maxRetries = stepFn.maxRetries ?? DEFAULT_STEP_MAX_RETRIES;
// step.attempt was incremented by step_started, use it here
const currentAttempt = step.attempt;
span?.setAttributes({
...Attribute.StepAttempt(currentAttempt),
...Attribute.StepMaxRetries(maxRetries),
});
// Note: maxRetries is the number of RETRIES after the first attempt, so total attempts = maxRetries + 1
if (currentAttempt >= maxRetries + 1) {
// Max retries reached
const retryCount = step.attempt - 1;
stepLogger.error(
'Max retries reached, bubbling error to parent workflow',
{
workflowRunId,
stepName,
attempt: step.attempt,
retryCount,
errorStack: normalizedStack,
}
);
const errorMessage = `Step "${stepName}" failed after ${maxRetries} ${pluralize('retry', 'retries', maxRetries)}: ${normalizedError.message}`;
// Fail the step via event (event-sourced architecture)
try {
await world.events.create(
workflowRunId,
{
eventType: 'step_failed',
specVersion: SPEC_VERSION_CURRENT,
correlationId: stepId,
eventData: {
error: errorMessage,
stack: normalizedStack,
},
},
{ requestId }
);
} catch (stepFailErr) {
if (EntityConflictError.is(stepFailErr)) {
runtimeLogger.info(
'Tried failing step, but step has already finished.',
{
workflowRunId,
stepId,
stepName,
message: stepFailErr.message,
}
);
return;
}
throw stepFailErr;
}
span?.setAttributes({
...Attribute.StepStatus('failed'),
...Attribute.StepRetryExhausted(true),
});
} else {
// Not at max retries yet - log as a retryable error
if (RetryableError.is(err)) {
stepLogger.info(
'Encountered RetryableError, step will be retried',
{
workflowRunId,
stepName,
attempt: currentAttempt,
message: err.message,
}
);
} else {
stepLogger.info('Encountered Error, step will be retried', {
workflowRunId,
stepName,
attempt: currentAttempt,
errorStack: normalizedStack,
});
}
// Set step to pending for retry via event (event-sourced architecture)
// step_retrying records the error and sets status to pending
try {
await world.events.create(
workflowRunId,
{
eventType: 'step_retrying',
specVersion: SPEC_VERSION_CURRENT,
correlationId: stepId,
eventData: {
error: normalizedError.message,
stack: normalizedStack,
...(RetryableError.is(err) && {
retryAfter: err.retryAfter,
}),
},
},
{ requestId }
);
} catch (stepRetryErr) {
if (EntityConflictError.is(stepRetryErr)) {
runtimeLogger.info(
'Tried retrying step, but step has already finished.',
{
workflowRunId,
stepId,
stepName,
message: stepRetryErr.message,
}
);
return;
}
throw stepRetryErr;
}
const timeoutSeconds = Math.max(
1,
RetryableError.is(err)
? Math.ceil((+err.retryAfter.getTime() - Date.now()) / 1000)
: 1
);
span?.setAttributes({
...Attribute.StepRetryTimeoutSeconds(timeoutSeconds),
...Attribute.StepRetryWillRetry(true),
});
// Add span event for retry scheduling
span?.addEvent?.('retry.scheduled', {
'retry.timeout_seconds': timeoutSeconds,
'retry.attempt': currentAttempt,
'retry.max_retries': maxRetries,
});
// It's a retryable error - so have the queue keep the message visible
// so that it gets retried.
return { timeoutSeconds };
}
}
// Re-invoke the workflow to handle the failed/retrying step
await queueMessage(world, getWorkflowQueueName(workflowName), {
runId: workflowRunId,
traceCarrier: await serializeTraceCarrier(),
requestedAt: new Date(),
});
return;
}
// --- Infrastructure: complete the step ---
// Errors here (network failures, server errors) propagate to the
// queue handler for automatic retry.
// NOTE: None of the code from this point is guaranteed to run
// Since the step might fail or cause a function timeout and the process might be SIGKILL'd
// The workflow runtime must be resilient to the below code not executing on a failed step
result = await trace('step.dehydrate', {}, async (dehydrateSpan) => {
const startTime = Date.now();
const dehydrated = await dehydrateStepReturnValue(
result,
workflowRunId,
encryptionKey,
ops
);
const durationMs = Date.now() - startTime;
dehydrateSpan?.setAttributes({
...Attribute.QueueSerializeTimeMs(durationMs),
...Attribute.StepResultType(typeof dehydrated),
});
return dehydrated;
});
waitUntil(
Promise.all(ops).catch((err) => {
// Ignore expected client disconnect errors (e.g., browser refresh during streaming)
const isAbortError =
err?.name === 'AbortError' || err?.name === 'ResponseAborted';
if (!isAbortError) throw err;
})
);
// Run step_completed and trace serialization concurrently;
// the trace carrier is used in the final queueMessage call below
let stepCompleted409 = false;
const [, traceCarrier] = await Promise.all([
world.events
.create(
workflowRunId,
{
eventType: 'step_completed',
specVersion: SPEC_VERSION_CURRENT,
correlationId: stepId,
eventData: {
result: result as Uint8Array,
},
},
{ requestId }
)
.catch((err: unknown) => {
if (EntityConflictError.is(err)) {
runtimeLogger.info(
'Tried completing step, but step has already finished.',
{
workflowRunId,
stepId,
stepName,
message: err.message,
}
);
stepCompleted409 = true;
return;
}
throw err;
}),
serializeTraceCarrier(),
]);
if (stepCompleted409) {
return;
}
span?.setAttributes({
...Attribute.StepStatus('completed'),
...Attribute.StepResultType(typeof result),
});
// Queue the workflow continuation with the concurrently-resolved trace carrier
await queueMessage(world, getWorkflowQueueName(workflowName), {
runId: workflowRunId,
traceCarrier,
requestedAt: new Date(),
});
}
);
});
}
);
/**
* A single route that handles any step execution request and routes to the
* appropriate step function. We may eventually want to create different bundles
* for each step, this is temporary.
*/
export const stepEntrypoint: (req: Request) => Promise<Response> =
/* @__PURE__ */ withHealthCheck(stepHandler, worldSpecVersion);