swf-runtime 1.0.0-alpha8

Runtime engine for Serverless Workflow DSL — execute, validate, and orchestrate workflows
Documentation
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
use super::*;

#[tokio::test]
async fn test_runner_workflow_input_schema_valid() {
    let output = run_workflow_from_yaml(
        &testdata("workflow_input_schema.yaml"),
        json!({"key": "testValue"}),
    )
    .await
    .unwrap();
    assert_eq!(output["outputKey"], json!("testValue"));
}

#[tokio::test]
async fn test_runner_workflow_input_schema_invalid() {
    let result = run_workflow_from_yaml(
        &testdata("workflow_input_schema.yaml"),
        json!({"wrongKey": "testValue"}),
    )
    .await;
    assert!(result.is_err());
}

// === Switch Then Loop ===

#[tokio::test]
async fn test_runner_workflow_output_schema_valid() {
    let output = run_workflow_from_yaml(&testdata("workflow_output_schema.yaml"), json!({}))
        .await
        .unwrap();
    assert_eq!(output["result"], json!("success"));
}

// === Workflow Output Schema: invalid ===

#[tokio::test]
async fn test_runner_workflow_output_schema_invalid() {
    let result =
        run_workflow_from_yaml(&testdata("workflow_output_schema_invalid.yaml"), json!({})).await;
    assert!(
        result.is_err(),
        "Expected error due to output schema validation failure"
    );
}

// === HTTP Call: with custom headers ===

#[tokio::test]
async fn test_runner_workflow_output_as() {
    let output = run_workflow_from_yaml(&testdata("workflow_output_as.yaml"), json!({}))
        .await
        .unwrap();
    // output.as: .result should extract just the result value
    assert_eq!(output, json!("hello"));
}

// === Nested try-catch ===

#[tokio::test]
async fn test_runner_sub_workflow_output_export_and_set() {
    // Child workflow: set task with output.as + export.as
    let child_yaml = r#"
document:
  dsl: '1.0.0'
  namespace: default
  name: set-into-context
  version: '1.0.0'
do:
  - updateUser:
      set:
        updated:
          userId: '${ .userId + "_tested" }'
          username: '${ .username + "_tested" }'
      output:
        as: .updated
      export:
        as: '.'
"#;
    let child: WorkflowDefinition = serde_yaml::from_str(child_yaml).unwrap();

    // Parent workflow: calls child with input, then reads exported context
    let parent_yaml = r#"
document:
  dsl: '1.0.0'
  namespace: default
  name: parent
  version: '1.0.0'
do:
  - sayHello:
      run:
        workflow:
          namespace: default
          name: set-into-context
          version: '1.0.0'
          input:
            userId: '123'
            username: 'alice'
"#;
    let parent: WorkflowDefinition = serde_yaml::from_str(parent_yaml).unwrap();

    let runner = WorkflowRunner::new(parent)
        .unwrap()
        .with_sub_workflow(child);

    let output = runner.run(json!({})).await.unwrap();
    assert_eq!(output["userId"], json!("123_tested"));
    assert_eq!(output["username"], json!("alice_tested"));
}

/// Java SDK's read-context-and-set-sub-workflow pattern
/// Child reads $workflow.definition.document.name/version in its expression
#[tokio::test]
async fn test_runner_sub_workflow_read_context_and_set() {
    let child_yaml = r#"
document:
  dsl: '1.0.0'
  namespace: default
  name: set-into-context
  version: '1.0.0'
do:
  - updateUser:
      set:
        updated:
          userId: '${ .userId + "_tested" }'
          username: '${ .username + "_tested" }'
          password: '${ .password + "_tested" }'
        detail: '${ "The workflow " + $workflow.definition.document.name + ":" + $workflow.definition.document.version + " updated user in context" }'
      export:
        as: '.'
"#;
    let child: WorkflowDefinition = serde_yaml::from_str(child_yaml).unwrap();

    let parent_yaml = r#"
document:
  dsl: '1.0.0'
  namespace: default
  name: parent
  version: '1.0.0'
do:
  - sayHello:
      run:
        workflow:
          namespace: default
          name: set-into-context
          version: '1.0.0'
          input:
            userId: '123'
            username: 'alice'
            password: 'secret'
"#;
    let parent: WorkflowDefinition = serde_yaml::from_str(parent_yaml).unwrap();

    let runner = WorkflowRunner::new(parent)
        .unwrap()
        .with_sub_workflow(child);

    let output = runner.run(json!({})).await.unwrap();
    assert_eq!(output["updated"]["userId"], json!("123_tested"));
    assert_eq!(output["updated"]["username"], json!("alice_tested"));
    assert_eq!(output["updated"]["password"], json!("secret_tested"));
    // Verify $workflow context is correct inside the sub-workflow
    let detail = output["detail"].as_str();
    assert!(
        detail.is_some(),
        "detail field missing, output: {:?}",
        output
    );
    assert!(detail.unwrap().contains("set-into-context"));
    assert!(detail.unwrap().contains("1.0.0"));
}

