-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathe2e_samples.rs
More file actions
2699 lines (2384 loc) · 102 KB
/
Copy pathe2e_samples.rs
File metadata and controls
2699 lines (2384 loc) · 102 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//! End-to-end samples: start here to learn the API by example.
//!
//! Each test demonstrates a common orchestration pattern using
//! `OrchestrationContext` and the in-process `Runtime`.
#![allow(clippy::unwrap_used)]
#![allow(clippy::clone_on_ref_ptr)]
#![allow(clippy::expect_used)]
use duroxide::EventKind;
use duroxide::runtime::registry::ActivityRegistry;
use duroxide::runtime::{self};
use duroxide::{ActivityContext, Client, Either2, OrchestrationContext, OrchestrationRegistry};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Duration;
mod common;
/// Hello World: define one activity and call it from an orchestrator.
///
/// Highlights:
/// - Register an activity in an `ActivityRegistry`
/// - Start the `Runtime` with a provider (filesystem here)
/// - Schedule an activity and await its typed completion
#[tokio::test]
async fn sample_hello_world_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
// Register a simple activity: "Hello" -> format a greeting
let activity_registry = ActivityRegistry::builder()
.register("Hello", |ctx: ActivityContext, input: String| async move {
ctx.trace_info("Hello activity started");
let greeting = format!("Hello, {input}!");
ctx.trace_info(format!("Hello activity completed -> {greeting}"));
Ok(greeting)
})
.build();
// Orchestrator: emit a trace, call Hello twice, return result using input
let orchestration = |ctx: OrchestrationContext, input: String| async move {
ctx.trace_info("hello_world started");
let res = ctx.schedule_activity("Hello", "Rust").await?;
ctx.trace_info(format!("hello_world result={res} "));
let res1 = ctx.schedule_activity("Hello", input).await?;
ctx.trace_info(format!("hello_world result={res1} "));
Ok(res1)
};
let orchestration_registry = OrchestrationRegistry::builder()
.register("HelloWorld", orchestration)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client
.start_orchestration("inst-sample-hello-1", "HelloWorld", "World")
.await
.unwrap();
match client
.wait_for_orchestration("inst-sample-hello-1", std::time::Duration::from_secs(5))
.await
.unwrap()
{
runtime::OrchestrationStatus::Completed { output, .. } => assert_eq!(output, "Hello, World!"),
runtime::OrchestrationStatus::Failed { details, .. } => {
panic!("orchestration failed: {}", details.display_message())
}
_ => panic!("unexpected orchestration status"),
}
rt.shutdown(None).await;
}
/// Basic control flow: branch on a flag returned by an activity.
///
/// Highlights:
/// - Call an activity to fetch a decision
/// - Use standard Rust control flow to drive subsequent activities
#[tokio::test]
async fn sample_basic_control_flow_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
// Register activities that return a flag and branch outcomes
let activity_registry = ActivityRegistry::builder()
.register("GetFlag", |_ctx: ActivityContext, _input: String| async move {
Ok("yes".to_string())
})
.register("SayYes", |_ctx: ActivityContext, _in: String| async move {
Ok("picked_yes".to_string())
})
.register("SayNo", |_ctx: ActivityContext, _in: String| async move {
Ok("picked_no".to_string())
})
.build();
// Orchestrator: get a flag and branch
let orchestration = |ctx: OrchestrationContext, _input: String| async move {
let flag = ctx.schedule_activity("GetFlag", "").await.unwrap();
ctx.trace_info(format!("control_flow flag decided = {flag}"));
if flag == "yes" {
Ok(ctx.schedule_activity("SayYes", "").await.unwrap())
} else {
Ok(ctx.schedule_activity("SayNo", "").await.unwrap())
}
};
let orchestration_registry = OrchestrationRegistry::builder()
.register("ControlFlow", orchestration)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client
.start_orchestration("inst-sample-cflow-1", "ControlFlow", "")
.await
.unwrap();
match client
.wait_for_orchestration("inst-sample-cflow-1", std::time::Duration::from_secs(5))
.await
.unwrap()
{
runtime::OrchestrationStatus::Completed { output, .. } => assert_eq!(output, "picked_yes"),
runtime::OrchestrationStatus::Failed { details, .. } => {
panic!("orchestration failed: {}", details.display_message())
}
_ => panic!("unexpected orchestration status"),
}
rt.shutdown(None).await;
}
/// Loops and accumulation: call an activity repeatedly and build up a value.
///
/// Highlights:
/// - Use a for-loop in the orchestrator
/// - Emit replay-safe traces per iteration
#[tokio::test]
async fn sample_loop_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
// Register an activity that appends "x" to its input
let activity_registry = ActivityRegistry::builder()
.register("Append", |_ctx: ActivityContext, input: String| async move {
Ok(format!("{input}x"))
})
.build();
// Orchestrator: loop three times, updating an accumulator
let orchestration = |ctx: OrchestrationContext, _input: String| async move {
let mut acc = String::from("start");
for i in 0..3 {
acc = ctx.schedule_activity("Append", acc).await.unwrap();
ctx.trace_info(format!("loop iteration {i} completed acc={acc}"));
}
Ok(acc)
};
let orchestration_registry = OrchestrationRegistry::builder()
.register("LoopOrchestration", orchestration)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client
.start_orchestration("inst-sample-loop-1", "LoopOrchestration", "")
.await
.unwrap();
match client
.wait_for_orchestration("inst-sample-loop-1", std::time::Duration::from_secs(5))
.await
.unwrap()
{
runtime::OrchestrationStatus::Completed { output, .. } => assert_eq!(output, "startxxx"),
runtime::OrchestrationStatus::Failed { details, .. } => {
panic!("orchestration failed: {}", details.display_message())
}
_ => panic!("unexpected orchestration status"),
}
rt.shutdown(None).await;
}
/// Error handling and compensation: recover from a failed activity.
///
/// Highlights:
/// - Activities return `Result<String, String>` and map into `Ok/Err`
/// - On failure, run a compensating activity and log what happened
#[tokio::test]
async fn sample_error_handling_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
// Register a fragile activity that may fail, and a recovery activity
let activity_registry = ActivityRegistry::builder()
.register("Fragile", |_ctx: ActivityContext, input: String| async move {
if input == "bad" {
Err("boom".to_string())
} else {
Ok("ok".to_string())
}
})
.register("Recover", |_ctx: ActivityContext, _input: String| async move {
Ok("recovered".to_string())
})
.build();
// Orchestrator: try fragile, on error call Recover
let orchestration = |ctx: OrchestrationContext, _input: String| async move {
match ctx.schedule_activity("Fragile", "bad").await {
Ok(v) => {
ctx.trace_info(format!("fragile succeeded value={v}"));
Ok(v)
}
Err(e) => {
ctx.trace_warn(format!("fragile failed error={e}"));
let rec = ctx.schedule_activity("Recover", "").await.unwrap();
if rec != "recovered" {
ctx.trace_error(format!("unexpected recovery value={rec}"));
}
Ok(rec)
}
}
};
let orchestration_registry = OrchestrationRegistry::builder()
.register("ErrorHandling", orchestration)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client
.start_orchestration("inst-sample-err-1", "ErrorHandling", "")
.await
.unwrap();
match client
.wait_for_orchestration("inst-sample-err-1", std::time::Duration::from_secs(5))
.await
.unwrap()
{
runtime::OrchestrationStatus::Completed { output, .. } => assert_eq!(output, "recovered"),
runtime::OrchestrationStatus::Failed { details, .. } => {
panic!("orchestration failed: {}", details.display_message())
}
_ => panic!("unexpected orchestration status"),
}
rt.shutdown(None).await;
}
/// Timeouts via racing a long-running activity against a timer.
///
/// Highlights:
/// - Schedule a long-running activity and a short timer
/// - Use `ctx.select` to deterministically pick the earliest completion in history
/// - If the timer wins, return an error to the user
#[tokio::test]
async fn sample_timeout_with_timer_race_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
// Register a long-running activity that sleeps before returning
let activity_registry = ActivityRegistry::builder()
.register("LongOp", |ctx: ActivityContext, _input: String| async move {
ctx.trace_info("LongOp started");
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
ctx.trace_info("LongOp finished");
Ok("done".to_string())
})
.build();
// Orchestration: race LongOp vs 100ms timer and error if timer wins
let orchestration = |ctx: OrchestrationContext, _input: String| async move {
let act = ctx.schedule_activity("LongOp", "");
let t = async {
ctx.schedule_timer(Duration::from_millis(100)).await;
Err::<String, String>("timeout".into())
};
let (idx, out) = ctx.select2(act, t).await.into_tuple();
match idx {
0 => out,
1 => out,
_ => unreachable!(),
}
};
let orchestration_registry = OrchestrationRegistry::builder()
.register("TimeoutSample", orchestration)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client
.start_orchestration("inst-timeout-sample", "TimeoutSample", "")
.await
.unwrap();
match client
.wait_for_orchestration("inst-timeout-sample", std::time::Duration::from_secs(5))
.await
.unwrap()
{
runtime::OrchestrationStatus::Failed { details, .. } => assert_eq!(details.display_message(), "timeout"),
runtime::OrchestrationStatus::Completed { output, .. } => panic!("expected timeout failure, got: {output}"),
_ => panic!("unexpected orchestration status"),
}
rt.shutdown(None).await;
}
/// Mixed race with select2: activity vs external event, demonstrate using the winner index.
///
/// Highlights:
/// - Schedule a slow activity and subscribe to an external event
/// - Use `ctx.select2(activity, external)` to pick the earliest completion
/// - Use the usize index from select2 to branch on which completed first
#[tokio::test]
async fn sample_select2_activity_vs_external_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
let activity_registry = ActivityRegistry::builder()
.register("Sleep", |ctx: ActivityContext, _input: String| async move {
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
ctx.trace_info("Sleep activity finished");
Ok("slept".to_string())
})
.build();
let orchestration = |ctx: OrchestrationContext, _input: String| async move {
let act = ctx.schedule_activity("Sleep", "");
let evt = async { Ok::<String, String>(ctx.schedule_wait("Go").await) };
let (idx, out) = ctx.select2(act, evt).await.into_tuple();
// Demonstrate using the index to branch
match idx {
0 => out.map(|s| format!("activity:{s}")),
1 => out.map(|payload| format!("event:{payload}")),
_ => unreachable!(),
}
};
let orchestration_registry = OrchestrationRegistry::builder()
.register("Select2ActVsEvt", orchestration)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
// Start orchestration, then raise external after subscription is recorded
let store_for_wait = store.clone();
tokio::spawn(async move {
let sfw = store_for_wait.clone();
let _ = common::wait_for_subscription(sfw.clone(), "inst-s2-mixed", "Go", 1000).await;
let client = Client::new(sfw);
let _ = client.raise_event("inst-s2-mixed", "Go", "ok").await;
});
let client = Client::new(store.clone());
client
.start_orchestration("inst-s2-mixed", "Select2ActVsEvt", "")
.await
.unwrap();
let s = match client
.wait_for_orchestration("inst-s2-mixed", std::time::Duration::from_secs(5))
.await
.unwrap()
{
runtime::OrchestrationStatus::Completed { output, .. } => output,
runtime::OrchestrationStatus::Failed { details, .. } => {
panic!("orchestration failed: {}", details.display_message())
}
_ => panic!("unexpected orchestration status"),
};
// External event should win (idx==1) because activity sleeps 300ms
assert_eq!(s, "event:ok");
rt.shutdown(None).await;
}
/// Parallel fan-out/fan-in: run two activities concurrently and join results.
///
/// Highlights:
/// - Use `ctx.join` to await multiple `DurableFuture`s concurrently in history order
/// - Deterministic replay ensures join order follows history
#[tokio::test]
async fn dtf_legacy_gabbar_greetings_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
// Register a greeting activity used by both branches
let activity_registry = ActivityRegistry::builder()
.register("Greetings", |ctx: ActivityContext, input: String| async move {
ctx.trace_info("Greeting activity started");
ctx.trace_debug(format!("Original input: {input}"));
let output = format!("Hello, {input}!");
ctx.trace_info(format!("Greeting activity completed -> {output}"));
Ok(output)
})
.build();
let orchestration = |ctx: OrchestrationContext, _input: String| async move {
// Schedule two greetings in parallel using deterministic join
let a = ctx.schedule_activity("Greetings", "Gabbar");
let b = ctx.schedule_activity("Greetings", "Samba");
let outs = ctx.join(vec![a, b]).await;
let mut vals: Vec<String> = outs
.into_iter()
.map(|o| match o {
Ok(s) => s,
Err(e) => panic!("activity failed: {e}"),
})
.collect();
// For a stable assertion build a canonical order
vals.sort();
Ok(format!("{}, {}", vals[0].clone(), vals[1].clone()))
};
let orchestration_registry = OrchestrationRegistry::builder()
.register("Greetings", orchestration)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client
.start_orchestration("inst-dtf-greetings", "Greetings", "")
.await
.unwrap();
match client
.wait_for_orchestration("inst-dtf-greetings", std::time::Duration::from_secs(5))
.await
.unwrap()
{
runtime::OrchestrationStatus::Completed { output, .. } => assert_eq!(output, "Hello, Gabbar!, Hello, Samba!"),
runtime::OrchestrationStatus::Failed { details, .. } => {
panic!("orchestration failed: {}", details.display_message())
}
_ => panic!("unexpected orchestration status"),
}
rt.shutdown(None).await;
}
/// System activities: use built-in activities to get wall-clock time and a new GUID.
///
/// Highlights:
/// - Call `ctx.utc_now()` and `ctx.new_guid()`
/// - Log and validate basic formatting of results
#[tokio::test]
async fn sample_system_activities_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
let activity_registry = ActivityRegistry::builder().build();
let orchestration = |ctx: OrchestrationContext, _input: String| async move {
let now = ctx.utc_now().await?;
let guid = ctx.new_guid().await?;
// Convert SystemTime to milliseconds for display
let now_ms = now
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| e.to_string())?
.as_millis() as u64;
ctx.trace_info(format!("system now={now_ms}ms, guid={guid}"));
Ok(format!("n={now_ms},g={guid}"))
};
let orchestration_registry = OrchestrationRegistry::builder()
.register("SystemActivities", orchestration)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client
.start_orchestration("inst-system-acts", "SystemActivities", "")
.await
.unwrap();
let out = match client
.wait_for_orchestration("inst-system-acts", std::time::Duration::from_secs(5))
.await
.unwrap()
{
runtime::OrchestrationStatus::Completed { output, .. } => output,
runtime::OrchestrationStatus::Failed { details, .. } => {
panic!("orchestration failed: {}", details.display_message())
}
_ => panic!("unexpected orchestration status"),
};
// Basic assertions
assert!(out.contains("n=") && out.contains(",g="));
let parts: Vec<&str> = out.split([',', '=']).collect();
// parts like ["n", now, "g", guid]
assert!(parts.len() >= 4);
let now_val: u64 = parts[1].parse().unwrap_or(0);
let guid_str = parts[3];
assert!(now_val > 0);
// GUID format: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" (36 chars with hyphens)
assert_eq!(guid_str.len(), 36);
assert!(guid_str.chars().filter(|c| *c != '-').all(|c| c.is_ascii_hexdigit()));
rt.shutdown(None).await;
}
/// Sample: start an orchestration and poll its status until completion.
#[tokio::test]
async fn sample_status_polling_fs() {
use duroxide::OrchestrationStatus;
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
let activity_registry = ActivityRegistry::builder().build();
let orchestration = |ctx: OrchestrationContext, _input: String| async move {
ctx.schedule_timer(Duration::from_millis(20)).await;
Ok("done".to_string())
};
let orchestration_registry = OrchestrationRegistry::builder()
.register("StatusSample", orchestration)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client
.start_orchestration("inst-status-sample", "StatusSample", "")
.await
.unwrap();
// New helper: wait until terminal (Completed/Failed) or timeout.
match client
.wait_for_orchestration("inst-status-sample", std::time::Duration::from_secs(2))
.await
.unwrap()
{
OrchestrationStatus::Completed { output, .. } => assert_eq!(output, "done"),
OrchestrationStatus::Failed { details, .. } => panic!("unexpected failure: {}", details.display_message()),
_ => unreachable!(),
}
rt.shutdown(None).await;
}
/// Sub-orchestrations: simple parent/child orchestration.
///
/// Highlights:
/// - Parent calls a child orchestration and awaits its result
/// - Child uses an activity and returns its output
#[tokio::test]
async fn sample_sub_orchestration_basic_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
let activity_registry = ActivityRegistry::builder()
.register("Upper", |ctx: ActivityContext, input: String| async move {
ctx.trace_info("Upper activity converting string");
let result = input.to_uppercase();
ctx.trace_info(format!("Upper activity result -> {result}"));
Ok(result)
})
.build();
let child_upper = |ctx: OrchestrationContext, input: String| async move {
let up = ctx.schedule_activity("Upper", input).await.unwrap();
Ok(up)
};
let parent = |ctx: OrchestrationContext, input: String| async move {
let r = ctx.schedule_sub_orchestration("ChildUpper", input).await.unwrap();
Ok(format!("parent:{r}"))
};
let orchestration_registry = OrchestrationRegistry::builder()
.register("ChildUpper", child_upper)
.register("Parent", parent)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client
.start_orchestration("inst-sub-basic", "Parent", "hi")
.await
.unwrap();
match client
.wait_for_orchestration("inst-sub-basic", std::time::Duration::from_secs(5))
.await
.unwrap()
{
runtime::OrchestrationStatus::Completed { output, .. } => assert_eq!(output, "parent:HI"),
runtime::OrchestrationStatus::Failed { details, .. } => {
panic!("orchestration failed: {}", details.display_message())
}
_ => panic!("unexpected orchestration status"),
}
rt.shutdown(None).await;
}
/// Sub-orchestrations: fan-out to multiple children and join.
///
/// Highlights:
/// - Parent starts two child orchestrations in parallel
/// - Uses `ctx.join` to await both in history order and aggregates results
#[tokio::test]
async fn sample_sub_orchestration_fanout_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
let activity_registry = ActivityRegistry::builder()
.register("Add", |_ctx: ActivityContext, input: String| async move {
let mut it = input.split(',');
let a = it.next().unwrap_or("0").parse::<i64>().unwrap_or(0);
let b = it.next().unwrap_or("0").parse::<i64>().unwrap_or(0);
Ok((a + b).to_string())
})
.build();
let child_sum = |ctx: OrchestrationContext, input: String| async move {
let s = ctx.schedule_activity("Add", input).await.unwrap();
Ok(s)
};
let parent = |ctx: OrchestrationContext, _input: String| async move {
let a = ctx.schedule_sub_orchestration("ChildSum", "1,2");
let b = ctx.schedule_sub_orchestration("ChildSum", "3,4");
let outs = ctx.join(vec![a, b]).await;
let mut nums: Vec<i64> = outs
.into_iter()
.map(|o| match o {
Ok(s) => s.parse::<i64>().unwrap(),
Err(e) => panic!("child failed: {e}"),
})
.collect();
let total: i64 = nums.drain(..).sum();
Ok(format!("total={total}"))
};
let orchestration_registry = OrchestrationRegistry::builder()
.register("ChildSum", child_sum)
.register("ParentFan", parent)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client
.start_orchestration("inst-sub-fan", "ParentFan", "")
.await
.unwrap();
match client
.wait_for_orchestration("inst-sub-fan", std::time::Duration::from_secs(10))
.await
.unwrap()
{
runtime::OrchestrationStatus::Completed { output, .. } => assert_eq!(output, "total=10"),
runtime::OrchestrationStatus::Failed { details, .. } => {
panic!("orchestration failed: {}", details.display_message())
}
_ => panic!("unexpected orchestration status"),
}
rt.shutdown(None).await;
}
/// Sub-orchestrations: chained (root -> mid -> leaf).
///
/// Highlights:
/// - Root calls Mid; Mid calls Leaf; each returns a transformed value
/// - Demonstrates nested sub-orchestrations
#[tokio::test]
async fn sample_sub_orchestration_chained_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
let activity_registry = ActivityRegistry::builder()
.register("AppendX", |_ctx: ActivityContext, input: String| async move {
Ok(format!("{input}x"))
})
.build();
let leaf = |ctx: OrchestrationContext, input: String| async move {
Ok(ctx.schedule_activity("AppendX", input).await.unwrap())
};
let mid = |ctx: OrchestrationContext, input: String| async move {
let r = ctx.schedule_sub_orchestration("Leaf", input).await.unwrap();
Ok(format!("{r}-mid"))
};
let root = |ctx: OrchestrationContext, input: String| async move {
let r = ctx.schedule_sub_orchestration("Mid", input).await.unwrap();
Ok(format!("root:{r}"))
};
let orchestration_registry = OrchestrationRegistry::builder()
.register("Leaf", leaf)
.register("Mid", mid)
.register("Root", root)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client.start_orchestration("inst-sub-chain", "Root", "a").await.unwrap();
match client
.wait_for_orchestration("inst-sub-chain", std::time::Duration::from_secs(5))
.await
.unwrap()
{
runtime::OrchestrationStatus::Completed { output, .. } => assert_eq!(output, "root:ax-mid"),
runtime::OrchestrationStatus::Failed { details, .. } => {
panic!("orchestration failed: {}", details.display_message())
}
_ => panic!("unexpected orchestration status"),
}
rt.shutdown(None).await;
}
/// Detached orchestration scheduling: start independent orchestrations without awaiting.
///
/// Highlights:
/// - Use `ctx.schedule_orchestration(name, instance, input)` with explicit instance IDs
/// - No parent/child semantics; scheduled orchestrations are independent roots
/// - Verify scheduled instances complete via status polling
#[tokio::test]
async fn sample_detached_orchestration_scheduling_fs() {
use duroxide::OrchestrationStatus;
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
let activity_registry = ActivityRegistry::builder()
.register("Echo", |_ctx: ActivityContext, input: String| async move { Ok(input) })
.build();
let chained = |ctx: OrchestrationContext, input: String| async move {
ctx.schedule_timer(Duration::from_millis(5)).await;
Ok(ctx.schedule_activity("Echo", input).await.unwrap())
};
let coordinator = |ctx: OrchestrationContext, _input: String| async move {
ctx.schedule_orchestration("Chained", "W1", "A");
ctx.schedule_orchestration("Chained", "W2", "B");
Ok("scheduled".to_string())
};
let orchestration_registry = OrchestrationRegistry::builder()
.register("Chained", chained)
.register("Coordinator", coordinator)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client
.start_orchestration("CoordinatorRoot", "Coordinator", "")
.await
.unwrap();
match client
.wait_for_orchestration("CoordinatorRoot", std::time::Duration::from_secs(5))
.await
.unwrap()
{
runtime::OrchestrationStatus::Completed { output, .. } => assert_eq!(output, "scheduled"),
runtime::OrchestrationStatus::Failed { details, .. } => {
panic!("orchestration failed: {}", details.display_message())
}
_ => panic!("unexpected orchestration status"),
}
// The scheduled instances are plain W1/W2 (no prefixing)
let insts = vec!["W1".to_string(), "W2".to_string()];
for inst in insts {
match client
.wait_for_orchestration(&inst, std::time::Duration::from_secs(5))
.await
.unwrap()
{
OrchestrationStatus::Completed { output, .. } => {
assert!(output == "A" || output == "B");
}
OrchestrationStatus::Failed { details, .. } => {
panic!("scheduled orchestration failed: {}", details.display_message())
}
_ => unreachable!(),
}
}
rt.shutdown(None).await;
}
/// Detached orchestration followed by activity: tests that fire-and-forget scheduling
/// is correctly recorded in history for determinism on replay.
///
/// This test will fail with nondeterminism if OrchestrationChained events are not recorded,
/// because on replay the engine will try to match StartOrchestrationDetached action against
/// ActivityScheduled event.
///
/// Highlights:
/// - Fire-and-forget with `ctx.schedule_orchestration()` followed by awaited activity
/// - Verifies both the parent and child orchestrations complete correctly
#[tokio::test]
async fn sample_detached_then_activity_fs() {
use duroxide::OrchestrationStatus;
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
let activity_registry = ActivityRegistry::builder()
.register("Echo", |_ctx: ActivityContext, input: String| async move { Ok(input) })
.build();
let child = |ctx: OrchestrationContext, input: String| async move {
ctx.schedule_timer(Duration::from_millis(5)).await;
Ok(format!("child-{input}"))
};
let parent = |ctx: OrchestrationContext, _input: String| async move {
// Fire-and-forget: schedule detached orchestration
ctx.schedule_orchestration("Child", "detached-child", "payload");
// Then await an activity - this requires OrchestrationChained to be recorded
// for replay to work correctly
let result = ctx.schedule_activity("Echo", "hello").await?;
Ok(result)
};
let orchestration_registry = OrchestrationRegistry::builder()
.register("Child", child)
.register("Parent", parent)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client
.start_orchestration("ParentInstance", "Parent", "")
.await
.unwrap();
// Parent should complete with Echo result
match client
.wait_for_orchestration("ParentInstance", std::time::Duration::from_secs(5))
.await
.unwrap()
{
OrchestrationStatus::Completed { output, .. } => assert_eq!(output, "hello"),
OrchestrationStatus::Failed { details, .. } => {
panic!("parent orchestration failed: {}", details.display_message())
}
_ => panic!("unexpected orchestration status"),
}
// Child should also complete
match client
.wait_for_orchestration("detached-child", std::time::Duration::from_secs(5))
.await
.unwrap()
{
OrchestrationStatus::Completed { output, .. } => assert_eq!(output, "child-payload"),
OrchestrationStatus::Failed { details, .. } => {
panic!("child orchestration failed: {}", details.display_message())
}
_ => panic!("unexpected child status"),
}
rt.shutdown(None).await;
}
/// ContinueAsNew sample: roll over input across executions until a condition is met.
///
/// Highlights:
/// - Use `ctx.continue_as_new(new_input)` to terminate current execution and start a new one
/// - Provider keeps all execution histories; latest execution holds the final result
#[tokio::test]
async fn sample_continue_as_new_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
let activity_registry = ActivityRegistry::builder().build();
let orch = |ctx: OrchestrationContext, input: String| async move {
let n: u32 = input.parse().unwrap_or(0);
if n < 3 {
ctx.trace_info(format!("CAN sample n={n} -> continue"));
return ctx.continue_as_new((n + 1).to_string()).await;
} else {
Ok(format!("final:{n}"))
}
};
let orchestration_registry = OrchestrationRegistry::builder().register("CanSample", orch).build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client
.start_orchestration("inst-sample-can", "CanSample", "0")
.await
.unwrap();
match client
.wait_for_orchestration("inst-sample-can", std::time::Duration::from_secs(5))
.await
.unwrap()
{
runtime::OrchestrationStatus::Completed { output, .. } => assert_eq!(output, "final:3"),
runtime::OrchestrationStatus::Failed { details, .. } => {
panic!("orchestration failed: {}", details.display_message())
}
_ => panic!("unexpected orchestration status"),
}
// Check executions exist
let mgmt = store.as_management_capability().expect("ProviderAdmin required");
let execs = mgmt.list_executions("inst-sample-can").await.unwrap_or_default();
assert_eq!(execs, vec![1, 2, 3, 4]);
rt.shutdown(None).await;
}
// Typed samples
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct AddReq {
a: i32,
b: i32,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct AddRes {
sum: i32,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Ack {
ok: bool,
}
/// Typed activity + typed orchestration: Add two numbers and return a struct
#[tokio::test]
async fn sample_typed_activity_and_orchestration_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
let activity_registry = ActivityRegistry::builder()
.register_typed::<AddReq, AddRes, _, _>("Add", |_ctx: ActivityContext, req| async move {
Ok(AddRes { sum: req.a + req.b })
})
.build();
let orchestration = |ctx: OrchestrationContext, req: AddReq| async move {
let out: AddRes = ctx.schedule_activity_typed::<AddReq, AddRes>("Add", &req).await?;
Ok(out)
};
let orchestration_registry = OrchestrationRegistry::builder()
.register_typed::<AddReq, AddRes, _, _>("Adder", orchestration)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let client = Client::new(store.clone());
client
.start_orchestration_typed::<AddReq>("inst-typed-add", "Adder", AddReq { a: 2, b: 3 })
.await
.unwrap();
match client
.wait_for_orchestration_typed::<AddRes>("inst-typed-add", std::time::Duration::from_secs(5))
.await
.unwrap()
{
Ok(result) => assert_eq!(result, AddRes { sum: 5 }),
Err(error) => panic!("orchestration failed: {error}"),
}
rt.shutdown(None).await;
}
/// Typed external event sample: await Ack { ok } from an event
#[tokio::test]
async fn sample_typed_event_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
let activity_registry = ActivityRegistry::builder().build();
let orch = |ctx: OrchestrationContext, _in: ()| async move {
let ack: Ack = ctx.schedule_wait_typed::<Ack>("Ready").await;
Ok::<_, String>(serde_json::to_string(&ack).unwrap())
};
let orchestration_registry = OrchestrationRegistry::builder()
.register_typed::<(), String, _, _>("WaitAck", orch)
.build();
let rt = runtime::Runtime::start_with_store(store.clone(), activity_registry, orchestration_registry).await;
let store_for_wait = store.clone();
tokio::spawn(async move {
let sfw = store_for_wait.clone();
let _ = common::wait_for_subscription(sfw.clone(), "inst-typed-ack", "Ready", 1000).await;
// Raise typed event by serializing payload
let payload = serde_json::to_string(&Ack { ok: true }).unwrap();
let client = Client::new(sfw);
let _ = client.raise_event("inst-typed-ack", "Ready", payload).await;
});
let client = Client::new(store.clone());
client
.start_orchestration_typed::<()>("inst-typed-ack", "WaitAck", ())
.await
.unwrap();
match client
.wait_for_orchestration_typed::<String>("inst-typed-ack", std::time::Duration::from_secs(5))
.await
.unwrap()
{
Ok(result) => assert_eq!(result, serde_json::to_string(&Ack { ok: true }).unwrap()),
Err(error) => panic!("orchestration failed: {error}"),
}
rt.shutdown(None).await;
}
/// Mixed string and typed activities with typed orchestration, showcasing select on typed+string
#[tokio::test]
async fn sample_mixed_string_and_typed_typed_orch_fs() {
let (store, _temp_dir) = common::create_sqlite_store_disk().await;
// String activity: returns uppercased string
// Typed activity: Add two numbers
let activity_registry = ActivityRegistry::builder()
.register("Upper", |_ctx: ActivityContext, input: String| async move {
Ok(input.to_uppercase())
})
.register_typed::<AddReq, AddRes, _, _>("Add", |_ctx: ActivityContext, req| async move {
Ok(AddRes { sum: req.a + req.b })
})
.build();
// Typed orchestrator input/output
let orch = |ctx: OrchestrationContext, req: AddReq| async move {