-
Notifications
You must be signed in to change notification settings - Fork 255
Expand file tree
/
Copy path99_e2e.ts
More file actions
1718 lines (1449 loc) · 49.3 KB
/
99_e2e.ts
File metadata and controls
1718 lines (1449 loc) · 49.3 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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Test path alias resolution - imports a helper from outside the workbench directory
/** biome-ignore-all lint/complexity/noStaticOnlyClass: <explanation> */
import { pathsAliasHelper } from '@repo/lib/steps/paths-alias-test';
import {
createHook,
createWebhook,
FatalError,
fetch,
getStepMetadata,
getWorkflowMetadata,
getWritable,
type RequestWithResponse,
RetryableError,
sleep,
} from 'workflow';
import { getRun, Run, resumeHook, start } from 'workflow/api';
import { importedStepOnly } from './_imported_step_only';
import { callThrower, stepThatThrowsFromHelper } from './helpers';
//////////////////////////////////////////////////////////
export async function add(a: number, b: number) {
'use step';
return a + b;
}
export async function addTenWorkflow(input: number) {
'use workflow';
const a = await add(input, 2);
const b = await add(a, 3);
const c = await add(b, 5);
return c;
}
//////////////////////////////////////////////////////////
async function randomDelay(v: string) {
'use step';
await new Promise((resolve) => setTimeout(resolve, Math.random() * 3000));
return v.toUpperCase();
}
export async function promiseAllWorkflow() {
'use workflow';
const [a, b, c] = await Promise.all([
randomDelay('a'),
randomDelay('b'),
randomDelay('c'),
]);
return a + b + c;
}
//////////////////////////////////////////////////////////
async function specificDelay(delay: number, v: string) {
'use step';
await new Promise((resolve) => setTimeout(resolve, delay));
return v.toUpperCase();
}
export async function promiseRaceWorkflow() {
'use workflow';
const winner = await Promise.race([
specificDelay(10000, 'a'),
specificDelay(100, 'b'), // "b" should always win
specificDelay(20000, 'c'),
]);
return winner;
}
//////////////////////////////////////////////////////////
async function stepThatFails() {
'use step';
throw new FatalError('step failed');
}
export async function promiseAnyWorkflow() {
'use workflow';
const winner = await Promise.any([
stepThatFails(),
specificDelay(100, 'b'), // "b" should always win
specificDelay(6000, 'c'),
]);
return winner;
}
//////////////////////////////////////////////////////////
export async function importedStepOnlyWorkflow() {
'use workflow';
return await importedStepOnly();
}
//////////////////////////////////////////////////////////
// Name should not conflict with genStream in 3_streams.ts
// TODO: swc transform should mangle names to avoid conflicts
async function genReadableStream() {
'use step';
const encoder = new TextEncoder();
return new ReadableStream({
async start(controller) {
for (let i = 0; i < 10; i++) {
console.log('enqueueing', i);
controller.enqueue(encoder.encode(`${i}\n`));
await new Promise((resolve) => setTimeout(resolve, 1000));
}
console.log('closing controller');
controller.close();
},
});
}
export async function readableStreamWorkflow() {
'use workflow';
console.log('calling genReadableStream');
const stream = await genReadableStream();
console.log('genReadableStream returned', stream);
return stream;
}
//////////////////////////////////////////////////////////
export async function hookWorkflow(token: string, customData: string) {
'use workflow';
type Payload = { message: string; customData: string; done?: boolean };
using hook = createHook<Payload>({
token,
metadata: { customData },
});
const payloads: Payload[] = [];
for await (const payload of hook) {
payloads.push(payload);
if (payload.done) {
break;
}
}
return payloads;
}
//////////////////////////////////////////////////////////
async function sendWebhookResponse(req: RequestWithResponse) {
'use step';
const body = await req.text();
await req.respondWith(new Response('Hello from webhook!'));
return body;
}
export async function webhookWorkflow() {
'use workflow';
type Payload = { url: string; method: string; body: string };
const payloads: Payload[] = [];
// All webhooks must be created upfront so they're all registered
// before the test sends HTTP requests to them
const webhookWithDefaultResponse = createWebhook();
const res = new Response('Hello from static response!', { status: 402 });
const webhookWithStaticResponse = createWebhook({
respondWith: res,
});
const webhookWithManualResponse = createWebhook({
respondWith: 'manual',
});
// Webhook with default response
{
const req = await webhookWithDefaultResponse;
const body = await req.text();
payloads.push({ url: req.url, method: req.method, body });
}
// Webhook with static response
{
const req = await webhookWithStaticResponse;
const body = await req.text();
payloads.push({ url: req.url, method: req.method, body });
}
// Webhook with manual response
{
const req = await webhookWithManualResponse;
const body = await sendWebhookResponse(req);
payloads.push({ url: req.url, method: req.method, body });
}
return payloads;
}
//////////////////////////////////////////////////////////
export async function sleepingWorkflow(durationMs = 10_000) {
'use workflow';
const startTime = Date.now();
await sleep(durationMs);
const endTime = Date.now();
return { startTime, endTime };
}
export async function parallelSleepWorkflow() {
'use workflow';
const startTime = Date.now();
await Promise.all(Array.from({ length: 10 }, () => sleep('1s')));
const endTime = Date.now();
return { startTime, endTime };
}
//////////////////////////////////////////////////////////
async function nullByteStep() {
'use step';
return 'null byte \0';
}
export async function nullByteWorkflow() {
'use workflow';
const a = await nullByteStep();
return a;
}
//////////////////////////////////////////////////////////
async function stepWithMetadata() {
'use step';
const stepMetadata = getStepMetadata();
const workflowMetadata = getWorkflowMetadata();
return { stepMetadata, workflowMetadata };
}
export async function workflowAndStepMetadataWorkflow() {
'use workflow';
const workflowMetadata = getWorkflowMetadata();
const { stepMetadata, workflowMetadata: innerWorkflowMetadata } =
await stepWithMetadata();
return {
workflowMetadata: {
workflowName: workflowMetadata.workflowName,
workflowRunId: workflowMetadata.workflowRunId,
workflowStartedAt: workflowMetadata.workflowStartedAt,
url: workflowMetadata.url,
features: workflowMetadata.features,
},
stepMetadata,
innerWorkflowMetadata,
};
}
//////////////////////////////////////////////////////////
async function stepWithOutputStreamBinary(
writable: WritableStream,
text: string
) {
'use step';
const writer = writable.getWriter();
// binary data
await writer.write(new TextEncoder().encode(text));
writer.releaseLock();
}
async function stepWithOutputStreamObject(writable: WritableStream, obj: any) {
'use step';
const writer = writable.getWriter();
// object data
await writer.write(obj);
writer.releaseLock();
}
async function stepCloseOutputStream(writable: WritableStream) {
'use step';
await writable.close();
}
export async function outputStreamWorkflow() {
'use workflow';
const writable = getWritable();
const namedWritable = getWritable({ namespace: 'test' });
await sleep('1s');
await stepWithOutputStreamBinary(writable, 'Hello, world!');
await sleep('1s');
await stepWithOutputStreamBinary(namedWritable, 'Hello, named stream!');
await sleep('1s');
await stepWithOutputStreamObject(writable, { foo: 'test' });
await sleep('1s');
await stepWithOutputStreamObject(namedWritable, { foo: 'bar' });
await sleep('1s');
await stepCloseOutputStream(writable);
await stepCloseOutputStream(namedWritable);
return 'done';
}
//////////////////////////////////////////////////////////
async function stepWithOutputStreamInsideStep(text: string) {
'use step';
// Call getWritable directly inside the step function
const writable = getWritable();
const writer = writable.getWriter();
await writer.write(new TextEncoder().encode(text));
writer.releaseLock();
}
async function stepWithNamedOutputStreamInsideStep(
namespace: string,
obj: any
) {
'use step';
// Call getWritable with namespace directly inside the step function
const writable = getWritable({ namespace });
const writer = writable.getWriter();
await writer.write(obj);
writer.releaseLock();
}
async function stepCloseOutputStreamInsideStep(namespace?: string) {
'use step';
// Call getWritable directly inside the step function and close it
const writable = getWritable({ namespace });
await writable.close();
}
export async function outputStreamInsideStepWorkflow() {
'use workflow';
await sleep('1s');
await stepWithOutputStreamInsideStep('Hello from step!');
await sleep('1s');
await stepWithNamedOutputStreamInsideStep('step-ns', {
message: 'Hello from named stream in step!',
});
await sleep('1s');
await stepWithOutputStreamInsideStep('Second message');
await sleep('1s');
await stepWithNamedOutputStreamInsideStep('step-ns', { counter: 42 });
await sleep('1s');
await stepCloseOutputStreamInsideStep();
await stepCloseOutputStreamInsideStep('step-ns');
return 'done';
}
//////////////////////////////////////////////////////////
export async function fetchWorkflow() {
'use workflow';
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
return data;
}
//////////////////////////////////////////////////////////
export async function promiseRaceStressTestDelayStep(
dur: number,
resp: number
): Promise<number> {
'use step';
console.log(`sleep`, resp, `/`, dur);
await new Promise((resolve) => setTimeout(resolve, dur));
console.log(resp, `done`);
return resp;
}
export async function promiseRaceStressTestWorkflow() {
'use workflow';
const promises = new Map<number, Promise<number>>();
const done: number[] = [];
for (let i = 0; i < 5; i++) {
const resp = i;
const dur = 1000 * 5 * i; // 5 seconds apart
console.log(`sched`, resp, `/`, dur);
promises.set(i, promiseRaceStressTestDelayStep(dur, resp));
}
while (promises.size > 0) {
console.log(`promises.size`, promises.size);
const res = await Promise.race(promises.values());
console.log(res);
done.push(res);
promises.delete(res);
}
return done;
}
//////////////////////////////////////////////////////////
async function stepThatRetriesAndSucceeds() {
'use step';
const { attempt } = getStepMetadata();
console.log(`stepThatRetriesAndSucceeds - attempt: ${attempt}`);
// Fail on attempts 1 and 2, succeed on attempt 3
if (attempt < 3) {
console.log(`Attempt ${attempt} - throwing error to trigger retry`);
throw new Error(`Failed on attempt ${attempt}`);
}
console.log(`Attempt ${attempt} - succeeding`);
return attempt;
}
export async function retryAttemptCounterWorkflow() {
'use workflow';
console.log('Starting retry attempt counter workflow');
// This step should fail twice and succeed on the third attempt
const finalAttempt = await stepThatRetriesAndSucceeds();
console.log(`Workflow completed with final attempt: ${finalAttempt}`);
return { finalAttempt };
}
//////////////////////////////////////////////////////////
async function stepThatThrowsRetryableError() {
'use step';
const { attempt, stepStartedAt } = getStepMetadata();
if (attempt === 1) {
throw new RetryableError('Retryable error', {
retryAfter: '10s',
});
}
return {
attempt,
stepStartedAt,
duration: Date.now() - stepStartedAt.getTime(),
};
}
export async function crossFileErrorWorkflow() {
'use workflow';
// This will throw an error from the imported helpers.ts file
callThrower();
return 'never reached';
}
//////////////////////////////////////////////////////////
export async function retryableAndFatalErrorWorkflow() {
'use workflow';
const retryableResult = await stepThatThrowsRetryableError();
let gotFatalError = false;
try {
await stepThatFails();
} catch (error: any) {
if (FatalError.is(error)) {
gotFatalError = true;
}
}
return { retryableResult, gotFatalError };
}
//////////////////////////////////////////////////////////
// Test that maxRetries = 0 means the step runs once but does not retry on failure
async function stepWithNoRetries() {
'use step';
const { attempt } = getStepMetadata();
console.log(`stepWithNoRetries - attempt: ${attempt}`);
// Always fail - with maxRetries = 0, this should only run once
throw new Error(`Failed on attempt ${attempt}`);
}
stepWithNoRetries.maxRetries = 0;
// Test that maxRetries = 0 works when the step succeeds
async function stepWithNoRetriesThatSucceeds() {
'use step';
const { attempt } = getStepMetadata();
console.log(`stepWithNoRetriesThatSucceeds - attempt: ${attempt}`);
return { attempt };
}
stepWithNoRetriesThatSucceeds.maxRetries = 0;
export async function maxRetriesZeroWorkflow() {
'use workflow';
console.log('Starting maxRetries = 0 workflow');
// First, verify that a step with maxRetries = 0 can still succeed
const successResult = await stepWithNoRetriesThatSucceeds();
// Now test that a failing step with maxRetries = 0 does NOT retry
let failedAttempt: number | null = null;
let gotError = false;
try {
await stepWithNoRetries();
} catch (error: any) {
gotError = true;
console.log('Received error', typeof error, error, error.message);
// Extract the attempt number from the error message
const match = error.message?.match(/attempt (\d+)/);
if (match) {
failedAttempt = parseInt(match[1], 10);
}
}
console.log(
`Workflow completed: successResult=${JSON.stringify(successResult)}, gotError=${gotError}, failedAttempt=${failedAttempt}`
);
return {
successResult,
gotError,
failedAttempt,
};
}
//////////////////////////////////////////////////////////
export async function hookCleanupTestWorkflow(
token: string,
customData: string
) {
'use workflow';
type Payload = { message: string; customData: string };
using hook = createHook<Payload>({
token,
metadata: { customData },
});
const payload = await hook;
return {
message: payload.message,
customData: payload.customData,
hookCleanupTestData: 'workflow_completed',
};
}
//////////////////////////////////////////////////////////
/**
* Workflow for testing early hook disposal - allows another workflow to reuse
* the token while this workflow is still running.
*
* The block scope with `using` releases the token before the sleep, so another
* workflow can claim the token while this one continues.
*/
export async function hookDisposeTestWorkflow(
token: string,
customData: string
) {
'use workflow';
type Payload = { message: string; customData: string };
let message: string;
let customDataResult: string;
{
// Block scope releases the hook token when exited
using hook = createHook<Payload>({
token,
metadata: { customData },
});
const payload = await hook;
message = payload.message;
customDataResult = payload.customData;
}
// Token is now available for another workflow while we continue
await sleep('5s');
return {
message,
customData: customDataResult,
disposed: true,
hookDisposeTestData: 'workflow_completed',
};
}
//////////////////////////////////////////////////////////
export async function stepFunctionPassingWorkflow() {
'use workflow';
// Pass a step function reference to another step (without closure vars)
const result = await stepWithStepFunctionArg(doubleNumber);
return result;
}
async function stepWithStepFunctionArg(stepFn: (x: number) => Promise<number>) {
'use step';
// Call the passed step function reference
const result = await stepFn(10);
return result * 2;
}
async function doubleNumber(x: number) {
'use step';
return x * 2;
}
//////////////////////////////////////////////////////////
export async function stepFunctionWithClosureWorkflow() {
'use workflow';
const multiplier = 3;
const prefix = 'Result: ';
// Create a step function that captures closure variables
const calculate = async (x: number) => {
'use step';
return `${prefix}${x * multiplier}`;
};
// Pass the step function (with closure vars) to another step
const result = await stepThatCallsStepFn(calculate, 7);
return result;
}
async function stepThatCallsStepFn(
stepFn: (x: number) => Promise<string>,
value: number
) {
'use step';
// Call the passed step function - closure vars should be preserved
const result = await stepFn(value);
return `Wrapped: ${result}`;
}
//////////////////////////////////////////////////////////
export async function closureVariableWorkflow(baseValue: number) {
'use workflow';
// biome-ignore lint/style/useConst: Intentionally using `let` instead of `const`
let multiplier = 3;
const prefix = 'Result: ';
// Nested step function that uses closure variables
const calculate = async () => {
'use step';
const result = baseValue * multiplier;
return `${prefix}${result}`;
};
const output = await calculate();
return output;
}
//////////////////////////////////////////////////////////
// Child workflow that will be spawned from another workflow
export async function childWorkflow(value: number) {
'use workflow';
// Do some processing
const doubled = await doubleValue(value);
return { childResult: doubled, originalValue: value };
}
async function doubleValue(value: number) {
'use step';
return value * 2;
}
// Step function that spawns another workflow using start()
async function spawnChildWorkflow(value: number) {
'use step';
// start() can only be called inside a step function, not directly in workflow code
const childRun = await start(childWorkflow, [value]);
return childRun.runId;
}
// Step function that waits for a workflow run to complete and returns its result
async function awaitWorkflowResult<T>(runId: string) {
'use step';
const run = getRun<T>(runId);
const result = await run.returnValue;
return result;
}
export async function spawnWorkflowFromStepWorkflow(inputValue: number) {
'use workflow';
// Spawn the child workflow from inside a step function
const childRunId = await spawnChildWorkflow(inputValue);
// Wait for the child workflow to complete (also in a step)
const childResult = await awaitWorkflowResult<{
childResult: number;
originalValue: number;
}>(childRunId);
return {
parentInput: inputValue,
childRunId,
childResult,
};
}
async function spawnChildWorkflowRun(value: number) {
'use step';
return await start(childWorkflow, [value]);
}
async function getRunIdFromRun(run: Run<unknown>) {
'use step';
return run.runId;
}
async function awaitRunFromRun<T>(run: Run<T>) {
'use step';
return await run.returnValue;
}
export async function runClassSerializationWorkflow(inputValue: number) {
'use workflow';
const childRun = await spawnChildWorkflowRun(inputValue);
const isRunInWorkflow = childRun instanceof Run;
const runIdFromStep = await getRunIdFromRun(childRun);
const childResult = await awaitRunFromRun<{
childResult: number;
originalValue: number;
}>(childRun);
return {
childRunId: childRun.runId,
runIdFromStep,
isRunInWorkflow,
childResult,
};
}
//////////////////////////////////////////////////////////
/**
* Step that calls a helper function imported via path alias.
*/
async function callPathsAliasHelper() {
'use step';
// Call the helper function imported via @repo/* path alias
return pathsAliasHelper();
}
/**
* Test that TypeScript path aliases work correctly.
* This workflow uses a step that calls a helper function imported via the @repo/* path alias,
* which resolves to a file outside the workbench directory.
*/
export async function pathsAliasWorkflow() {
'use workflow';
// Call the step that uses the path alias helper
const result = await callPathsAliasHelper();
return result;
}
// ============================================================
// ERROR HANDLING E2E TEST WORKFLOWS
// ============================================================
// These workflows test error propagation and retry behavior.
// Each workflow tests a specific error scenario with clear naming:
// error<Context><Behavior>
// Where Context is "Workflow" or "Step", and Behavior describes what's tested.
//
// Organized into 3 sections:
// 1. Error Propagation - message and stack trace preservation
// 2. Retry Behavior - how different error types affect retries
// 3. Catchability - catching errors in workflow code
// ============================================================
// ------------------------------------------------------------
// SECTION 1: ERROR PROPAGATION
// Tests that error messages and stack traces are preserved correctly
// ------------------------------------------------------------
// --- Workflow Errors (errors thrown directly in workflow code) ---
function errorNested3() {
throw new Error('Nested workflow error');
}
function errorNested2() {
errorNested3();
}
function errorNested1() {
errorNested2();
}
/** Test: Workflow error from nested function calls preserves stack trace */
export async function errorWorkflowNested() {
'use workflow';
errorNested1();
return 'never reached';
}
/** Test: Workflow error from imported module preserves file reference in stack */
export async function errorWorkflowCrossFile() {
'use workflow';
callThrower(); // from helpers.ts - throws Error
return 'never reached';
}
// --- Step Errors (errors thrown in steps that propagate to workflow) ---
async function errorStepFn() {
'use step';
throw new Error('Step error message');
}
errorStepFn.maxRetries = 0;
/** Test: Step error message propagates correctly to workflow */
export async function errorStepBasic() {
'use workflow';
try {
await errorStepFn();
return { caught: false, message: null, stack: null };
} catch (e: any) {
return { caught: true, message: e.message, stack: e.stack };
}
}
/** Test: Step error from imported module has function names in stack */
export async function errorStepCrossFile() {
'use workflow';
try {
await stepThatThrowsFromHelper(); // from helpers.ts
return { caught: false, message: null, stack: null };
} catch (e: any) {
return { caught: true, message: e.message, stack: e.stack };
}
}
// ------------------------------------------------------------
// SECTION 2: RETRY BEHAVIOR
// Tests how different error types affect step retry behavior
// ------------------------------------------------------------
async function retryUntilAttempt3() {
'use step';
const { attempt } = getStepMetadata();
if (attempt < 3) {
throw new Error(`Failed on attempt ${attempt}`);
}
return attempt;
}
/** Test: Regular Error retries until success (succeeds on attempt 3) */
export async function errorRetrySuccess() {
'use workflow';
const attempt = await retryUntilAttempt3();
return { finalAttempt: attempt };
}
// ---
async function throwFatalError() {
'use step';
throw new FatalError('Fatal step error');
}
/** Test: FatalError fails immediately without retry (attempt=1) */
export async function errorRetryFatal() {
'use workflow';
await throwFatalError();
return 'never reached';
}
// ---
async function throwRetryableError() {
'use step';
const { attempt, stepStartedAt } = getStepMetadata();
if (attempt === 1) {
throw new RetryableError('Retryable error', { retryAfter: '10s' });
}
return {
attempt,
duration: Date.now() - stepStartedAt.getTime(),
};
}
/** Test: RetryableError respects custom retryAfter timing (waits 10s+) */
export async function errorRetryCustomDelay() {
'use workflow';
return await throwRetryableError();
}
// ---
async function throwWithNoRetries() {
'use step';
const { attempt } = getStepMetadata();
throw new Error(`Failed on attempt ${attempt}`);
}
throwWithNoRetries.maxRetries = 0;
/** Test: maxRetries=0 runs once without retry on failure */
export async function errorRetryDisabled() {
'use workflow';
try {
await throwWithNoRetries();
return { failed: false, attempt: null };
} catch (e: any) {
// Extract attempt from error message
const match = e.message?.match(/attempt (\d+)/);
return { failed: true, attempt: match ? parseInt(match[1]) : null };
}
}
// ------------------------------------------------------------
// SECTION 3: CATCHABILITY
// Tests that errors can be caught and inspected in workflow code
// ------------------------------------------------------------
/** Test: FatalError can be caught and detected with FatalError.is() */
export async function errorFatalCatchable() {
'use workflow';
try {
await throwFatalError();
return { caught: false, isFatal: false };
} catch (e: any) {
return { caught: true, isFatal: FatalError.is(e) };
}
}
// ------------------------------------------------------------
// SECTION 4: NOT REGISTERED ERRORS
// Tests for step/workflow not registered in the current deployment
// ------------------------------------------------------------
/**
* Test: step not registered causes the step to fail (like FatalError),
* and the workflow can catch the error gracefully.
*
* This manually invokes useStep with a step ID that doesn't exist in the
* deployment bundle, simulating what would happen if a build/bundling issue
* caused a step to be missing.
*/
export async function stepNotRegisteredCatchable() {
'use workflow';
// Manually invoke a step that doesn't exist in the deployment.
// The SWC transform generates exactly this pattern for real step calls,
// so this is equivalent to calling a step that wasn't bundled.
const ghost = (globalThis as any)[Symbol.for('WORKFLOW_USE_STEP')](
'step//./workflows/99_e2e//nonExistentStep'
);
try {
await ghost();
return { caught: false, error: null };
} catch (e: any) {
return { caught: true, error: e.message };
}
}
/**
* Test: step not registered causes the run to fail when not caught.
*/
export async function stepNotRegisteredUncaught() {
'use workflow';
const ghost = (globalThis as any)[Symbol.for('WORKFLOW_USE_STEP')](
'step//./workflows/99_e2e//anotherNonExistentStep'
);
// Don't catch — the step failure should propagate and fail the run
return await ghost();
}
// ============================================================
// STATIC METHOD STEP/WORKFLOW TESTS
// ============================================================
// Tests for static methods on classes with "use step" and "use workflow" directives.
// ============================================================
/**
* Service class with static step methods for math operations.
* These methods are transformed to be callable as workflow steps.
*/
export class MathService {
/** Static step: add two numbers */
static async add(a: number, b: number): Promise<number> {
'use step';
return a + b;
}
/** Static step: multiply two numbers */
static async multiply(a: number, b: number): Promise<number> {
'use step';
return a * b;
}
}
/**
* Workflow class with a static workflow method that uses static step methods.
*/
export class Calculator {
/** Static workflow: uses MathService static step methods */