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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
//! The context passed to workflow code: tasks, timers, child workflows, state, events,
//! queries and updates.
use crate::error::{Error, Result};
use crate::task::IntoTaskName;
use crate::workflow::command::*;
use crate::workflow::executable::{ClosureExecution, Executable, TaskExecution};
use crate::workflow::{
ChildWorkflowHandle, ChildWorkflowOptions, RestartFreshOptions, TaskOptions, WorkflowExecution,
};
use crate::workflow::{WorkflowRand, WorkflowTime};
use orcher_sdk_core::kernel::step_ids::{self as kernel_ids, StepKind as KernelStep};
use serde::{de::DeserializeOwned, Serialize};
use std::collections::{HashMap, HashSet, VecDeque};
use std::future::Future;
use std::sync::{Arc, Mutex};
use std::time::Duration;
/// What kind of step the code reached.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum StepKind {
/// A task, including the built-in session tasks.
Task,
/// A durable timer, including a timed wait's deadline.
Timer,
/// A child workflow, by its workflow id.
Child,
}
/// A step the code reached in an activation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ReachedStep {
/// What kind of step it is.
pub(crate) kind: StepKind,
/// Its id: a task's or timer's id, a child's workflow id.
pub(crate) id: String,
}
/// The context a workflow runs in.
///
/// Every operation with an outside effect (tasks, closures, timers, child workflows) goes
/// through the context, which records its result in the journal. On replay the recorded
/// result is returned instead of running the operation again.
///
/// Clones share the same interior state.
pub struct WorkflowContext {
execution: WorkflowExecution,
version: String,
/// How the run's step ids are made; see [`StepIds`].
step_ids: StepIds,
/// Random source seeded by the workflow id, so replays draw the same values.
rand: WorkflowRand,
/// Journal-derived clock; see [`WorkflowContext::time`]. Shared with the state so a
/// child handle can move it too.
time: WorkflowTime,
pub(crate) state: Arc<Mutex<ContextState>>,
}
/// What an update handler registered on a context returns.
pub(crate) type UpdateFuture =
std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send>>;
/// An update handler registered on a context: JSON arguments in, JSON result out.
pub(crate) type ContextUpdateHandler = Arc<dyn Fn(Vec<u8>) -> UpdateFuture + Send + Sync>;
/// Events buffered for one name, oldest first, each with its place in the
/// order the run observes its outcomes and the time it was journaled (ms since
/// the epoch), when known.
pub(crate) type BufferedEvents = VecDeque<(Option<usize>, Vec<u8>, Option<i64>)>;
/// Serializes a query handler's result, failing the query if it cannot be.
fn encode_query_result<R: Serialize>(query: &str, result: &R) -> Result<Vec<u8>> {
serde_json::to_vec(result).map_err(|e| {
Error::Workflow(crate::error::WorkflowError::QueryError {
query: query.to_string(),
reason: format!("result could not be serialized: {e}"),
})
})
}
/// A registered query handler: takes the query's JSON arguments (empty when
/// the client sent none) and returns its JSON result.
pub(crate) type QueryHandlerFn = Arc<dyn Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync>;
/// The outcomes an activation holds for the code to receive, by their place in the run's
/// order of outcomes: what [`WorkflowContext::is_replaying`] is decided from.
#[derive(Clone, Debug, Default)]
pub(crate) struct OutcomeMarks {
/// The latest place of any outcome; 0 if there is none.
newest: u64,
/// The earliest place of an outcome the activation marks as new to the run.
first_new: Option<u64>,
/// Whether the activation marks any outcome as observed in an earlier activation.
any_seen_before: bool,
}
impl OutcomeMarks {
fn note(&mut self, order: u64, seen_before: bool) {
self.newest = self.newest.max(order);
if seen_before {
self.any_seen_before = true;
} else {
self.first_new = Some(self.first_new.map_or(order, |first| first.min(order)));
}
}
/// Whether the code is still re-running what an earlier activation ran, once it has
/// received every outcome up to `received_through`; `None` if no outcome was noted.
fn replaying(&self, received_through: u64) -> Option<bool> {
if self.any_seen_before {
// The activation says which outcomes the run saw before: the code replays
// until it receives the first that is new, and throughout if there is none
// (an activation for a query, an update or a cancellation request).
Some(self.first_new.is_none_or(|first| received_through < first))
} else if self.newest > 0 {
// Unmarked: take the newest outcome as what is new.
Some(received_through < self.newest)
} else {
None
}
}
}
/// Mutable interior state for `WorkflowContext`, wrapped in `Arc<Mutex<>>`.
#[derive(Clone)]
pub(crate) struct ContextState {
pub(crate) replaying: bool,
/// The one step counter. Task, timer, child, closure and session ids are derived from
/// it, and each step takes exactly one number whether it is issued or read back from
/// the journal, so an id depends only on the step's place in the code.
pub(crate) sequence: u64,
/// The workflow's clock, the one `WorkflowContext::time` reads.
pub(crate) clock: WorkflowTime,
/// When the engine journaled each result the workflow can receive, in ms
/// since the epoch: keyed as in `pending_task_results`, and fired timers
/// under `timer:{id}`.
pub(crate) resolved_at: HashMap<String, i64>,
/// Where each result the workflow can receive comes in the order the run observes
/// its outcomes (the kernel's resolution sequence), keyed as `resolved_at`. Which of
/// a result and a cancellation request came first is decided by it, never by times,
/// which tie within a millisecond.
pub(crate) resolved_order: HashMap<String, u64>,
/// The outcomes this activation holds for the code to receive (task, value, child and
/// timer results, and events), by their place in that order; see
/// [`WorkflowContext::is_replaying`].
pub(crate) outcomes: OutcomeMarks,
/// The latest place in that order of an outcome the code has received so far.
pub(crate) received_through: std::cell::Cell<u64>,
pub(crate) commands: Vec<WorkflowCommand>,
pub(crate) workflow_state: HashMap<String, Vec<u8>>,
pub(crate) pending_task_results: HashMap<String, Vec<u8>>,
/// Step kind by step id: 0 for a task, 1 for a closure.
pub(crate) step_type_map: HashMap<String, i32>,
/// Attempts made so far, by step id.
pub(crate) step_attempt_counts: HashMap<String, i32>,
/// Recorded failures of closure steps, by step id.
pub(crate) pending_task_failures: HashMap<String, crate::workflow::StepFailure>,
pub(crate) cached_input: Option<crate::payload::Payload>,
/// Task queue override for session-routed tasks, set by `SessionContext` around its
/// call to `execute_task`.
pub(crate) task_queue_override: Option<String>,
/// Fired durable timers by timer id, with the firing's place in the order the run
/// observes its outcomes when known.
pub(crate) fired_timers: HashMap<String, Option<usize>>,
pub(crate) child_workflows: HashMap<String, ChildWorkflowHandle>,
/// The ids of the children the journal records this run starting. A child the code
/// starts without an id is started under the id the journal holds for it, when the
/// journal holds one from an earlier SDK's default; see
/// [`default_child_workflow_id`](WorkflowContext::default_child_workflow_id).
pub(crate) journaled_children: HashSet<String>,
/// Events received before a matching `wait_for_event`, per name, oldest first, each
/// with its place in the order the run observes its outcomes when known.
pub(crate) event_buffer: HashMap<String, BufferedEvents>,
/// `wait_for_event_with_timeout` calls made per event name in this activation. The
/// count names each deadline timer, so ids match across replays.
pub(crate) event_timeout_waits: HashMap<String, u32>,
/// The id of every step (task, timer, child workflow) the code reached in this
/// activation, in order, whether the journal already held its outcome or its command
/// is issued now. sdk-core checks them against the steps the journal recorded to tell
/// code that no longer replays the run.
pub(crate) reached_steps: Vec<ReachedStep>,
pub(crate) query_handlers: HashMap<String, QueryHandlerFn>,
pub(crate) update_handlers: HashMap<String, ContextUpdateHandler>,
/// Whether the journal holds a request to cancel the workflow.
pub(crate) cancel_requested: bool,
/// Where that request comes in the order the run observes its outcomes, when known.
pub(crate) cancel_requested_order: Option<u64>,
/// Whether the code has been told of the request. It is told once, at the first
/// wait whose result does not come before the request: the same wait on every
/// replay, since the code's order and the history's order are both fixed.
pub(crate) cancel_delivered: bool,
}
impl ContextState {
/// Whether the wait in hand is where the code learns of a cancellation request:
/// a request has come, the code has not been told yet, and the journal did not
/// record this wait's result before the request. Marks the request delivered
/// when it is.
///
/// `result` is `None` when the wait has no result yet, and otherwise where the
/// result comes in the run's order of outcomes, if known. A result that comes
/// before the request is received; one with no known place is too, since it exists.
pub(crate) fn take_cancellation(&mut self, result: Option<Option<u64>>) -> bool {
if !self.cancel_requested || self.cancel_delivered {
return false;
}
let received_first = match (result, self.cancel_requested_order) {
(None, _) => false,
(Some(Some(result_order)), Some(requested_order)) => result_order < requested_order,
(Some(_), _) => true,
};
if received_first {
return false;
}
self.cancel_delivered = true;
true
}
/// The result of the wait under `key`, as
/// [`take_cancellation`](Self::take_cancellation) takes it.
pub(crate) fn result_seen(&self, key: &str) -> Option<Option<u64>> {
self.pending_task_results
.contains_key(key)
.then(|| self.resolved_order.get(key).copied())
}
/// The workflow received what was journaled under `key`: its clock moves
/// to when that was journaled.
pub(crate) fn observe(&self, key: &str) {
self.received(key);
if let Some(at_ms) = self.resolved_at.get(key) {
self.clock.advance_to(*at_ms);
}
}
/// The code received the outcome held under `key`, without its clock moving: a
/// recorded value, which the code reads back on replay but did not wait for when it
/// first ran.
pub(crate) fn received(&self, key: &str) {
if let Some(order) = self.resolved_order.get(key) {
self.received_at_order(*order);
}
}
/// The code received the outcome at `order` in the run's order of outcomes.
pub(crate) fn received_at_order(&self, order: u64) {
if order > self.received_through.get() {
self.received_through.set(order);
}
}
}
/// How a run's step ids are made, as the engine bound the run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum StepIds {
/// This SDK's own ids: a run from before the kernel assigned them, or one
/// a worker reporting no step-id schemes started.
Own,
/// The kernel's: every step named by its kind and call sequence, a child
/// started without a workflow id named from the run's history lineage.
Kernel {
/// The run's history lineage.
lineage: String,
},
}
impl Clone for WorkflowContext {
fn clone(&self) -> Self {
Self {
execution: self.execution.clone(),
version: self.version.clone(),
step_ids: self.step_ids.clone(),
rand: self.rand.clone(),
time: self.time.clone(),
state: Arc::clone(&self.state),
}
}
}
impl WorkflowContext {
/// Creates a workflow context. The worker runtime creates one for each activation,
/// with its clock at the journaled workflow start; tests and tools may call this
/// directly, and with no journal to read, the clock starts at the moment of the call.
pub fn new(execution: WorkflowExecution, replaying: bool, version: String) -> Self {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or(Duration::ZERO)
.as_millis() as i64;
Self::starting_at(execution, replaying, version, now_ms)
}
/// Creates a context whose clock starts at `started_at_ms` (milliseconds since the
/// UNIX epoch).
pub(crate) fn starting_at(
execution: WorkflowExecution,
replaying: bool,
version: String,
started_at_ms: i64,
) -> Self {
let workflow_id = execution.workflow_id.clone();
let workflow_rand = WorkflowRand::new(&workflow_id);
let workflow_time = WorkflowTime::from_millis(started_at_ms);
let context_state = ContextState {
replaying,
sequence: 0,
clock: workflow_time.clone(),
resolved_at: HashMap::new(),
resolved_order: HashMap::new(),
outcomes: OutcomeMarks::default(),
received_through: std::cell::Cell::new(0),
commands: Vec::new(),
workflow_state: HashMap::new(),
pending_task_results: HashMap::new(),
step_type_map: HashMap::new(),
step_attempt_counts: HashMap::new(),
pending_task_failures: HashMap::new(),
cached_input: None,
task_queue_override: None,
fired_timers: HashMap::new(),
child_workflows: HashMap::new(),
journaled_children: HashSet::new(),
event_buffer: HashMap::new(),
event_timeout_waits: HashMap::new(),
reached_steps: Vec::new(),
query_handlers: HashMap::new(),
update_handlers: HashMap::new(),
cancel_requested: false,
cancel_requested_order: None,
cancel_delivered: false,
};
let ctx = Self {
execution,
version,
step_ids: StepIds::Own,
rand: workflow_rand,
time: workflow_time,
state: Arc::new(Mutex::new(context_state)),
};
ctx.register_automatic_queries();
ctx
}
/// The context for a run under the kernel's step-id scheme, whose history
/// lineage is `lineage` and whose random values come from `seed`.
pub(crate) fn under_kernel_scheme(mut self, lineage: String, seed: [u8; 32]) -> Self {
self.step_ids = StepIds::Kernel { lineage };
self.rand = WorkflowRand::from_kernel_seed(seed);
self
}
/// The id of a step of kind `kind` made by the call numbered `sequence`:
/// the kernel's for a run under its scheme, `own` otherwise.
pub(crate) fn step_id(
&self,
kind: KernelStep,
sequence: u64,
own: impl FnOnce() -> String,
) -> String {
match self.step_ids {
StepIds::Kernel { .. } => kernel_ids::id_for(kind, sequence),
StepIds::Own => own(),
}
}
/// Whether the run is under the kernel's step-id scheme.
pub(crate) fn kernel_assigns_ids(&self) -> bool {
matches!(self.step_ids, StepIds::Kernel { .. })
}
pub(crate) fn next_sequence(&self) -> u64 {
let mut state = self.state.lock().unwrap();
let seq = state.sequence;
state.sequence += 1;
seq
}
pub(crate) fn add_command(&self, command: WorkflowCommand) {
tracing::debug!("Adding command: {:?}", command);
let mut state = self.state.lock().unwrap();
state.commands.push(command);
}
pub(crate) fn take_commands(&self) -> Vec<WorkflowCommand> {
let mut state = self.state.lock().unwrap();
std::mem::take(&mut state.commands)
}
/// The code reached the step of this kind with this id; see
/// [`take_reached_steps`](Self::take_reached_steps).
pub(crate) fn reach_step(&self, kind: StepKind, step_id: &str) {
let mut state = self.state.lock().unwrap();
state.reached_steps.push(ReachedStep {
kind,
id: step_id.to_string(),
});
}
/// The ids of the steps the code reached in this activation, for its result.
///
/// sdk-core compares them with the steps the journal recorded: a recorded step left
/// unreached by an activation that issues new work or ends the workflow is reported
/// as non-determinism, and the activation is tried again instead of applied.
pub(crate) fn take_reached_steps(&self) -> Vec<ReachedStep> {
let mut state = self.state.lock().unwrap();
std::mem::take(&mut state.reached_steps)
}
pub(crate) fn execution(&self) -> &WorkflowExecution {
&self.execution
}
// ============================================================================
// Tasks and closures
// ============================================================================
/// Runs a registered task and returns its result.
///
/// `task` is either a typed reference generated by `#[task]`, which the compiler checks,
/// or a string name, which is only checked at run time. The result is journaled; on
/// replay the recorded result is returned and the task does not run again. In tests,
/// tasks can be mocked with `TestWorkflowExecutor`.
///
/// # Errors
///
/// Returns an error if the task is not registered, fails after its retries, or its
/// input or output cannot be serialized. While the task is still running, returns a
/// `Suspended` error that the runtime uses to park the workflow.
///
/// # Example
///
/// ```rust
/// # use orcher_sdk::prelude::*;
/// #[task(retry = 3)]
/// async fn send_email(_ctx: TaskContext, to: String) -> Result<String> {
/// Ok(format!("receipt for {to}"))
/// }
///
/// #[workflow]
/// async fn welcome(ctx: WorkflowContext, email: String) -> Result<String> {
/// // Typed reference: a typo fails to compile.
/// let receipt: String = ctx.execute_task(send_email, email.clone()).await?;
///
/// // String name: a typo fails only at run time.
/// let _again: String = ctx.execute_task("send_email", email).await?;
///
/// Ok(receipt)
/// }
/// ```
pub async fn execute_task<T, I, O>(&self, task: T, input: I) -> Result<O>
where
T: IntoTaskName,
I: Serialize + Send + Sync + 'static,
O: DeserializeOwned + Send + Sync + 'static,
{
let task_name = task.into_task_name();
let task_exec = TaskExecution::<I, O>::new(input);
task_exec.execute_in_context(self, task_name).await
}
#[doc(hidden)]
pub async fn execute_task_by_name<I, O>(&self, task_name: &'static str, input: I) -> Result<O>
where
I: Serialize + Send + Sync + 'static,
O: DeserializeOwned + Send + Sync + 'static,
{
self.execute_task(task_name, input).await
}
/// Runs an inline closure as a journaled step named `step_name`.
///
/// Suited to one-off side effects such as an HTTP call or a query. On replay the
/// recorded result is returned and the closure does not run again. For work used from
/// several places, prefer a registered task and [`execute_task`](Self::execute_task).
///
/// # Errors
///
/// Returns an error if the closure fails, its result cannot be serialized, or the
/// recorded result is missing during replay.
pub async fn execute<F, Fut, O>(&self, step_name: &str, closure: F) -> Result<O>
where
F: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = Result<O>> + Send,
O: Serialize + DeserializeOwned + Send + Sync + 'static,
{
let closure_exec = ClosureExecution::new(closure);
closure_exec.execute_in_context(self, step_name).await
}
/// Deprecated: use [`execute_task`](Self::execute_task) or [`execute`](Self::execute).
#[deprecated(
since = "0.2.0",
note = "Use ctx.execute() instead for unified task/closure execution with journaling"
)]
pub async fn execute_task_with_options<I, O>(
&self,
task_type: &str,
input: I,
options: TaskOptions,
) -> Result<O>
where
I: Serialize,
O: DeserializeOwned,
{
let input_bytes = serde_json::to_vec(&input)
.map_err(|e| Error::Serialization(format!("Failed to serialize task input: {}", e)))?;
// One number on every path, cached or not. The id comes from it so it is stable
// across replays, and taking it unconditionally keeps later ids from shifting.
let sequence = self.next_sequence();
// Under the kernel's scheme the kernel names the step; a chosen id
// names it only for a run under this SDK's own.
let task_id = self.step_id(KernelStep::Task, sequence, || {
options
.task_id
.clone()
.unwrap_or_else(|| format!("task_{}", sequence))
});
self.reach_step(StepKind::Task, &task_id);
self.cancellation_for(&task_id)?;
let replaying = {
let state = self.state.lock().unwrap();
state.replaying
};
if replaying {
let state = self.state.lock().unwrap();
if let Some(result_bytes) = state.pending_task_results.get(&task_id) {
tracing::trace!(
task_id = %task_id,
result_len = result_bytes.len(),
"Replaying journaled task result"
);
state.observe(&task_id);
// Decoded as `execute_task` decodes it, so a task that failed for good
// raises `TaskFailed` here too.
return crate::workflow::executable::decode_task_result(
&task_id,
task_type,
result_bytes,
);
} else {
tracing::trace!(
task_id = %task_id,
"No journaled task result; scheduling the task"
);
}
}
let declared = crate::worker::registration::task_limits(task_type);
let command = WorkflowCommand::ScheduleTask(ScheduleTaskCommand {
sequence,
task_id: task_id.clone(),
task_type: task_type.to_string(),
task_queue: self.execution.task_queue.clone(),
input: input_bytes,
// Precedence: what this call asked for, else what the task declared on its
// `#[task]` attribute, else the 300s scheduler default.
timeout: options
.timeout
.or_else(|| {
declared
.and_then(|d| d.timeout_secs)
.map(Duration::from_secs)
})
.unwrap_or(Duration::from_secs(300)),
heartbeat_timeout: options.heartbeat_timeout.or_else(|| {
declared
.and_then(|d| d.heartbeat_timeout_secs)
.map(Duration::from_secs)
}),
queue_timeout: options.queue_timeout,
retry_policy: (&options).into(),
headers: vec![],
});
self.add_command(command);
Err(Error::Workflow(crate::error::WorkflowError::Suspended {
reason: format!("Task '{}' scheduled for execution", task_id),
pending_operations: vec![task_id],
}))
}
// ============================================================================
// Timers
// ============================================================================
/// Sleeps for `duration` on a durable timer, which survives worker restarts.
///
/// The timer id is `timer_{sequence}`, taken from the step sequence, so it is the same
/// on every replay and matches the engine's fired-timer event.
pub async fn sleep(&self, duration: Duration) -> Result<()> {
let sequence = self.next_sequence();
let timer_id = self.step_id(KernelStep::Timer, sequence, || {
format!("timer_{}", sequence)
});
self.emit_timer(timer_id, sequence, duration)
}
/// Sleeps on a durable timer with an explicit id, for example to address it for
/// cancellation. Prefer [`sleep`](Self::sleep) unless you need a known id.
///
/// The id names the timer only in runs this SDK started before the engine bound
/// runs to a step-id scheme; a run under the kernel's scheme has the timer named
/// by the kernel, as [`sleep`](Self::sleep) does.
pub async fn sleep_with_id(&self, timer_id: &str, duration: Duration) -> Result<()> {
let sequence = self.next_sequence();
let timer_id = self.step_id(KernelStep::Timer, sequence, || timer_id.to_string());
self.emit_timer(timer_id, sequence, duration)
}
/// Emits a StartTimer command and suspends, or returns at once if the timer has
/// already fired.
///
/// Callers take the sequence number before this check, whether or not the timer has
/// fired, so later ids stay the same across replays. The runtime marks a timer fired
/// by the timer id in its FireTimer job.
fn emit_timer(&self, timer_id: String, sequence: u64, duration: Duration) -> Result<()> {
self.reach_step(StepKind::Timer, &timer_id);
let fired = {
let state = self.state.lock().unwrap();
state.fired_timers.contains_key(&timer_id).then(|| {
state
.resolved_order
.get(&format!("timer:{}", timer_id))
.copied()
})
};
self.cancellation_at(fired)?;
let already_fired = {
let state = self.state.lock().unwrap();
let fired = state.fired_timers.contains_key(&timer_id);
if fired {
state.observe(&format!("timer:{}", timer_id));
}
fired
};
if already_fired {
return Ok(());
}
self.add_command(WorkflowCommand::StartTimer(StartTimerCommand {
sequence,
timer_id: timer_id.clone(),
duration,
}));
Err(Error::Workflow(crate::error::WorkflowError::Suspended {
reason: format!("Waiting for timer {}", timer_id),
pending_operations: vec![timer_id],
}))
}
// ============================================================================
// Child workflows
// ============================================================================
/// Starts a child workflow and waits for its result.
pub async fn execute_child_workflow<I, O>(&self, workflow_type: &str, input: I) -> Result<O>
where
I: Serialize,
O: DeserializeOwned,
{
self.execute_child_workflow_with_options(
workflow_type,
input,
ChildWorkflowOptions::default(),
)
.await
}
/// Starts a child workflow with custom options and waits for its result.
pub async fn execute_child_workflow_with_options<I, O>(
&self,
workflow_type: &str,
input: I,
options: ChildWorkflowOptions,
) -> Result<O>
where
I: Serialize,
O: DeserializeOwned,
{
// Advances the sequence and derives a stable child id.
let handle = self
.start_child_workflow_with_options(workflow_type, input, options)
.await?;
self.cancellation_for(&format!("child:{}", handle.id()))?;
// On replay, the runtime has injected the child's outcome under `child:{id}`.
let cached = {
let state = self.state.lock().unwrap();
let key = format!("child:{}", handle.id());
let cached = state.pending_task_results.get(&key).cloned();
if cached.is_some() {
state.observe(&key);
}
cached
};
if let Some(result_bytes) = cached {
// A failed child is recorded as a JSON object with `__orcher_child_failed__`.
if let Ok(v) = serde_json::from_slice::<serde_json::Value>(&result_bytes) {
if v.get("__orcher_child_failed__")
.and_then(|b| b.as_bool())
.unwrap_or(false)
{
let msg = v
.get("message")
.and_then(|m| m.as_str())
.unwrap_or("child workflow failed");
return Err(Error::Workflow(
crate::error::WorkflowError::ChildWorkflowFailed {
workflow_type: workflow_type.to_string(),
workflow_id: handle.id().to_string(),
reason: msg.to_string(),
},
));
}
}
return serde_json::from_slice(&result_bytes).map_err(|e| {
Error::Serialization(format!(
"Failed to deserialize child workflow result: {}",
e
))
});
}
// Not finished yet: suspend until the child completes.
handle.result().await
}
/// Starts a child workflow and returns a handle without waiting for it.
pub async fn start_child_workflow<I>(
&self,
workflow_type: &str,
input: I,
) -> Result<ChildWorkflowHandle>
where
I: Serialize,
{
self.start_child_workflow_with_options(
workflow_type,
input,
ChildWorkflowOptions::default(),
)
.await
}
/// Starts a child workflow with custom options and returns a handle.
pub async fn start_child_workflow_with_options<I>(
&self,
workflow_type: &str,
input: I,
options: ChildWorkflowOptions,
) -> Result<ChildWorkflowHandle>
where
I: Serialize,
{
let input_bytes = serde_json::to_vec(&input).map_err(|e| {
Error::Serialization(format!("Failed to serialize child workflow input: {}", e))
})?;
// Take the sequence first so the default child id is the same on every replay.
let sequence = self.next_sequence();
let workflow_id = options
.workflow_id
.clone()
.unwrap_or_else(|| self.default_child_workflow_id(sequence));
self.reach_step(StepKind::Child, &workflow_id);
let run_id = format!("run_{}", uuid::Uuid::new_v4());
// Inherit the parent's task queue unless one is given.
let task_queue = options
.task_queue
.clone()
.unwrap_or_else(|| self.execution.task_queue.clone());
// The handle shares the context state, so `handle.result()` reads the outcome the
// runtime injects under `child:{id}`, the same entry the execute path reads.
let handle = ChildWorkflowHandle::new(
workflow_id.clone(),
run_id,
workflow_type.to_string(),
self.clone(),
);
{
let mut state = self.state.lock().unwrap();
state
.child_workflows
.insert(workflow_id.clone(), handle.clone());
}
// A child that already completed is not started again.
let already_done = {
let state = self.state.lock().unwrap();
state
.pending_task_results
.contains_key(&format!("child:{}", workflow_id))
};
if !already_done {
let command = WorkflowCommand::StartChildWorkflow(StartChildWorkflowCommand {
sequence,
workflow_id: workflow_id.clone(),
workflow_type: workflow_type.to_string(),
task_queue,
input: input_bytes,
timeout: options.execution_timeout,
orphan_policy: options.orphan_policy.into(),
retry_policy: options.retry_policy,
});
self.add_command(command);
}
tracing::info!(
workflow_id = %self.execution.workflow_id,
child_workflow_id = %workflow_id,
child_workflow_type = %workflow_type,
already_done = already_done,
"Started child workflow"
);
Ok(handle)
}
// ============================================================================
// State
// ============================================================================
/// Stores a JSON-serialized value under `key` in the workflow state.
pub fn set_state<T>(&self, key: &str, value: &T) -> Result<()>
where
T: Serialize,
{
let value_bytes = serde_json::to_vec(&value)
.map_err(|e| Error::Serialization(format!("Failed to serialize state value: {}", e)))?;
let mut state = self.state.lock().unwrap();
state.workflow_state.insert(key.to_string(), value_bytes);
tracing::debug!(
workflow_id = %self.execution.workflow_id,
key = %key,
"Set workflow state"
);
Ok(())
}
/// Reads the value stored under `key`, or `None` if there is none.
pub fn get_state<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
let state = self.state.lock().unwrap();
match state.workflow_state.get(key) {
Some(value_bytes) => {
let value: T = serde_json::from_slice(value_bytes).map_err(|e| {
Error::Serialization(format!("Failed to deserialize state value: {}", e))
})?;
Ok(Some(value))
}
None => Ok(None),
}
}
// ============================================================================
// Events and queries
// ============================================================================
/// Waits for the next event named `event_name`.
///
/// Events of one name are delivered oldest first. If one is already buffered it is
/// returned at once; otherwise the workflow suspends until the event arrives.
pub async fn wait_for_event<T>(&self, event_name: &str) -> Result<T>
where
T: DeserializeOwned,
{
// Under the kernel's scheme a wait is a durable call like any other,
// and takes its number on every path, found or parked.
let kernel_sequence = self.kernel_assigns_ids().then(|| self.next_sequence());
// Scoped deliberately: the suspend path below locks `state` again, and
// std::sync::Mutex is not reentrant. Holding this guard past the early
// return deadlocks the worker thread.
//
// Oldest first: events of one name are consumed in arrival order, as in the
// other SDKs.
// The oldest event of this name is received if it came before any cancellation
// request; otherwise this is where the request is delivered.
let next = {
let state = self.state.lock().unwrap();
state
.event_buffer
.get(event_name)
.and_then(|events| events.front())
.map(|(order, _, _)| order.map(|order| order as u64))
};
self.cancellation_at(next)?;
let buffered = {
let mut state = self.state.lock().unwrap();
let event = state
.event_buffer
.get_mut(event_name)
.and_then(|events| events.pop_front());
event.map(|(position, payload, at_ms)| {
if let Some(position) = position {
state.received_at_order(position as u64);
}
if let Some(at_ms) = at_ms {
state.clock.advance_to(at_ms);
}
payload
})
};
if let Some(event_bytes) = buffered {
let event: T = serde_json::from_slice(&event_bytes).map_err(|e| {
Error::Serialization(format!(
"Failed to deserialize event '{}': {}",
event_name, e
))
})?;
tracing::debug!(
workflow_id = %self.execution.workflow_id,
event_name = %event_name,
"Event retrieved from buffer"
);
return Ok(event);
}
// No buffered event: emit WaitForEvent and suspend. This produces no proto
// command; the server releases its claim on the workflow and queues it again
// when SendEvent delivers an EventReceived entry.
//
// Under this SDK's own scheme a wait is not an engine step (events are matched
// to waits by name), so it takes no number from the step counter on any path. If
// parking took one and finding the event did not, a step issued beside the wait
// would get another id once the event had arrived.
let seq = kernel_sequence.unwrap_or_else(|| self.state.lock().unwrap().sequence);
tracing::debug!(
workflow_id = %self.execution.workflow_id,
event_name = %event_name,
"Suspending workflow to wait for event"
);
self.add_command(WorkflowCommand::WaitForEvent(
crate::workflow::WaitForEventCommand {
sequence: seq,
event_name: event_name.to_string(),
timeout: None,
},
));
Err(Error::Workflow(crate::error::WorkflowError::Suspended {
reason: format!("Waiting for event: {}", event_name),
pending_operations: vec![format!("event:{}", event_name)],
}))
}
/// Like [`wait_for_event`](Self::wait_for_event), but returns `None` if `timeout`
/// passes without the event.
///
/// The deadline is a durable timer started beside the wait, so it holds while no
/// worker is running the workflow. Whichever the journal shows first wins: an event
/// that arrived before the deadline is returned; a fired deadline returns `None`, and
/// an event that lands after it is left for the next wait, because an earlier
/// activation already took the timeout branch.
///
/// # Errors
///
/// Returns an error if `timeout` is zero or the event cannot be deserialized.
pub async fn wait_for_event_with_timeout<T>(
&self,
event_name: &str,
timeout: Duration,
) -> Result<Option<T>>
where
T: DeserializeOwned,
{
if timeout.is_zero() {
return Err(Error::Workflow(crate::error::WorkflowError::StateError(
"wait_for_event_with_timeout: timeout must be greater than zero".to_string(),
)));
}
// Scoped for the same reason as `wait_for_event`: the suspend path below
// locks `state` again, and the mutex is not reentrant.
//
// The deadline timer id is `event_timeout_<name>_<n>`, where n counts this
// activation's timed waits on that name. It is allocated first, on every path.
// Allocating it only when parking would give the next wait on the same name a
// different id on replay than it had live, and that wait would find an earlier
// wait's fired timer and time out for no reason. It is not the step sequence: a
// wait takes no number from the step counter on any path (see `wait_for_event`).
//
// Under the kernel's scheme the wait and its deadline timer are two durable
// calls, each taking its number on every path, and the timer is named by its
// number like any other.
let kernel_sequences = self
.kernel_assigns_ids()
.then(|| (self.next_sequence(), self.next_sequence()));
let (timer_id, buffered, timer_fired) = {
let mut state = self.state.lock().unwrap();
let timer_id = match kernel_sequences {
Some((_, timer_sequence)) => kernel_ids::id_for(KernelStep::Timer, timer_sequence),
None => {
let n = state
.event_timeout_waits
.entry(event_name.to_string())
.or_insert(0);
*n += 1;
format!("event_timeout_{}_{}", event_name, n)
}
};
// Reached on every path, whichever of the event and the deadline wins: the
// journal holds this timer whenever an earlier activation parked here.
state.reached_steps.push(ReachedStep {
kind: StepKind::Timer,
id: timer_id.clone(),
});
// A fired marker without a position has no known order: treat it as later
// than any event, so a buffered event still wins.
let fired_at = state
.fired_timers
.get(&timer_id)
.map(|position| position.unwrap_or(usize::MAX));
// Whichever of the event and the deadline came first is this wait's
// result; if neither came before a cancellation request, this is where the
// request is delivered.
let event = state
.event_buffer
.get(event_name)
.and_then(|events| events.front())
.map(|(order, _, _)| order.map(|order| order as u64));
let deadline = state.fired_timers.contains_key(&timer_id).then(|| {
state
.resolved_order
.get(&format!("timer:{}", timer_id))
.copied()
});
let result = match (event, deadline) {
(Some(Some(event)), Some(Some(deadline))) => Some(Some(event.min(deadline))),
(Some(event), None) => Some(event),
(None, deadline) => deadline,
(Some(_), Some(_)) => Some(None),
};
if state.take_cancellation(result) {
return Err(Error::Workflow(crate::error::WorkflowError::Canceled));
}
let event_first = match (state.event_buffer.get(event_name), fired_at) {
(Some(events), Some(fired_at)) => events
.front()
.is_some_and(|(position, _, _)| position.is_none_or(|p| p < fired_at)),
(Some(events), None) => !events.is_empty(),
(None, _) => false,
};
let buffered = if event_first {
let event = state
.event_buffer
.get_mut(event_name)
.and_then(|events| events.pop_front());
event.map(|(position, payload, at_ms)| {
if let Some(position) = position {
state.received_at_order(position as u64);
}
if let Some(at_ms) = at_ms {
state.clock.advance_to(at_ms);
}
payload
})
} else {
None
};
if buffered.is_none() && fired_at.is_some() {
state.observe(&format!("timer:{}", timer_id));
}
(timer_id, buffered, fired_at.is_some())
};
if let Some(event_bytes) = buffered {
let event: T = serde_json::from_slice(&event_bytes).map_err(|e| {
Error::Serialization(format!(
"Failed to deserialize event '{}': {}",
event_name, e
))
})?;
tracing::debug!(
workflow_id = %self.execution.workflow_id,
event_name = %event_name,
"Event retrieved from buffer (with timeout)"
);
return Ok(Some(event));
}
if timer_fired {
tracing::debug!(
workflow_id = %self.execution.workflow_id,
event_name = %event_name,
timer_id = %timer_id,
"Wait for event timed out"
);
return Ok(None);
}
// Neither has arrived: park on the event and start the deadline timer.
// The timer is not cancelled if the event wins. For a finished workflow the
// engine marks the timer done without journaling it; for an unfinished one it
// costs a single extra replay. Under this SDK's own scheme the sequence fields
// only label the commands; the counter is not advanced (see `wait_for_event`).
let (wait_seq, timer_seq) = kernel_sequences.unwrap_or_else(|| {
let seq = self.state.lock().unwrap().sequence;
(seq, seq)
});
tracing::debug!(
workflow_id = %self.execution.workflow_id,
event_name = %event_name,
timeout_secs = %timeout.as_secs(),
timer_id = %timer_id,
"Suspending workflow to wait for event (with timeout)"
);
self.add_command(WorkflowCommand::WaitForEvent(
crate::workflow::WaitForEventCommand {
sequence: wait_seq,
event_name: event_name.to_string(),
timeout: Some(timeout),
},
));
self.add_command(WorkflowCommand::StartTimer(StartTimerCommand {
sequence: timer_seq,
timer_id: timer_id.clone(),
duration: timeout,
}));
Err(Error::Workflow(crate::error::WorkflowError::Suspended {
reason: format!("Waiting for event (with timeout): {}", event_name),
pending_operations: vec![format!("event:{}", event_name), timer_id],
}))
}
/// Registers a handler that answers the query `query_name`.
///
/// Queries let clients read workflow state without affecting execution. Handlers are
/// synchronous and should not modify workflow state. The result is serialized to
/// JSON; if that fails, the query fails with the reason. Registering a name again
/// replaces the earlier handler. The handler ignores any arguments the client sends;
/// use [`register_query_handler_with_args`](Self::register_query_handler_with_args)
/// to read them.
///
/// # Example
///
/// ```rust
/// # use orcher_sdk::prelude::*;
/// # async fn example(ctx: &mut WorkflowContext) -> Result<()> {
/// ctx.register_query_handler("get_status", || {
/// "processing".to_string()
/// });
///
/// ctx.register_query_handler("get_progress", || {
/// serde_json::json!({
/// "completed": 42,
/// "total": 100,
/// "percentage": 42.0
/// })
/// });
/// # Ok(())
/// # }
/// ```
pub fn register_query_handler<F, R>(&self, query_name: &str, handler: F)
where
F: Fn() -> R + Send + Sync + 'static,
R: Serialize,
{
let name = query_name.to_string();
self.insert_query_handler(
query_name,
Arc::new(move |_args: &[u8]| encode_query_result(&name, &handler())),
);
}
/// Registers a handler that answers the query `query_name` with the
/// arguments the client sent.
///
/// Like [`register_query_handler`](Self::register_query_handler), but the
/// handler receives the client's arguments, decoded as `A`. A query sent
/// with no arguments decodes from JSON `null`, so `A` can be an `Option`.
/// Arguments that do not decode as `A` fail the query with the reason.
///
/// # Example
///
/// ```rust
/// # use orcher_sdk::prelude::*;
/// # async fn example(ctx: &WorkflowContext) -> Result<()> {
/// let prices = vec![("apple".to_string(), 120u32), ("pear".to_string(), 90)];
///
/// ctx.register_query_handler_with_args("price_of", move |item: String| {
/// prices.iter().find(|(name, _)| *name == item).map(|(_, cents)| *cents)
/// });
/// # Ok(())
/// # }
/// ```
pub fn register_query_handler_with_args<F, A, R>(&self, query_name: &str, handler: F)
where
F: Fn(A) -> R + Send + Sync + 'static,
A: DeserializeOwned,
R: Serialize,
{
let name = query_name.to_string();
self.insert_query_handler(
query_name,
Arc::new(move |args: &[u8]| {
let args = if args.is_empty() {
b"null".as_slice()
} else {
args
};
let args: A = serde_json::from_slice(args).map_err(|e| {
Error::Workflow(crate::error::WorkflowError::QueryError {
query: name.clone(),
reason: format!("invalid query arguments: {e}"),
})
})?;
encode_query_result(&name, &handler(args))
}),
);
}
fn insert_query_handler(&self, query_name: &str, handler: QueryHandlerFn) {
let mut state = self.state.lock().unwrap();
state.query_handlers.insert(query_name.to_string(), handler);
tracing::debug!(
workflow_id = %self.execution.workflow_id,
query_name = %query_name,
"Query handler registered"
);
}
/// Runs the query handler registered under `query_name` with the query's
/// JSON arguments (empty when the client sent none).
pub(crate) fn handle_query_request(&self, query_name: &str, args: &[u8]) -> Result<Vec<u8>> {
// Clone the handler out so it does not run under the state lock.
let handler = self
.state
.lock()
.unwrap()
.query_handlers
.get(query_name)
.cloned();
match handler {
Some(handler) => handler(args),
None => Err(Error::Workflow(crate::error::WorkflowError::QueryError {
query: query_name.to_string(),
reason: "Query handler not registered".to_string(),
})),
}
}
// ============================================================================
// Sessions
// ============================================================================
/// Creates a worker session, which pins the tasks run through it to one worker.
///
/// This schedules an internal `__orcher_create_session` task on the workflow's own
/// queue. The worker that picks it up takes a session slot and returns its
/// worker-specific queue name. The returned
/// [`SessionContext`](crate::workflow::SessionContext) routes tasks to that queue.
///
/// The creation task's id comes from the step sequence. On replay the session queue
/// name is read from the journal, and the session is not created again.
///
/// # Errors
///
/// Returns a `Suspended` error while the session is being created, and
/// `TaskFailed` if creation failed, for example because no worker had a free
/// session slot within [`SessionOptions::creation_timeout`].
///
/// [`SessionOptions::creation_timeout`]: crate::workflow::session::SessionOptions::creation_timeout
///
/// # Example
///
/// ```rust
/// use orcher_sdk::prelude::*;
/// use orcher_sdk::workflow::session::SessionOptions;
/// use std::time::Duration;
///
/// #[task]
/// async fn load_model(_ctx: TaskContext, name: String) -> Result<String> {
/// Ok(format!("loaded {name}"))
/// }
///
/// #[task]
/// async fn run_inference(_ctx: TaskContext, prompt: String) -> Result<String> {
/// Ok(format!("answer to {prompt}"))
/// }
///
/// #[workflow]
/// async fn answer(ctx: WorkflowContext, prompt: String) -> Result<String> {
/// let mut session = ctx
/// .create_session(
/// SessionOptions::default()
/// .with_creation_timeout(Duration::from_secs(30))
/// .with_execution_timeout(Duration::from_secs(600)),
/// )
/// .await?;
///
/// // Both tasks run on the same worker.
/// let _model: String = session.execute_task(load_model, "small".to_string()).await?;
/// let answer: String = session.execute_task(run_inference, prompt).await?;
///
/// session.complete();
/// Ok(answer)
/// }
/// ```
pub async fn create_session(
&self,
options: crate::workflow::session::SessionOptions,
) -> Result<crate::workflow::session::SessionContext<'_>> {
use crate::workflow::session::*;
let sequence = self.next_sequence();
let session_id = format!("session_{}", sequence);
let task_id = self.step_id(KernelStep::Task, sequence, || {
format!("{}_{}", SESSION_CREATE_TASK, sequence)
});
self.reach_step(StepKind::Task, &task_id);
self.cancellation_for(&task_id)?;
// On replay the creation task's recorded result is a serialized SessionInfo.
{
let state = self.state.lock().unwrap();
if state.replaying {
if let Some(cached) = state.pending_task_results.get(&task_id) {
state.observe(&task_id);
// Decoded like any task result, so a creation that failed (for
// example, no session slot came free in time) raises `TaskFailed`.
let info: SessionInfo = crate::workflow::executable::decode_task_result(
&task_id,
SESSION_CREATE_TASK,
cached,
)?;
tracing::debug!(
session_id = %info.session_id,
session_queue = %info.session_queue,
"Replaying session creation"
);
return Ok(SessionContext::new(self, info));
}
}
}
let input = CreateSessionInput {
session_id: session_id.clone(),
creation_timeout_ms: options.creation_timeout.as_millis() as u64,
execution_timeout_ms: options.execution_timeout.as_millis() as u64,
max_concurrent_tasks: options.max_concurrent_tasks,
heartbeat_interval_ms: options.heartbeat_interval.as_millis() as u64,
};
let input_bytes = serde_json::to_vec(&input).map_err(|e| {
Error::Serialization(format!("Failed to serialize session creation input: {}", e))
})?;
let command = ScheduleTaskCommand {
sequence,
task_id: task_id.clone(),
task_type: SESSION_CREATE_TASK.to_string(),
task_queue: self.execution.task_queue.clone(), // The workflow's queue: any worker.
input: input_bytes,
timeout: options.creation_timeout,
heartbeat_timeout: None,
queue_timeout: None,
retry_policy: None, // Session creation is not retried.
headers: vec![],
};
// 0 marks the step as a task.
{
let mut state = self.state.lock().unwrap();
state.step_type_map.insert(task_id.clone(), 0);
}
self.add_command(WorkflowCommand::ScheduleTask(command));
tracing::debug!(
session_id = %session_id,
task_queue = %self.execution.task_queue,
"Scheduling session creation task"
);
// Suspend. When the task completes, its SessionInfo is injected into
// pending_task_results and the workflow resumes, and this call returns it from the
// replay path above.
Err(Error::Workflow(crate::error::WorkflowError::Suspended {
reason: format!("Creating session '{}'", session_id),
pending_operations: vec![task_id],
}))
}
// ============================================================================
// Updates
// ============================================================================
/// Registers an async handler for the update `update_name`.
///
/// The handler runs when a client sends an UpdateWorkflow request whose `update_type`
/// matches `update_name`. It receives the JSON-decoded arguments, may read and modify
/// workflow state, and its result is journaled so replays see the same outcome.
///
/// # Example
///
/// ```rust
/// # use orcher_sdk::prelude::*;
/// #[derive(Serialize, Deserialize)]
/// struct Address {
/// street: String,
/// }
///
/// #[derive(Serialize, Deserialize)]
/// struct AddressChangeResult {
/// accepted: bool,
/// }
///
/// # fn example(ctx: &WorkflowContext) {
/// ctx.register_update_handler("change_address", |new_address: Address| async move {
/// Ok(AddressChangeResult { accepted: !new_address.street.is_empty() })
/// });
/// # }
/// ```
pub fn register_update_handler<F, Fut, I, R>(&self, update_name: &str, handler: F)
where
F: Fn(I) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = Result<R>> + Send + 'static,
I: serde::de::DeserializeOwned + Send + 'static,
R: Serialize + Send + 'static,
{
let wrapped_handler: ContextUpdateHandler = Arc::new(move |args: Vec<u8>| {
let input: I = match serde_json::from_slice(&args) {
Ok(v) => v,
Err(e) => {
return Box::pin(async move {
Err(Error::Other(format!(
"Failed to deserialize update args: {}",
e
)))
}) as UpdateFuture;
}
};
let fut = handler(input);
Box::pin(async move {
let result = fut.await?;
serde_json::to_vec(&result)
.map_err(|e| Error::Other(format!("Failed to serialize update result: {}", e)))
}) as UpdateFuture
});
let mut state = self.state.lock().unwrap();
state
.update_handlers
.insert(update_name.to_string(), wrapped_handler);
tracing::debug!(
workflow_id = %self.execution.workflow_id,
update_name = %update_name,
"Update handler registered"
);
}
/// Runs the update handler registered under `update_name` on JSON `args` and returns
/// the JSON result. Called by the worker runtime.
///
/// # Errors
///
/// Returns an error if no handler is registered under that name, or if the handler
/// fails or its arguments or result cannot be (de)serialized.
#[allow(dead_code)]
pub async fn handle_update_request(&self, update_name: &str, args: Vec<u8>) -> Result<Vec<u8>> {
let handler = {
let state = self.state.lock().unwrap();
state.update_handlers.get(update_name).cloned()
};
match handler {
Some(handler) => handler(args).await,
None => Err(Error::Workflow(crate::error::WorkflowError::QueryError {
query: update_name.to_string(),
reason: "Update handler not registered".to_string(),
})),
}
}
/// Returns `true` if an update handler is registered under `update_name`.
pub fn has_update_handler(&self, update_name: &str) -> bool {
let state = self.state.lock().unwrap();
state.update_handlers.contains_key(update_name)
}
/// Returns the names of all registered update handlers, in no particular order.
pub fn get_update_names(&self) -> Vec<String> {
let state = self.state.lock().unwrap();
state.update_handlers.keys().cloned().collect()
}
// ============================================================================
// Event buffering
// ============================================================================
/// Buffers an event with no known position, for `wait_for_event` to consume.
#[cfg(test)]
pub(crate) fn buffer_event(&self, event_name: impl Into<String>, payload: Vec<u8>) {
self.buffer_event_at(event_name, payload, None);
}
/// Buffers an event with its place in the order the run observes its outcomes.
///
/// The runtime calls this for each `EventReceived` entry. `None` means "before
/// everything": the event wins any race with a deadline timer.
#[cfg(test)]
pub(crate) fn buffer_event_at(
&self,
event_name: impl Into<String>,
payload: Vec<u8>,
position: Option<usize>,
) {
self.buffer_journaled_event(event_name, payload, position, None);
}
/// Buffer an event with its place in the run's order and the time the engine
/// journaled it (ms since the epoch), which the workflow's clock moves to
/// when a wait takes the event.
pub(crate) fn buffer_journaled_event(
&self,
event_name: impl Into<String>,
payload: Vec<u8>,
position: Option<usize>,
at_ms: Option<i64>,
) {
let name = event_name.into();
let mut state = self.state.lock().unwrap();
state
.event_buffer
.entry(name.clone())
.or_default()
.push_back((position, payload, at_ms));
tracing::debug!(
workflow_id = %self.execution.workflow_id,
event_name = %name,
"Event buffered"
);
}
// ============================================================================
// Built-in queries
// ============================================================================
/// Registers the queries every workflow answers without any setup.
///
/// They are `workflow_id`, `workflow_type`, `run_id`, `is_replaying`, `attempt`,
/// `version`, `namespace`, `task_queue`, and `workflow_info`, which returns all of
/// these as one JSON object. Values are captured when the context is created. A
/// workflow may replace any of them by registering a handler with the same name.
fn register_automatic_queries(&self) {
let wf_id = self.execution.workflow_id.clone();
self.register_query_handler("workflow_id", move || wf_id.clone());
let wf_type = self.execution.workflow_type.clone();
self.register_query_handler("workflow_type", move || wf_type.clone());
let run_id = self.execution.run_id.clone();
self.register_query_handler("run_id", move || run_id.clone());
let replaying = self.is_replaying();
self.register_query_handler("is_replaying", move || replaying);
let attempt = self.execution.attempt;
self.register_query_handler("attempt", move || attempt);
let version = self.version.clone();
self.register_query_handler("version", move || version.clone());
let namespace = self.execution.namespace.clone();
self.register_query_handler("namespace", move || namespace.clone());
let task_queue = self.execution.task_queue.clone();
self.register_query_handler("task_queue", move || task_queue.clone());
let exec = self.execution.clone();
let ver = self.version.clone();
let rep = self.is_replaying();
self.register_query_handler("workflow_info", move || {
serde_json::json!({
"workflow_id": exec.workflow_id,
"run_id": exec.run_id,
"workflow_type": exec.workflow_type,
"namespace": exec.namespace,
"task_queue": exec.task_queue,
"attempt": exec.attempt,
"version": ver,
"is_replaying": rep,
})
});
tracing::debug!(
workflow_id = %self.execution.workflow_id,
"Automatic base queries registered"
);
}
// ============================================================================
// Deterministic helpers
// ============================================================================
/// Returns the deterministic random source.
///
/// Values are derived from the workflow id and an internal counter, so a replay draws
/// the same sequence as the original run, provided the calls happen in the same order.
/// Use it instead of `Uuid::new_v4()` or a thread RNG in workflow code.
///
/// # Examples
///
/// ```rust
/// # use orcher_sdk::prelude::*;
/// # async fn example(ctx: &WorkflowContext) -> Result<()> {
/// // Deterministic UUIDs.
/// let order_id = format!("ORD-{}", ctx.rand().uuid());
/// let confirmation = format!("CONF-{}", ctx.rand().uuid());
///
/// // A float in [0.0, 1.0).
/// let priority = ctx.rand().random();
///
/// // An integer in a range.
/// let discount = ctx.rand().random_range(5..=20);
///
/// // One element of a slice.
/// let shipping = ctx.rand().choose(&["standard", "express", "overnight"]);
/// # Ok(())
/// # }
/// ```
///
/// Never call `Uuid::new_v4()` or a thread RNG directly in workflow code: a replay
/// would draw different values than the original run did.
pub fn rand(&self) -> &WorkflowRand {
&self.rand
}
/// Returns the time helper.
///
/// `ctx.time().now()` is read from the journal: the workflow's journaled start, then
/// the moment the engine journaled each task result, fired timer, child outcome or
/// event the workflow has received. It is the same at each point in the code on every
/// replay, and so are the `elapsed*` methods, which measure on the same clock. See
/// [`WorkflowTime`].
///
/// # Examples
///
/// ```rust
/// # use orcher_sdk::prelude::*;
/// # use std::time::Duration;
/// # async fn example(ctx: &WorkflowContext) -> Result<()> {
/// // The workflow's current time, the same at this point on every replay.
/// let order_time = ctx.time().now();
///
/// // Measured on the same clock.
/// if ctx.time().elapsed() > Duration::from_secs(3600) {
/// return Err(Error::Workflow(orcher_sdk::error::WorkflowError::StateError(
/// "Workflow timeout exceeded".to_string()
/// )));
/// }
///
/// let elapsed_secs = ctx.time().elapsed_secs();
/// tracing::info!("Workflow running for {} seconds", elapsed_secs);
/// # Ok(())
/// # }
/// ```
///
/// Never read `SystemTime::now()` in workflow code: a replay would see a different
/// time than the original run did.
pub fn time(&self) -> &WorkflowTime {
&self.time
}
// ============================================================================
// Restart fresh
// ============================================================================
/// Ends this run and starts a new one with the same workflow id and an empty history.
///
/// Long-running workflows (periodic jobs, subscriptions, workflows that model a
/// durable entity) use this to keep their history from growing without bound, and to
/// pick up new code periodically.
///
/// The new run has a new run id, an empty history, and fresh `ctx.rand()` and
/// `ctx.time()`. It keeps the workflow type and task queue and gets empty input; no
/// state carries over. To pass state, or to change the type or queue, use
/// [`restart_fresh_with`](Self::restart_fresh_with).
///
/// This only emits the RestartFresh command; the workflow should return afterward.
///
/// # Example
///
/// ```rust
/// # use orcher_sdk::prelude::*;
/// use std::time::Duration;
///
/// async fn nightly_cleanup(ctx: WorkflowContext) -> Result<()> {
/// let removed: u64 = ctx.execute_task("remove_expired_sessions", ()).await?;
/// tracing::info!(removed, "cleanup finished");
///
/// // Wait for the next night.
/// ctx.sleep(Duration::from_secs(24 * 3600)).await?;
///
/// // Start the next cycle with an empty history.
/// ctx.restart_fresh()
/// }
/// ```
pub fn restart_fresh(&self) -> Result<()> {
// `None` keeps the current value.
let command = WorkflowCommand::RestartFresh(RestartFreshCommand {
workflow_type: None,
input: vec![],
task_queue: None,
timeout: None,
retry_policy: None,
});
self.add_command(command);
tracing::info!(
workflow_id = %self.execution.workflow_id,
workflow_type = %self.execution.workflow_type,
"Workflow restarting with fresh execution"
);
Ok(())
}
/// Like [`restart_fresh`](Self::restart_fresh), but passes `input` to the new run and
/// can change its workflow type, task queue or timeout through `options`.
///
/// Changing the workflow type is a way to move a long-running workflow onto new code.
///
/// # Errors
///
/// Returns an error if `input` cannot be serialized.
///
/// # Example
///
/// ```rust
/// # use orcher_sdk::prelude::*;
/// # use std::time::Duration;
/// #[derive(Serialize, Deserialize)]
/// struct SubscriptionState {
/// user_id: String,
/// cycle: u32,
/// amount: f64,
/// }
///
/// #[workflow]
/// async fn subscription(ctx: WorkflowContext, state: SubscriptionState) -> Result<()> {
/// let _charge_id: String = ctx
/// .execute_task("charge_customer", state.user_id.clone())
/// .await?;
///
/// // Wait for the next billing cycle.
/// ctx.sleep(Duration::from_secs(30 * 24 * 3600)).await?;
///
/// // Carry the state the next cycle needs.
/// let next_state = SubscriptionState {
/// user_id: state.user_id,
/// cycle: state.cycle + 1,
/// amount: state.amount,
/// };
///
/// ctx.restart_fresh_with(
/// next_state,
/// Some(RestartFreshOptions::new().timeout(Duration::from_secs(3600))),
/// )
/// }
/// ```
///
/// Moving to a new workflow type:
///
/// ```rust
/// # use orcher_sdk::prelude::*;
/// #[workflow]
/// async fn old_workflow(ctx: WorkflowContext, data: String) -> Result<()> {
/// ctx.restart_fresh_with(
/// data,
/// Some(
/// RestartFreshOptions::new()
/// .workflow_type("NewWorkflowV2")
/// .task_queue("upgraded-queue"),
/// ),
/// )
/// }
/// ```
pub fn restart_fresh_with<T: Serialize>(
&self,
input: T,
options: Option<RestartFreshOptions>,
) -> Result<()> {
let input_bytes = serde_json::to_vec(&input).map_err(|e| {
Error::Serialization(format!("Failed to serialize restart input: {}", e))
})?;
let opts = options.unwrap_or_default();
let command = WorkflowCommand::RestartFresh(RestartFreshCommand {
workflow_type: opts.workflow_type,
input: input_bytes,
task_queue: opts.task_queue,
timeout: opts.timeout,
retry_policy: opts.retry_policy,
});
self.add_command(command);
tracing::info!(
workflow_id = %self.execution.workflow_id,
current_workflow_type = %self.execution.workflow_type,
"Workflow restarting with fresh execution and new input"
);
Ok(())
}
// ============================================================================
// Metadata
// ============================================================================
/// Returns the workflow id.
pub fn workflow_id(&self) -> &str {
&self.execution.workflow_id
}
/// Returns the run id, which is unique to this run.
pub fn run_id(&self) -> &str {
&self.execution.run_id
}
/// Returns `true` while the code is re-running what an earlier activation of the
/// run already ran, and `false` once it is past that and doing something for the
/// first time.
///
/// A run's code runs again from the start each time it is activated, receiving the
/// outcomes it waited for from its history. Until it has received the newest outcome
/// this activation holds, everything it does was done before; from then on it is new.
/// So it is `false` throughout a run's first activation, and in a later one it turns
/// `false` at the point the code reaches work the history has no outcome for.
///
/// Use it to avoid repeating logs or metrics on replay. Do not use it to decide
/// whether to perform an effect: run effects as tasks, which the engine records, so
/// they happen once whatever the code's replays.
///
/// It is exact when the engine marks which of an activation's outcomes the run has
/// already observed. Without those marks the newest outcome is taken as the new one,
/// which is off in two cases: an activation with several new outcomes (two tasks that
/// finished together) reads `true` until the code has received the newest, and one
/// with no new outcome at all (for a query) reads `false` past the newest outcome.
pub fn is_replaying(&self) -> bool {
let state = self.state.lock().unwrap();
state
.outcomes
.replaying(state.received_through.get())
// No outcome noted: a context built by hand rather than from an activation,
// which says itself whether it replays.
.unwrap_or(state.replaying)
}
/// Returns the attempt number, starting at 1.
pub fn attempt(&self) -> i32 {
self.execution.attempt
}
/// Returns the workflow type name.
pub fn workflow_type(&self) -> &str {
&self.execution.workflow_type
}
/// Returns the namespace.
pub fn namespace(&self) -> &str {
&self.execution.namespace
}
/// Returns the task queue.
pub fn task_queue(&self) -> &str {
&self.execution.task_queue
}
/// Returns the workflow's version string, a metadata label only.
///
/// It is an identifier for metrics and inventory, not a replay-safety mechanism: the
/// engine does not gate or route replay by version. To change workflow logic safely,
/// run the new code under a new workflow name alongside the old one, or reset the
/// execution. Do not branch on this value.
pub fn version(&self) -> &str {
&self.version
}
// ========================================================================
// Runtime and test hooks
// ========================================================================
//
// Public rather than cfg(test): the worker runtime and the crate's `testing`
// module use them. Most are #[doc(hidden)].
/// Records a result for `task_id`, so a replaying workflow receives it as that
/// task's output. For tests.
///
/// # Example
///
/// ```rust
/// # use orcher_sdk::workflow::{WorkflowContext, WorkflowExecution};
/// # let execution = WorkflowExecution {
/// # workflow_id: "test".to_string(),
/// # run_id: "run".to_string(),
/// # workflow_type: "Test".to_string(),
/// # attempt: 1,
/// # namespace: "test".to_string(),
/// # task_queue: "test".to_string(),
/// # };
/// let mut ctx = WorkflowContext::new(execution, false, "1.0.0".to_string());
/// ctx.inject_task_result_for_test("task_1".to_string(), vec![1, 2, 3]);
/// ```
#[doc(hidden)]
pub fn inject_task_result_for_test(&self, task_id: String, result: Vec<u8>) {
let mut state = self.state.lock().unwrap();
state.pending_task_results.insert(task_id, result);
}
/// Caches the workflow input for later invocations of the handler.
///
/// The runtime calls this after extracting the input from the execution request. A
/// handler can be invoked more than once in one activation, for example in an event
/// loop, and later invocations do not get the jobs to extract the input from.
pub fn cache_input(&self, input: crate::payload::Payload) {
let mut state = self.state.lock().unwrap();
state.cached_input = Some(input);
}
/// Returns the input stored by [`cache_input`](Self::cache_input), if any.
pub fn get_cached_input(&self) -> Option<crate::payload::Payload> {
let state = self.state.lock().unwrap();
state.cached_input.clone()
}
/// Records results for many steps at once, keyed by step name.
///
/// On replay, each step (task, closure or child workflow) that finds a recorded result
/// returns it instead of running again. The server sends recorded step results in the
/// journal as StepCompleted entries:
///
/// ```text
/// Server: returns the journal, including a StepCompleted entry per finished step.
/// SDK: injects those results, marks the context as replaying, and runs the
/// workflow, which reads the results instead of running the steps.
/// ```
///
/// # Example
///
/// ```rust
/// # use orcher_sdk::prelude::*;
/// # use std::collections::HashMap;
/// # fn example(ctx: &WorkflowContext) {
/// let mut step_results = HashMap::new();
/// step_results.insert("fetch_user_1".to_string(), vec![/* result bytes */]);
/// step_results.insert("query_orders_2".to_string(), vec![/* result bytes */]);
///
/// ctx.inject_step_results(step_results);
/// ctx.set_replaying_for_test(true);
///
/// // The steps named above return the recorded bytes.
/// # }
/// ```
#[doc(hidden)]
pub fn inject_step_results(&self, step_results: std::collections::HashMap<String, Vec<u8>>) {
let mut state = self.state.lock().unwrap();
for (step_name, result) in step_results {
state.pending_task_results.insert(step_name, result);
}
}
/// Whether the workflow has been told it is being cancelled.
///
/// True from the wait at which the code learned of the request onwards: that wait
/// returned [`WorkflowError::Canceled`](crate::error::WorkflowError::Canceled), and
/// everything after it is the workflow's cleanup, which runs normally. A long loop
/// that does not wait can check this to stop early. Read from the journal, so it
/// answers the same at the same point on every replay.
pub fn is_cancel_requested(&self) -> bool {
self.state.lock().unwrap().cancel_delivered
}
/// Records that the journal holds a request to cancel the workflow, at `order` in
/// the order the run observes its outcomes when known. The first request is the one
/// the run is told of; a later one changes nothing.
pub(crate) fn note_cancel_requested(&self, order: Option<u64>) {
let mut state = self.state.lock().unwrap();
if state.cancel_requested {
return;
}
state.cancel_requested = true;
state.cancel_requested_order = order;
}
/// `Err(Canceled)` when this wait is where the code learns of a cancellation
/// request; see [`ContextState::take_cancellation`].
fn cancellation_at(&self, result: Option<Option<u64>>) -> Result<()> {
if self.state.lock().unwrap().take_cancellation(result) {
return Err(Error::Workflow(crate::error::WorkflowError::Canceled));
}
Ok(())
}
/// As [`cancellation_at`](Self::cancellation_at), for the result injected under `key`.
pub(crate) fn cancellation_for(&self, key: &str) -> Result<()> {
let result = self.state.lock().unwrap().result_seen(key);
self.cancellation_at(result)
}
/// Records the result of one step (for example `"fetch_user_1"`) and marks it as a
/// task. The runtime calls this for each result in the journal.
#[doc(hidden)]
pub fn inject_step_result(&self, step_name: String, result: Vec<u8>) {
let mut state = self.state.lock().unwrap();
state.pending_task_results.insert(step_name.clone(), result);
// Mark it as a task so extract_closure_commands does not treat it as a closure.
state.step_type_map.insert(step_name, 0);
}
/// Marks a durable timer as fired, with no known position. `sleep` and
/// `sleep_with_id` check this so they return instead of emitting StartTimer again.
#[cfg(test)]
pub(crate) fn mark_timer_fired(&self, timer_id: String) {
self.mark_timer_fired_at(timer_id, None);
}
/// The id of a child started without one, at step `sequence`.
///
/// It is derived from the parent's workflow id and the step sequence, so it is the
/// same on every replay and differs between parents: children of two parents, each
/// started at the same point in its parent's code, do not share an id.
///
/// SDKs up to 0.9.0 used `child_{sequence}`, which every parent shared. A run that
/// started a child under that id keeps it: if the journal records `child_{sequence}`,
/// the child at this sequence is that one, so a run that began under the old default
/// replays to the same child rather than starting another.
pub(crate) fn default_child_workflow_id(&self, sequence: u64) -> String {
if let StepIds::Kernel { lineage } = &self.step_ids {
return kernel_ids::default_child_workflow_id(lineage, sequence);
}
let legacy = format!("child_{}", sequence);
if self
.state
.lock()
.unwrap()
.journaled_children
.contains(&legacy)
{
return legacy;
}
format!("{}-child-{}", self.execution.workflow_id, sequence)
}
/// Records that the journal holds a child started under `workflow_id`.
pub(crate) fn record_journaled_child(&self, workflow_id: String) {
self.state
.lock()
.unwrap()
.journaled_children
.insert(workflow_id);
}
/// Records when the engine journaled the result held under `key` (milliseconds since
/// the UNIX epoch), for the workflow's clock to move to when the result is received.
/// The first time recorded for a key stands.
pub(crate) fn record_resolved_at(&self, key: String, at_ms: i64) {
self.state
.lock()
.unwrap()
.resolved_at
.entry(key)
.or_insert(at_ms);
}
/// Records where the result held under `key` comes in the order the run observes its
/// outcomes, to tell whether it came before a cancellation request. The first
/// recorded for a key stands.
pub(crate) fn record_resolved_order(&self, key: String, order: u64) {
self.state
.lock()
.unwrap()
.resolved_order
.entry(key)
.or_insert(order);
}
/// Notes that this activation holds an outcome for the code to receive, at `order`
/// in the run's order of outcomes, and whether the run already observed it in an
/// earlier activation as the activation marks it.
pub(crate) fn note_outcome(&self, order: u64, seen_before: bool) {
self.state.lock().unwrap().outcomes.note(order, seen_before);
}
/// Marks a durable timer as fired, with its place in the order the run observes its
/// outcomes, so a wait with a timeout can tell whether its event or its deadline came
/// first.
pub(crate) fn mark_timer_fired_at(&self, timer_id: String, position: Option<usize>) {
self.state
.lock()
.unwrap()
.fired_timers
.insert(timer_id, position);
}
/// Sets whether the context is replaying, so tests can simulate a replay.
#[doc(hidden)]
pub fn set_replaying_for_test(&self, replaying: bool) {
let mut state = self.state.lock().unwrap();
state.replaying = replaying;
}
/// Returns a copy of the commands emitted so far, leaving them in place.
#[doc(hidden)]
pub fn commands_for_test(&self) -> Vec<WorkflowCommand> {
let state = self.state.lock().unwrap();
state.commands.clone()
}
/// Removes and returns the commands emitted so far.
#[doc(hidden)]
pub fn take_commands_for_test(&self) -> Vec<WorkflowCommand> {
let mut state = self.state.lock().unwrap();
std::mem::take(&mut state.commands)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct ApprovalData {
approved: bool,
approver: String,
reason: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct StatusResponse {
status: String,
progress: u32,
total: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct UpdateData {
field: String,
value: String,
}
fn create_test_context() -> WorkflowContext {
let execution = WorkflowExecution {
workflow_id: "test-wf-123".to_string(),
run_id: "run-456".to_string(),
workflow_type: "TestWorkflow".to_string(),
attempt: 1,
namespace: "default".to_string(),
task_queue: "test-queue".to_string(),
};
WorkflowContext::new(execution, false, "1.0".to_string())
}
// Terminal task failures
/// The result the runtime injects for a task that failed for good.
fn task_failure_sentinel(message: &str, attempts: u32) -> Vec<u8> {
serde_json::to_vec(&serde_json::json!({
crate::error::TASK_FAILED_SENTINEL_KEY: true,
"message": message,
"error_type": "TaskError",
"attempts": attempts,
}))
.unwrap()
}
fn task_failed(result: Result<String>) -> (String, u32, String) {
match result {
Err(Error::Workflow(crate::error::WorkflowError::TaskFailed {
task_type,
attempts,
reason,
..
})) => (task_type, attempts, reason),
other => panic!("expected TaskFailed, got {other:?}"),
}
}
#[tokio::test]
async fn create_session_raises_a_failed_creation_as_task_failed() {
use crate::workflow::session::{SessionOptions, SESSION_CREATE_TASK};
let ctx = create_test_context();
ctx.set_replaying_for_test(true);
ctx.inject_step_result(
format!("{SESSION_CREATE_TASK}_0"),
task_failure_sentinel("Resource exhausted: session slots (1/1 in use)", 1),
);
let result = ctx.create_session(SessionOptions::default()).await;
match result {
Err(Error::Workflow(crate::error::WorkflowError::TaskFailed {
task_type,
reason,
..
})) => {
assert_eq!(task_type, SESSION_CREATE_TASK);
assert!(reason.contains("session slots"), "{reason}");
}
Err(other) => panic!("expected TaskFailed, got {other:?}"),
Ok(_) => panic!("expected TaskFailed, got a session"),
}
}
/// A sentinel journaled before failures carried a category still decodes,
/// keeping its type and leaving the category unspecified.
#[tokio::test]
async fn a_sentinel_without_a_category_decodes_as_unspecified() {
let ctx = create_test_context();
ctx.set_replaying_for_test(true);
ctx.inject_step_result(
"charge_0".to_string(),
task_failure_sentinel("card declined", 1),
);
match ctx.execute_task::<_, _, String>("charge", 5u32).await {
Err(Error::Workflow(crate::error::WorkflowError::TaskFailed {
error_type,
code,
..
})) => {
assert_eq!(error_type, "TaskError");
assert_eq!(code, crate::error::TaskFailureCode::Unspecified);
}
other => panic!("expected TaskFailed, got {other:?}"),
}
}
#[tokio::test]
async fn execute_task_raises_a_terminal_task_failure() {
let ctx = create_test_context();
ctx.set_replaying_for_test(true);
ctx.inject_step_result(
"charge_0".to_string(),
task_failure_sentinel("card declined", 3),
);
let result = ctx.execute_task::<_, _, String>("charge", 5u32).await;
assert_eq!(
task_failed(result),
("charge".to_string(), 3, "card declined".to_string())
);
}
#[tokio::test]
#[allow(deprecated)]
async fn execute_task_with_options_raises_a_terminal_task_failure() {
let ctx = create_test_context();
ctx.set_replaying_for_test(true);
ctx.inject_step_result(
"task_0".to_string(),
task_failure_sentinel("card declined", 3),
);
let result = ctx
.execute_task_with_options::<_, String>("charge", 5u32, TaskOptions::default())
.await;
assert_eq!(
task_failed(result),
("charge".to_string(), 3, "card declined".to_string())
);
}
#[tokio::test]
#[allow(deprecated)]
async fn execute_task_with_options_raises_a_failure_under_a_given_task_id() {
let ctx = create_test_context();
ctx.set_replaying_for_test(true);
ctx.inject_step_result(
"charge-once".to_string(),
task_failure_sentinel("timed out", 1),
);
let result = ctx
.execute_task_with_options::<_, String>(
"charge",
5u32,
TaskOptions::default().with_task_id("charge-once"),
)
.await;
assert_eq!(
task_failed(result),
("charge".to_string(), 1, "timed out".to_string())
);
}
// Child workflow ids
fn context_of(parent_id: &str) -> WorkflowContext {
let execution = WorkflowExecution {
workflow_id: parent_id.to_string(),
run_id: format!("{parent_id}-run"),
workflow_type: "ParentWorkflow".to_string(),
attempt: 1,
namespace: "default".to_string(),
task_queue: "test-queue".to_string(),
};
WorkflowContext::new(execution, false, "1.0".to_string())
}
#[tokio::test]
async fn children_of_different_parents_get_different_default_ids() {
let a = context_of("order-a")
.start_child_workflow("charge", ())
.await
.unwrap();
let b = context_of("order-b")
.start_child_workflow("charge", ())
.await
.unwrap();
assert_ne!(a.id(), b.id());
assert_eq!(a.id(), "order-a-child-0");
assert_eq!(b.id(), "order-b-child-0");
}
#[tokio::test]
async fn a_default_child_id_is_the_same_on_every_replay() {
let mut ids = Vec::new();
for _ in 0..2 {
let ctx = context_of("order-a");
ctx.execute_task::<_, _, ()>("reserve", ()).await.ok();
let child = ctx.start_child_workflow("charge", ()).await.unwrap();
ids.push(child.id().to_string());
}
assert_eq!(ids, ["order-a-child-1", "order-a-child-1"]);
}
#[tokio::test]
async fn an_explicit_child_id_is_kept() {
let child = context_of("order-a")
.start_child_workflow_with_options(
"charge",
(),
ChildWorkflowOptions::new().workflow_id("charge-order-a"),
)
.await
.unwrap();
assert_eq!(child.id(), "charge-order-a");
}
// Cancellation requests
/// A context replaying a history in which `work_0` completed (the run's second
/// outcome) and then the cancellation request came (its third).
fn context_asked_to_cancel() -> WorkflowContext {
let ctx = create_test_context();
ctx.set_replaying_for_test(true);
ctx.inject_step_result("work_0".to_string(), serde_json::to_vec(&1).unwrap());
ctx.record_resolved_order("work_0".to_string(), 2);
ctx.note_cancel_requested(Some(3));
ctx
}
fn is_canceled(result: &Result<u32>) -> bool {
matches!(
result,
Err(Error::Workflow(crate::error::WorkflowError::Canceled))
)
}
#[tokio::test]
async fn a_result_from_before_the_request_is_received() {
let ctx = context_asked_to_cancel();
let first: Result<u32> = ctx.execute_task_by_name("work", 0).await;
assert_eq!(first.unwrap(), 1);
assert!(
!ctx.is_cancel_requested(),
"not told until a wait is cut short"
);
}
#[tokio::test]
async fn the_first_wait_without_an_earlier_result_is_told_once() {
let ctx = context_asked_to_cancel();
let _: Result<u32> = ctx.execute_task_by_name("work", 0).await;
let interrupted: Result<u32> = ctx.execute_task_by_name("work", 1).await;
assert!(is_canceled(&interrupted));
assert!(ctx.is_cancel_requested());
// Cleanup: the next wait is scheduled as usual, not cancelled again.
let cleanup: Result<u32> = ctx.execute_task_by_name("refund", 2).await;
assert!(matches!(
cleanup,
Err(Error::Workflow(
crate::error::WorkflowError::Suspended { .. }
))
));
}
/// On a later replay the interrupted step may have a result of its own, recorded
/// after the request. It is still where the request is delivered, or the code
/// would take a different path than it did when it was first told.
#[tokio::test]
async fn the_same_wait_is_told_on_every_replay() {
let ctx = context_asked_to_cancel();
ctx.inject_step_result("work_1".to_string(), serde_json::to_vec(&2).unwrap());
ctx.record_resolved_order("work_1".to_string(), 4);
let _: Result<u32> = ctx.execute_task_by_name("work", 0).await;
let interrupted: Result<u32> = ctx.execute_task_by_name("work", 1).await;
assert!(is_canceled(&interrupted));
}
/// A result and the request recorded in the same millisecond: the run's order of
/// outcomes says which came first, never their times.
#[tokio::test]
async fn a_result_in_the_requests_millisecond_is_ordered_by_sequence() {
let asked = |result_order: u64, request_order: u64| {
let ctx = create_test_context();
ctx.set_replaying_for_test(true);
ctx.inject_step_result("work_0".to_string(), serde_json::to_vec(&1).unwrap());
ctx.record_resolved_at("work_0".to_string(), 2_000);
ctx.record_resolved_order("work_0".to_string(), result_order);
ctx.note_cancel_requested(Some(request_order));
ctx
};
let before = asked(2, 3);
let first: Result<u32> = before.execute_task_by_name("work", 0).await;
assert_eq!(first.unwrap(), 1);
assert!(!before.is_cancel_requested());
let after = asked(3, 2);
let first: Result<u32> = after.execute_task_by_name("work", 0).await;
assert!(is_canceled(&first));
assert!(after.is_cancel_requested());
}
/// A result whose place in the run's order is not known exists, so it is received.
#[tokio::test]
async fn a_result_with_no_known_place_is_received() {
let ctx = create_test_context();
ctx.set_replaying_for_test(true);
ctx.inject_step_result("work_0".to_string(), serde_json::to_vec(&1).unwrap());
ctx.note_cancel_requested(Some(2));
let first: Result<u32> = ctx.execute_task_by_name("work", 0).await;
assert_eq!(first.unwrap(), 1);
}
/// Only the first request is the one the run is told of.
#[tokio::test]
async fn a_second_request_does_not_move_the_first() {
let ctx = create_test_context();
ctx.set_replaying_for_test(true);
ctx.inject_step_result("work_0".to_string(), serde_json::to_vec(&1).unwrap());
ctx.record_resolved_order("work_0".to_string(), 3);
ctx.note_cancel_requested(Some(2));
ctx.note_cancel_requested(Some(4));
let first: Result<u32> = ctx.execute_task_by_name("work", 0).await;
assert!(is_canceled(&first));
}
#[tokio::test]
async fn without_a_request_nothing_is_cancelled() {
let ctx = create_test_context();
ctx.set_replaying_for_test(true);
let pending: Result<u32> = ctx.execute_task_by_name("work", 0).await;
assert!(!is_canceled(&pending));
assert!(!ctx.is_cancel_requested());
}
#[tokio::test]
async fn a_sleep_whose_timer_had_not_fired_is_told() {
let ctx = create_test_context();
ctx.set_replaying_for_test(true);
ctx.note_cancel_requested(Some(2));
let slept = ctx.sleep(Duration::from_secs(600)).await;
assert!(matches!(
slept,
Err(Error::Workflow(crate::error::WorkflowError::Canceled))
));
}
#[tokio::test]
async fn an_event_that_came_before_the_request_is_received() {
let ctx = create_test_context();
ctx.set_replaying_for_test(true);
ctx.buffer_journaled_event(
"go".to_string(),
serde_json::to_vec(&7).unwrap(),
Some(2),
Some(1_000),
);
ctx.note_cancel_requested(Some(3));
let received: u32 = ctx.wait_for_event("go").await.unwrap();
assert_eq!(received, 7);
let next: Result<u32> = ctx.wait_for_event("go").await;
assert!(is_canceled(&next));
}
#[tokio::test]
async fn an_event_that_came_after_the_request_is_where_it_is_told() {
let ctx = create_test_context();
ctx.set_replaying_for_test(true);
ctx.buffer_journaled_event(
"go".to_string(),
serde_json::to_vec(&7).unwrap(),
Some(3),
Some(2_000),
);
ctx.note_cancel_requested(Some(2));
let told: Result<u32> = ctx.wait_for_event("go").await;
assert!(is_canceled(&told));
}
// Event buffering tests
#[tokio::test]
async fn test_buffer_and_retrieve_event() {
let ctx = create_test_context();
let approval = ApprovalData {
approved: true,
approver: "manager@example.com".to_string(),
reason: "Looks good".to_string(),
};
let event_bytes = serde_json::to_vec(&approval).unwrap();
ctx.buffer_event("approve", event_bytes);
let retrieved: ApprovalData = ctx.wait_for_event("approve").await.unwrap();
assert_eq!(retrieved, approval);
}
#[tokio::test]
async fn test_buffer_multiple_events_same_name() {
let ctx = create_test_context();
let approval1 = ApprovalData {
approved: true,
approver: "manager1@example.com".to_string(),
reason: "First approval".to_string(),
};
let approval2 = ApprovalData {
approved: false,
approver: "manager2@example.com".to_string(),
reason: "Second approval".to_string(),
};
ctx.buffer_event("approve", serde_json::to_vec(&approval1).unwrap());
ctx.buffer_event("approve", serde_json::to_vec(&approval2).unwrap());
// Oldest first, in arrival order, as in the other SDKs. A loop over status
// callbacks must see them in the order they were sent.
let retrieved1: ApprovalData = ctx.wait_for_event("approve").await.unwrap();
assert_eq!(retrieved1, approval1);
let retrieved2: ApprovalData = ctx.wait_for_event("approve").await.unwrap();
assert_eq!(retrieved2, approval2);
}
#[tokio::test]
async fn test_buffer_different_event_names() {
let ctx = create_test_context();
let approval = ApprovalData {
approved: true,
approver: "manager@example.com".to_string(),
reason: "Approved".to_string(),
};
let update = UpdateData {
field: "status".to_string(),
value: "updated".to_string(),
};
ctx.buffer_event("approve", serde_json::to_vec(&approval).unwrap());
ctx.buffer_event("update", serde_json::to_vec(&update).unwrap());
let retrieved_update: UpdateData = ctx.wait_for_event("update").await.unwrap();
assert_eq!(retrieved_update, update);
let retrieved_approval: ApprovalData = ctx.wait_for_event("approve").await.unwrap();
assert_eq!(retrieved_approval, approval);
}
#[tokio::test]
async fn test_wait_for_event_not_buffered() {
let ctx = create_test_context();
let result: Result<ApprovalData> = ctx.wait_for_event("approve").await;
assert!(result.is_err());
}
/// Suspending is the normal outcome when the event has not arrived, and it is the
/// path where holding the state lock would deadlock.
#[tokio::test]
async fn test_wait_for_event_with_timeout_not_buffered() {
let ctx = create_test_context();
let result: Result<Option<ApprovalData>> = ctx
.wait_for_event_with_timeout("approve", Duration::from_secs(60))
.await;
assert!(
result.is_err(),
"waiting for an event that has not arrived must suspend, not return"
);
}
#[tokio::test]
async fn test_wait_for_event_with_timeout_buffered() {
let ctx = create_test_context();
let approval = ApprovalData {
approved: true,
approver: "manager@example.com".to_string(),
reason: "Quick approval".to_string(),
};
ctx.buffer_event("approve", serde_json::to_vec(&approval).unwrap());
let result: Option<ApprovalData> = ctx
.wait_for_event_with_timeout("approve", Duration::from_secs(60))
.await
.unwrap();
assert!(result.is_some());
assert_eq!(result.unwrap(), approval);
}
// The timeout is a durable timer raced against the event.
fn timer_ids(commands: &[WorkflowCommand]) -> Vec<String> {
commands
.iter()
.filter_map(|c| match c {
WorkflowCommand::StartTimer(t) => Some(t.timer_id.clone()),
_ => None,
})
.collect()
}
#[tokio::test]
async fn timed_wait_parks_on_the_event_and_starts_a_deadline_timer() {
let ctx = create_test_context();
let result: Result<Option<ApprovalData>> = ctx
.wait_for_event_with_timeout("approve", Duration::from_secs(5))
.await;
assert!(result.is_err(), "must suspend");
let commands = ctx.take_commands();
assert_eq!(commands.len(), 2);
assert!(matches!(
&commands[0],
WorkflowCommand::WaitForEvent(w) if w.event_name == "approve"
));
match &commands[1] {
WorkflowCommand::StartTimer(t) => {
assert_eq!(t.timer_id, "event_timeout_approve_1");
assert_eq!(t.duration, Duration::from_secs(5));
}
other => panic!("expected StartTimer, got {other:?}"),
}
}
#[tokio::test]
async fn timed_wait_returns_none_once_the_deadline_fired() {
let ctx = create_test_context();
ctx.mark_timer_fired("event_timeout_approve_1".to_string());
let result: Option<ApprovalData> = ctx
.wait_for_event_with_timeout("approve", Duration::from_secs(5))
.await
.unwrap();
assert!(result.is_none());
assert!(ctx.take_commands().is_empty());
}
#[tokio::test]
async fn timed_wait_takes_an_event_that_arrived_before_the_deadline() {
let ctx = create_test_context();
ctx.buffer_event_at("status", br#"{"early":true}"#.to_vec(), Some(2));
ctx.mark_timer_fired_at("event_timeout_status_1".to_string(), Some(5));
let result: Option<serde_json::Value> = ctx
.wait_for_event_with_timeout("status", Duration::from_secs(1))
.await
.unwrap();
assert_eq!(result, Some(serde_json::json!({"early": true})));
}
#[tokio::test]
async fn timed_out_wait_stays_timed_out_when_the_event_arrives_later() {
// Journal: the deadline fired (position 3), then the event (7). An
// earlier activation took the timeout branch; the replay must too,
// and the event belongs to the next wait.
let ctx = create_test_context();
ctx.mark_timer_fired_at("event_timeout_status_1".to_string(), Some(3));
ctx.buffer_event_at("status", br#"{"late":true}"#.to_vec(), Some(7));
let first: Option<serde_json::Value> = ctx
.wait_for_event_with_timeout("status", Duration::from_secs(1))
.await
.unwrap();
assert_eq!(first, None);
let second: Option<serde_json::Value> = ctx
.wait_for_event_with_timeout("status", Duration::from_secs(1))
.await
.unwrap();
assert_eq!(second, Some(serde_json::json!({"late": true})));
}
#[tokio::test]
async fn timed_wait_consumes_no_sequence_when_it_returns() {
// Step ids after the wait must match whether the event was there or
// not, or a replay would re-schedule work that already ran.
let ctx = create_test_context();
ctx.buffer_event("approve", br#"{"ok":true}"#.to_vec());
let before = ctx.state.lock().unwrap().sequence;
let _: Option<serde_json::Value> = ctx
.wait_for_event_with_timeout("approve", Duration::from_secs(1))
.await
.unwrap();
assert_eq!(ctx.state.lock().unwrap().sequence, before);
}
#[tokio::test]
async fn a_wait_takes_no_step_number_when_it_parks_either() {
// Parking and returning must agree, or a step issued beside a wait
// that parked gets another id once the event is there.
let ctx = create_test_context();
let before = ctx.state.lock().unwrap().sequence;
let parked: Result<serde_json::Value> = ctx.wait_for_event("approve").await;
assert!(parked.is_err());
let parked: Result<Option<serde_json::Value>> = ctx
.wait_for_event_with_timeout("status", Duration::from_secs(1))
.await;
assert!(parked.is_err());
assert_eq!(ctx.state.lock().unwrap().sequence, before);
}
#[tokio::test]
async fn deadline_timers_are_numbered_per_event_name() {
// Allocated on every path: the first wait returns a buffered event,
// and the second still gets the second id.
let ctx = create_test_context();
ctx.buffer_event("status", br#"{"round":1}"#.to_vec());
let _: Option<serde_json::Value> = ctx
.wait_for_event_with_timeout("status", Duration::from_secs(1))
.await
.unwrap();
let _: Result<Option<serde_json::Value>> = ctx
.wait_for_event_with_timeout("status", Duration::from_secs(1))
.await;
let _: Result<Option<serde_json::Value>> = ctx
.wait_for_event_with_timeout("other", Duration::from_secs(1))
.await;
assert_eq!(
timer_ids(&ctx.take_commands()),
vec!["event_timeout_status_2", "event_timeout_other_1"]
);
}
#[tokio::test]
async fn timed_wait_rejects_a_zero_timeout() {
let ctx = create_test_context();
let result: Result<Option<serde_json::Value>> = ctx
.wait_for_event_with_timeout("approve", Duration::ZERO)
.await;
assert!(result.is_err());
assert!(ctx.take_commands().is_empty());
}
// Query handler tests
#[test]
fn test_register_query_handler_simple() {
let ctx = create_test_context();
ctx.register_query_handler("get_status", || "processing".to_string());
let result = ctx.handle_query_request("get_status", &[]).unwrap();
let status: String = serde_json::from_slice(&result).unwrap();
assert_eq!(status, "processing");
}
#[test]
fn test_register_query_handler_complex() {
let ctx = create_test_context();
ctx.register_query_handler("get_progress", || StatusResponse {
status: "in_progress".to_string(),
progress: 42,
total: 100,
});
let result = ctx.handle_query_request("get_progress", &[]).unwrap();
let response: StatusResponse = serde_json::from_slice(&result).unwrap();
assert_eq!(response.status, "in_progress");
assert_eq!(response.progress, 42);
assert_eq!(response.total, 100);
}
#[test]
fn a_query_handler_receives_the_client_arguments() {
let ctx = create_test_context();
ctx.register_query_handler_with_args("double", |n: u32| n * 2);
let result = ctx.handle_query_request("double", b"21").unwrap();
assert_eq!(serde_json::from_slice::<u32>(&result).unwrap(), 42);
}
#[test]
fn a_query_sent_without_arguments_decodes_from_null() {
let ctx = create_test_context();
ctx.register_query_handler_with_args("greet", |name: Option<String>| {
format!("hello {}", name.unwrap_or_else(|| "there".to_string()))
});
let result = ctx.handle_query_request("greet", &[]).unwrap();
assert_eq!(
serde_json::from_slice::<String>(&result).unwrap(),
"hello there"
);
}
#[test]
fn query_arguments_that_do_not_decode_fail_the_query() {
let ctx = create_test_context();
ctx.register_query_handler_with_args("double", |n: u32| n * 2);
let err = ctx
.handle_query_request("double", br#""not a number""#)
.unwrap_err();
assert!(matches!(
err,
Error::Workflow(crate::error::WorkflowError::QueryError { ref reason, .. })
if reason.contains("invalid query arguments")
));
}
#[test]
fn a_query_result_that_cannot_be_serialized_fails_the_query() {
// A map with non-string keys has no JSON form.
let ctx = create_test_context();
ctx.register_query_handler("bad", || std::collections::HashMap::from([((1, 2), "x")]));
let err = ctx.handle_query_request("bad", &[]).unwrap_err();
assert!(matches!(
err,
Error::Workflow(crate::error::WorkflowError::QueryError { ref reason, .. })
if reason.contains("could not be serialized")
));
}
#[test]
fn outcome_marks_take_the_newest_outcome_as_new_when_unmarked() {
let mut marks = OutcomeMarks::default();
assert_eq!(marks.replaying(0), None, "no outcome: the context says");
marks.note(2, false);
marks.note(5, false);
assert_eq!(marks.replaying(0), Some(true));
assert_eq!(marks.replaying(2), Some(true));
assert_eq!(marks.replaying(5), Some(false));
}
#[test]
fn outcome_marks_replay_until_the_first_new_outcome_when_marked() {
let mut marks = OutcomeMarks::default();
marks.note(1, true);
marks.note(3, false);
marks.note(4, false);
assert_eq!(marks.replaying(1), Some(true));
// Two outcomes new together: new from the first of them.
assert_eq!(marks.replaying(3), Some(false));
}
#[test]
fn outcome_marks_replay_throughout_an_activation_with_nothing_new() {
// An activation for a query: every outcome was seen before.
let mut marks = OutcomeMarks::default();
marks.note(1, true);
marks.note(2, true);
assert_eq!(marks.replaying(2), Some(true));
}
#[test]
fn an_event_seen_before_and_never_received_does_not_hold_replay() {
// An event that came after its wait gave up stays unreceived; the code is new
// once it receives what is new, whatever is left behind.
let mut marks = OutcomeMarks::default();
marks.note(2, true); // the timer that ended the wait
marks.note(3, true); // the late event, never received
marks.note(4, false); // a task result that is new
assert_eq!(marks.replaying(2), Some(true));
assert_eq!(marks.replaying(4), Some(false));
}
#[test]
fn test_register_multiple_query_handlers() {
let ctx = create_test_context();
ctx.register_query_handler("get_status", || "running".to_string());
ctx.register_query_handler("get_count", || 42u32);
ctx.register_query_handler("is_ready", || true);
let status_result = ctx.handle_query_request("get_status", &[]).unwrap();
let status: String = serde_json::from_slice(&status_result).unwrap();
assert_eq!(status, "running");
let count_result = ctx.handle_query_request("get_count", &[]).unwrap();
let count: u32 = serde_json::from_slice(&count_result).unwrap();
assert_eq!(count, 42);
let ready_result = ctx.handle_query_request("is_ready", &[]).unwrap();
let ready: bool = serde_json::from_slice(&ready_result).unwrap();
assert!(ready);
}
#[test]
fn test_query_handler_not_registered() {
let ctx = create_test_context();
let result = ctx.handle_query_request("unknown_query", &[]);
assert!(result.is_err());
}
#[test]
fn test_query_handler_override() {
let ctx = create_test_context();
ctx.register_query_handler("get_status", || "initial".to_string());
ctx.register_query_handler("get_status", || "updated".to_string());
let result = ctx.handle_query_request("get_status", &[]).unwrap();
let status: String = serde_json::from_slice(&result).unwrap();
assert_eq!(status, "updated");
}
#[tokio::test]
async fn test_event_deserialization_error() {
let ctx = create_test_context();
ctx.buffer_event("approve", b"invalid json".to_vec());
let result: Result<ApprovalData> = ctx.wait_for_event("approve").await;
assert!(result.is_err());
}
// Automatic query tests
#[test]
fn test_automatic_queries_workflow_id() {
let ctx = create_test_context();
let result = ctx.handle_query_request("workflow_id", &[]).unwrap();
let wf_id: String = serde_json::from_slice(&result).unwrap();
assert_eq!(wf_id, "test-wf-123");
}
#[test]
fn test_automatic_queries_workflow_type() {
let ctx = create_test_context();
let result = ctx.handle_query_request("workflow_type", &[]).unwrap();
let wf_type: String = serde_json::from_slice(&result).unwrap();
assert_eq!(wf_type, "TestWorkflow");
}
#[test]
fn test_automatic_queries_run_id() {
let ctx = create_test_context();
let result = ctx.handle_query_request("run_id", &[]).unwrap();
let run_id: String = serde_json::from_slice(&result).unwrap();
assert_eq!(run_id, "run-456");
}
#[test]
fn test_automatic_queries_is_replaying() {
let ctx = create_test_context();
let result = ctx.handle_query_request("is_replaying", &[]).unwrap();
let replaying: bool = serde_json::from_slice(&result).unwrap();
assert!(!replaying);
}
#[test]
fn test_automatic_queries_attempt() {
let ctx = create_test_context();
let result = ctx.handle_query_request("attempt", &[]).unwrap();
let attempt: i32 = serde_json::from_slice(&result).unwrap();
assert_eq!(attempt, 1);
}
#[test]
fn test_automatic_queries_version() {
let ctx = create_test_context();
let result = ctx.handle_query_request("version", &[]).unwrap();
let version: String = serde_json::from_slice(&result).unwrap();
assert_eq!(version, "1.0");
}
#[test]
fn test_automatic_queries_namespace() {
let ctx = create_test_context();
let result = ctx.handle_query_request("namespace", &[]).unwrap();
let namespace: String = serde_json::from_slice(&result).unwrap();
assert_eq!(namespace, "default");
}
#[test]
fn test_automatic_queries_task_queue() {
let ctx = create_test_context();
let result = ctx.handle_query_request("task_queue", &[]).unwrap();
let task_queue: String = serde_json::from_slice(&result).unwrap();
assert_eq!(task_queue, "test-queue");
}
#[test]
fn test_automatic_queries_workflow_info() {
let ctx = create_test_context();
let result = ctx.handle_query_request("workflow_info", &[]).unwrap();
let info: serde_json::Value = serde_json::from_slice(&result).unwrap();
assert_eq!(info["workflow_id"], "test-wf-123");
assert_eq!(info["run_id"], "run-456");
assert_eq!(info["workflow_type"], "TestWorkflow");
assert_eq!(info["namespace"], "default");
assert_eq!(info["task_queue"], "test-queue");
assert_eq!(info["attempt"], 1);
assert_eq!(info["version"], "1.0");
assert_eq!(info["is_replaying"], false);
}
#[test]
fn test_automatic_queries_not_overridable_by_user() {
let ctx = create_test_context();
ctx.register_query_handler("workflow_id", || "custom_id".to_string());
// The last registration wins.
let result = ctx.handle_query_request("workflow_id", &[]).unwrap();
let workflow_id: String = serde_json::from_slice(&result).unwrap();
assert_eq!(workflow_id, "custom_id");
}
#[test]
fn test_all_automatic_queries_available() {
let ctx = create_test_context();
let queries = vec![
"workflow_id",
"workflow_type",
"run_id",
"is_replaying",
"attempt",
"version",
"namespace",
"task_queue",
"workflow_info",
];
for query in queries {
let result = ctx.handle_query_request(query, &[]);
assert!(result.is_ok(), "Query '{}' should be available", query);
}
}
// Restart fresh tests
#[test]
fn test_restart_fresh_basic() {
let ctx = create_test_context();
let result = ctx.restart_fresh();
assert!(result.is_ok());
let commands = ctx.take_commands();
assert_eq!(commands.len(), 1);
if let WorkflowCommand::RestartFresh(cmd) = &commands[0] {
assert!(cmd.workflow_type.is_none());
assert!(cmd.task_queue.is_none());
assert!(cmd.timeout.is_none());
assert!(cmd.input.is_empty());
} else {
panic!("Expected RestartFresh command");
}
}
#[test]
fn test_restart_fresh_with_input() {
let ctx = create_test_context();
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
struct State {
counter: u32,
user_id: String,
}
let state = State {
counter: 42,
user_id: "user-123".to_string(),
};
let result = ctx.restart_fresh_with(state.clone(), None);
assert!(result.is_ok());
let commands = ctx.take_commands();
assert_eq!(commands.len(), 1);
if let WorkflowCommand::RestartFresh(cmd) = &commands[0] {
assert!(cmd.workflow_type.is_none());
assert!(!cmd.input.is_empty());
let deserialized: State = serde_json::from_slice(&cmd.input).unwrap();
assert_eq!(deserialized, state);
assert!(cmd.task_queue.is_none());
assert!(cmd.timeout.is_none());
} else {
panic!("Expected RestartFresh command");
}
}
#[test]
fn test_restart_fresh_with_options() {
use crate::workflow::RestartFreshOptions;
let ctx = create_test_context();
let options = RestartFreshOptions::new()
.workflow_type("NewWorkflowV2")
.task_queue("upgraded-queue")
.timeout(Duration::from_secs(3600));
let result = ctx.restart_fresh_with("new_input", Some(options));
assert!(result.is_ok());
let commands = ctx.take_commands();
assert_eq!(commands.len(), 1);
if let WorkflowCommand::RestartFresh(cmd) = &commands[0] {
assert_eq!(cmd.workflow_type.as_deref(), Some("NewWorkflowV2"));
assert_eq!(cmd.task_queue.as_deref(), Some("upgraded-queue"));
assert_eq!(cmd.timeout, Some(Duration::from_secs(3600)));
let deserialized: String = serde_json::from_slice(&cmd.input).unwrap();
assert_eq!(deserialized, "new_input");
} else {
panic!("Expected RestartFresh command");
}
}
#[test]
fn test_restart_fresh_with_partial_options() {
use crate::workflow::RestartFreshOptions;
let ctx = create_test_context();
// Only workflow_type is set; the rest keep their defaults.
let options = RestartFreshOptions::new().workflow_type("NewWorkflow");
let result = ctx.restart_fresh_with(100u32, Some(options));
assert!(result.is_ok());
let commands = ctx.take_commands();
assert_eq!(commands.len(), 1);
if let WorkflowCommand::RestartFresh(cmd) = &commands[0] {
assert_eq!(cmd.workflow_type.as_deref(), Some("NewWorkflow"));
assert!(cmd.task_queue.is_none());
assert!(cmd.timeout.is_none());
} else {
panic!("Expected RestartFresh command");
}
}
#[test]
fn test_restart_fresh_command_is_terminal() {
let ctx = create_test_context();
ctx.restart_fresh().unwrap();
let commands = ctx.take_commands();
assert_eq!(commands.len(), 1);
assert!(commands[0].is_terminal());
}
#[test]
fn test_restart_fresh_serialization_error() {
use std::collections::HashMap;
let ctx = create_test_context();
// NaN serializes to JSON null, so this input does not fail.
let mut map: HashMap<String, f64> = HashMap::new();
map.insert("value".to_string(), f64::NAN);
let result = ctx.restart_fresh_with(&map, None);
assert!(result.is_ok());
}
#[test]
fn test_restart_fresh_with_complex_state() {
let ctx = create_test_context();
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
struct ComplexState {
id: String,
count: u32,
active: bool,
tags: Vec<String>,
metadata: HashMap<String, String>,
}
let mut metadata = HashMap::new();
metadata.insert("region".to_string(), "us-west-2".to_string());
metadata.insert("tier".to_string(), "premium".to_string());
let state = ComplexState {
id: "workflow-123".to_string(),
count: 999,
active: true,
tags: vec!["important".to_string(), "priority".to_string()],
metadata,
};
let result = ctx.restart_fresh_with(state.clone(), None);
assert!(result.is_ok());
let commands = ctx.take_commands();
assert_eq!(commands.len(), 1);
if let WorkflowCommand::RestartFresh(cmd) = &commands[0] {
let deserialized: ComplexState = serde_json::from_slice(&cmd.input).unwrap();
assert_eq!(deserialized, state);
} else {
panic!("Expected RestartFresh command");
}
}
#[test]
fn test_restart_fresh_multiple_calls() {
let ctx = create_test_context();
ctx.restart_fresh().unwrap();
let commands = ctx.take_commands();
assert_eq!(commands.len(), 1);
// A second call also emits a command, though a real workflow would return after
// the first.
ctx.restart_fresh().unwrap();
let commands = ctx.take_commands();
assert_eq!(commands.len(), 1);
}
// Workflow versioning tests
#[test]
fn test_version_basic() {
let execution = WorkflowExecution {
workflow_id: "wf-123".to_string(),
run_id: "run-456".to_string(),
workflow_type: "TestWorkflow".to_string(),
attempt: 1,
namespace: "default".to_string(),
task_queue: "test-queue".to_string(),
};
let ctx = WorkflowContext::new(execution, false, "1.2.3".to_string());
assert_eq!(ctx.version(), "1.2.3");
}
}