// === HTTP Call: OIDC client_credentials ===

#[tokio::test]
async fn test_runner_workflow_input_transform() {
    let output = run_workflow_from_yaml(
        &testdata("conditional_logic_input_from.yaml"),
        json!({"localWeather": {"temperature": 30}}),
    )
    .await
    .unwrap();
    // input.from should transform the input
    assert_eq!(output["weather"], json!("hot"));
}

// === Fork: compete mode returns first completed branch ===

#[tokio::test]
async fn test_runner_workflow_output_complex_transform() {
    let yaml_str = r#"
document:
  dsl: '1.0.0'
  namespace: test
  name: workflow-output-complex
  version: '0.1.0'
do:
  - buildResult:
      set:
        items:
          - name: Alice
            score: 95
          - name: Bob
            score: 85
output:
  as: "${ {topScorer: .items[0].name, count: (.items | length)} }"
"#;
    let output = run_workflow_yaml(&yaml_str, json!({})).await.unwrap();
    assert_eq!(output["topScorer"], json!("Alice"));
    assert_eq!(output["count"], json!(2));
}

// === Workflow input: complex transformation ===

#[tokio::test]
async fn test_runner_workflow_input_complex_transform() {
    let yaml_str = r#"
document:
  dsl: '1.0.0'
  namespace: test
  name: workflow-input-complex
  version: '0.1.0'
input:
  from: "${ {name: .rawName, age: .rawAge} }"
do:
  - useInput:
      set:
        result: "${ .name + \" is \" + (.age | tostring) }"
"#;
    let runner = WorkflowRunner::new(serde_yaml::from_str(&yaml_str).unwrap()).unwrap();

    let output = runner
        .run(json!({"rawName": "Alice", "rawAge": 30}))
        .await
        .unwrap();
    assert_eq!(output["result"], json!("Alice is 30"));
}

// === Workflow timeout: workflow exceeds timeout ===

#[tokio::test]
async fn test_runner_workflow_timeout_exceeded() {
    let yaml_str = r#"
document:
  dsl: '1.0.0'
  namespace: test
  name: workflow-timeout
  version: '0.1.0'
timeout:
  after: PT0.01S
do:
  - slowTask:
      wait: PT5S
"#;
    let runner = WorkflowRunner::new(serde_yaml::from_str(&yaml_str).unwrap()).unwrap();

    let result = runner.run(json!({})).await;
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert_eq!(err.error_type_short(), "timeout");
}

// === Workflow timeout: completes within timeout ===

#[tokio::test]
async fn test_runner_workflow_timeout_not_exceeded() {
    let yaml_str = r#"
document:
  dsl: '1.0.0'
  namespace: test
  name: workflow-timeout-ok
  version: '0.1.0'
timeout:
  after: PT0.01S
do:
  - quickTask:
      set:
        result: done
"#;
    let output = run_workflow_yaml(&yaml_str, json!({})).await.unwrap();
    assert_eq!(output["result"], json!("done"));
}

// === Workflow timeout: reference to reusable timeout ===

#[tokio::test]
async fn test_runner_workflow_timeout_reference() {
    let yaml_str = r#"
document:
  dsl: '1.0.0'
  namespace: test
  name: workflow-timeout-ref
  version: '0.1.0'
use:
  timeouts:
    shortTimeout:
      after: PT0.01S
timeout: shortTimeout
do:
  - slowTask:
      wait: PT5S
"#;
    let runner = WorkflowRunner::new(serde_yaml::from_str(&yaml_str).unwrap()).unwrap();

    let result = runner.run(json!({})).await;
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert_eq!(err.error_type_short(), "timeout");
}

// === Workflow timeout with try-catch ===

#[tokio::test]
async fn test_runner_workflow_timeout_try_catch() {
    let yaml_str = r#"
document:
  dsl: '1.0.0'
  namespace: test
  name: workflow-timeout-try-catch
  version: '0.1.0'
timeout:
  after: PT0.01S
do:
  - safeBlock:
      try:
        - slowTask:
            wait: PT5S
      catch:
        errors:
          with:
            type: timeout
        do:
          - handleTimeout:
              set:
                timedOut: true
"#;
    let runner = WorkflowRunner::new(serde_yaml::from_str(&yaml_str).unwrap()).unwrap();

    // Workflow-level timeout is applied outside try-catch, so it should still timeout
    let result = runner.run(json!({})).await;
    assert!(result.is_err());
    assert_eq!(result.unwrap_err().error_type_short(), "timeout");
}

// === Workflow timeout: dynamic expression ===

#[tokio::test]
async fn test_runner_workflow_input_from_output_as() {
    let yaml_str = r#"
document:
  dsl: '1.0.0'
  namespace: test
  name: workflow-input-from-output-as
  version: '0.1.0'
input:
  from: "${ {name: .rawName, age: .rawAge} }"
output:
  as: "${ {greeting: (\"Hello \" + .name), yearsOld: .age} }"
do:
  - useInput:
      set:
        name: "${ .name }"
        age: "${ .age }"
"#;
    let runner = WorkflowRunner::new(serde_yaml::from_str(&yaml_str).unwrap()).unwrap();

    let output = runner
        .run(json!({"rawName": "Alice", "rawAge": 30}))
        .await
        .unwrap();
    assert_eq!(output["greeting"], json!("Hello Alice"));
    assert_eq!(output["yearsOld"], json!(30));
}

// === Try-catch: retry with reference to reusable retry policy ===

#[tokio::test]
async fn test_runner_workflow_input_output_schema_combined() {
    // Use testdata file for valid input, verify it works with both input+output schema
    let output = run_workflow_from_yaml(
        &testdata("workflow_input_schema.yaml"),
        json!({"key": "test"}),
    )
    .await
    .unwrap();
    assert_eq!(output["outputKey"], json!("test"));
}

#[tokio::test]
async fn test_runner_workflow_input_output_schema_invalid_input() {
    // Verify existing testdata file rejects invalid input
    let result = run_workflow_from_yaml(
        &testdata("workflow_input_schema.yaml"),
        json!({"wrongKey": "testValue"}),
    )
    .await;
    assert!(
        result.is_err(),
        "Should fail with missing required field 'key'"
    );
}

// === Nested do with then:exit continues at outer scope ===

// Workflow: input.from + output.as combined
#[tokio::test]
async fn test_runner_workflow_input_output_combo() {
    let yaml_str = r#"
document:
  dsl: '1.0.0'
  namespace: test
  name: workflow-input-output-combo
  version: '0.1.0'
input:
  from: "${ {x: .a, y: .b} }"
output:
  as: "${ {result: .sum} }"
do:
  - compute:
      set:
        sum: "${ .x + .y }"
        x: "${ .x }"
        y: "${ .y }"
"#;
    let output = run_workflow_yaml(&yaml_str, json!({"a": 3, "b": 7}))
        .await
        .unwrap();
    assert_eq!(output["result"], json!(10));
}

#[tokio::test]
async fn test_runner_workflow_output_as_sequential_colors() {
    // Go SDK's sequential_set_colors_output_as.yaml pattern
    let yaml_str = r#"
document:
  dsl: '1.0.0'
  namespace: test
  name: sequential-colors-output-as
  version: '0.1.0'
do:
  - setRed:
      set:
        colors: ${ .colors + ["red"] }
  - setGreen:
      set:
        colors: ${ .colors + ["green"] }
  - setBlue:
      set:
        colors: ${ .colors + ["blue"] }
output:
  as: "${ { result: .colors } }"
"#;
    let output = run_workflow_yaml(&yaml_str, json!({"colors": []}))
        .await
        .unwrap();
    // workflow-level output.as transforms the final result
    assert_eq!(output["result"], json!(["red", "green", "blue"]));
}

#[tokio::test]
async fn test_runner_sub_workflow_basic() {
    // Parent workflow invokes child workflow via run: workflow
    let parent_yaml = std::fs::read_to_string(testdata("sub_workflow_parent.yaml")).unwrap();
    let child_yaml = std::fs::read_to_string(testdata("sub_workflow_child.yaml")).unwrap();

    let parent: WorkflowDefinition = serde_yaml::from_str(&parent_yaml).unwrap();
    let child: WorkflowDefinition = serde_yaml::from_str(&child_yaml).unwrap();

    let runner = WorkflowRunner::new(parent)
        .unwrap()
        .with_sub_workflow(child);

    let output = runner.run(json!({})).await.unwrap();
    assert_eq!(output["counter"], json!(1));
    assert_eq!(output["greeting"], json!("helloWorld"));
}

#[tokio::test]
async fn test_runner_sub_workflow_not_found() {
    // Parent references a sub-workflow that is not registered
    let parent_yaml = std::fs::read_to_string(testdata("sub_workflow_parent.yaml")).unwrap();
    let parent: WorkflowDefinition = serde_yaml::from_str(&parent_yaml).unwrap();

    let runner = WorkflowRunner::new(parent).unwrap();
    // No child workflow registered — should error
    let result = runner.run(json!({})).await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("not found in registry"),
        "Expected 'not found in registry', got: {}",
        err
    );
}

#[tokio::test]
async fn test_runner_sub_workflow_with_export() {
    // Sub-workflow uses output.as and export.as — output should be transformed
    let parent_yaml = std::fs::read_to_string(testdata("sub_workflow_export_parent.yaml")).unwrap();
    let child_yaml = std::fs::read_to_string(testdata("sub_workflow_export_child.yaml")).unwrap();

    let parent: WorkflowDefinition = serde_yaml::from_str(&parent_yaml).unwrap();
    let child: WorkflowDefinition = serde_yaml::from_str(&child_yaml).unwrap();

    let runner = WorkflowRunner::new(parent)
        .unwrap()
        .with_sub_workflow(child);

    let input = json!({
        "userId": "userId_1",
        "username": "test",
        "password": "test"
    });
    let output = runner.run(input).await.unwrap();
    assert_eq!(output["userId"], json!("userId_1_tested"));
    assert_eq!(output["username"], json!("test_tested"));
    assert_eq!(output["password"], json!("test_tested"));
}

#[tokio::test]
async fn test_runner_sub_workflow_inline() {
    // Test sub-workflow defined inline (no testdata files)
    let child_yaml = r#"
document:
  dsl: '1.0.0'
  namespace: test
  name: child
  version: '1.0.0'
do:
  - doubleIt:
      set:
        result: '${ .value * 2 }'
"#;
    let parent_yaml = r#"
document:
  dsl: '1.0.0'
  namespace: test
  name: parent-inline
  version: '1.0.0'
do:
  - callChild:
      run:
        workflow:
          namespace: test
          name: child
          version: '1.0.0'
"#;

    let parent: WorkflowDefinition = serde_yaml::from_str(parent_yaml).unwrap();
    let child: WorkflowDefinition = serde_yaml::from_str(child_yaml).unwrap();

    let runner = WorkflowRunner::new(parent)
        .unwrap()
        .with_sub_workflow(child);

    let output = runner.run(json!({"value": 21})).await.unwrap();
    assert_eq!(output["result"], json!(42));
}

#[tokio::test]
async fn test_runner_sub_workflow_read_context_from_fixtures() {
    // Test $workflow.definition variable access in sub-workflow using YAML fixtures
    let parent_yaml =
        std::fs::read_to_string(testdata("sub_workflow_read_context_parent.yaml")).unwrap();
    let child_yaml =
        std::fs::read_to_string(testdata("sub_workflow_read_context_child.yaml")).unwrap();

    let parent: WorkflowDefinition = serde_yaml::from_str(&parent_yaml).unwrap();
    let child: WorkflowDefinition = serde_yaml::from_str(&child_yaml).unwrap();

    let runner = WorkflowRunner::new(parent)
        .unwrap()
        .with_sub_workflow(child);

    let output = runner.run(json!({})).await.unwrap();
    assert_eq!(output["updated"]["userId"], json!("123_tested"));
    assert_eq!(output["updated"]["username"], json!("alice_tested"));
    assert_eq!(output["updated"]["password"], json!("secret_tested"));
    let detail = output["detail"].as_str();
    assert!(
        detail.is_some(),
        "detail field missing, output: {:?}",
        output
    );
    assert!(detail.unwrap().contains("set-into-context"));
    assert!(detail.unwrap().contains("1.0.0"));
}

// ---- CallHandler and RunHandler Tests ----