-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathlib.rs
More file actions
4007 lines (3681 loc) · 156 KB
/
Copy pathlib.rs
File metadata and controls
4007 lines (3681 loc) · 156 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Duroxide: Durable execution framework in Rust
//!
//! Duroxide is a framework for building reliable, long-running code based workflows that can survive
//! failures and restarts. For a deep dive into how durable execution works, see the
//! [Durable Futures Internals](https://github.com/affandar/duroxide/blob/main/docs/durable-futures-internals.md) documentation.
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use duroxide::providers::sqlite::SqliteProvider;
//! use duroxide::runtime::registry::ActivityRegistry;
//! use duroxide::runtime::{self};
//! use duroxide::{ActivityContext, OrchestrationContext, OrchestrationRegistry, Client};
//! use std::sync::Arc;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // 1. Create a storage provider
//! let store = Arc::new(SqliteProvider::new("sqlite:./data.db", None).await.unwrap());
//!
//! // 2. Register activities (your business logic)
//! let activities = ActivityRegistry::builder()
//! .register("Greet", |_ctx: ActivityContext, name: String| async move {
//! Ok(format!("Hello, {}!", name))
//! })
//! .build();
//!
//! // 3. Define your orchestration
//! let orchestration = |ctx: OrchestrationContext, name: String| async move {
//! let greeting = ctx.schedule_activity("Greet", name).await?;
// Mutex poisoning indicates a panic in another thread - a critical error.
// All expect()/unwrap() calls on mutex locks in this module are intentional:
// poisoned mutexes should panic as they indicate corrupted state.
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
// Arc::clone() vs .clone() is a style preference - we use .clone() for brevity
#![allow(clippy::clone_on_ref_ptr)]
//! Ok(greeting)
//! };
//!
//! // 4. Register and start the runtime
//! let orchestrations = OrchestrationRegistry::builder()
//! .register("HelloWorld", orchestration)
//! .build();
//!
//! let rt = runtime::Runtime::start_with_store(
//! store.clone(), activities, orchestrations
//! ).await;
//!
//! // 5. Create a client and start an orchestration instance
//! let client = Client::new(store.clone());
//! client.start_orchestration("inst-1", "HelloWorld", "World").await?;
//! let result = client.wait_for_orchestration("inst-1", std::time::Duration::from_secs(5)).await
//! .map_err(|e| format!("Wait error: {:?}", e))?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Key Concepts
//!
//! - **Orchestrations**: Long-running workflows written as async functions (coordination logic)
//! - **Activities**: Single-purpose work units (can do anything - DB, API, polling, etc.)
//! - Supports long-running activities via automatic lock renewal (minutes to hours)
//! - **Timers**: Use `ctx.schedule_timer(ms)` for orchestration-level delays and timeouts
//! - **Deterministic Replay**: Orchestrations are replayed from history to ensure consistency
//! - **Durable Futures**: Composable futures for activities, timers, and external events
//! - **ContinueAsNew (Multi-Execution)**: An orchestration can end the current execution and
//! immediately start a new one with fresh input. Each execution has its own isolated history
//! that starts with `OrchestrationStarted { event_id: 1 }`.
//!
//! ## ⚠️ Important: Orchestrations vs Activities
//!
//! **Orchestrations = Coordination (control flow, business logic)**
//! **Activities = Execution (single-purpose work units)**
//!
//! ```rust,no_run
//! # use duroxide::OrchestrationContext;
//! # use std::time::Duration;
//! # async fn example(ctx: OrchestrationContext) -> Result<(), String> {
//! // ✅ CORRECT: Orchestration-level delay using timer
//! ctx.schedule_timer(Duration::from_secs(5)).await; // Wait 5 seconds
//!
//! // ✅ ALSO CORRECT: Activity can poll/sleep as part of its work
//! // Example: Activity that provisions a VM and polls for readiness
//! // activities.register("ProvisionVM", |config| async move {
//! // let vm = create_vm(config).await?;
//! // while !vm_ready(&vm).await {
//! // tokio::time::sleep(Duration::from_secs(5)).await; // ✅ OK - part of provisioning
//! // }
//! // Ok(vm.id)
//! // });
//!
//! // ❌ WRONG: Activity that ONLY sleeps (use timer instead)
//! // ctx.schedule_activity("Sleep5Seconds", "").await;
//! # Ok(())
//! # }
//! ```
//!
//! **Put in Activities (single-purpose execution units):**
//! - Database operations
//! - API calls (can include retries/polling)
//! - Data transformations
//! - File I/O
//! - VM provisioning (with internal polling)
//!
//! **Put in Orchestrations (coordination and business logic):**
//! - Control flow (if/else, match, loops)
//! - Business decisions
//! - Multi-step workflows
//! - Error handling and compensation
//! - Timeouts and deadlines (use timers)
//! - Waiting for external events
//!
//! ## ContinueAsNew (Multi-Execution) Semantics
//!
//! ContinueAsNew (CAN) allows an orchestration to end its current execution and start a new
//! one with fresh input (useful for loops, pagination, long-running workflows).
//!
//! - Orchestration calls `ctx.continue_as_new(new_input)`
//! - Runtime stamps `OrchestrationContinuedAsNew` in the CURRENT execution's history
//! - Runtime enqueues a `WorkItem::ContinueAsNew`
//! - When processing that work item, the runtime starts a NEW execution with:
//! - `execution_id = previous_execution_id + 1`
//! - `existing_history = []` (fresh history)
//! - `OrchestrationStarted { event_id: 1, input = new_input }` is stamped automatically
//! - Each execution's history is independent; `duroxide::Client::read_execution_history(instance, id)`
//! returns events for that execution only
//!
//! Provider responsibilities are strictly storage-level (see below). The runtime owns all
//! orchestration semantics, including execution boundaries and starting the new execution.
//!
//! ## Provider Responsibilities (At a Glance)
//!
//! Providers are pure storage abstractions. The runtime computes orchestration semantics
//! and passes explicit instructions to the provider.
//!
//! - `fetch_orchestration_item()`
//! - Return a locked batch of work for ONE instance
//! - Include full history for the CURRENT `execution_id`
//! - Do NOT create/synthesize new executions here (even for ContinueAsNew)
//!
//! - `ack_orchestration_item(lock_token, execution_id, history_delta, ..., metadata)`
//! - Atomic commit of one orchestration turn
//! - Idempotently `INSERT OR IGNORE` execution row for the explicit `execution_id`
//! - `UPDATE instances.current_execution_id = MAX(current_execution_id, execution_id)`
//! - Append `history_delta` to the specified execution
//! - Update `executions.status` and `executions.output` from `metadata` (no event inspection)
//!
//! - Worker/Timer queues
//! - Peek-lock semantics (dequeue with lock token; ack by deleting)
//! - Automatic lock renewal for long-running activities (no configuration needed)
//! - Orchestrator, Worker, Timer queues are independent but committed atomically with history
//!
//! See `docs/provider-implementation-guide.md` and `src/providers/sqlite.rs` for a complete,
//! production-grade provider implementation.
//!
//! ## Simplified API
//!
//! All schedule methods return typed futures that can be awaited directly:
//!
//! ```rust,no_run
//! # use duroxide::OrchestrationContext;
//! # use std::time::Duration;
//! # async fn example(ctx: OrchestrationContext) -> Result<(), String> {
//! // Activities return Result<String, String>
//! let result = ctx.schedule_activity("Task", "input").await?;
//!
//! // Timers return ()
//! ctx.schedule_timer(Duration::from_secs(5)).await;
//!
//! // External events return String
//! let event = ctx.schedule_wait("Event").await;
//!
//! // Sub-orchestrations return Result<String, String>
//! let sub_result = ctx.schedule_sub_orchestration("Sub", "input").await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Common Patterns
//!
//! ### Function Chaining
//! ```rust,no_run
//! # use duroxide::OrchestrationContext;
//! async fn chain_example(ctx: OrchestrationContext) -> Result<String, String> {
//! let step1 = ctx.schedule_activity("Step1", "input").await?;
//! let step2 = ctx.schedule_activity("Step2", &step1).await?;
//! Ok(step2)
//! }
//! ```
//!
//! ### Fan-Out/Fan-In
//! ```rust,no_run
//! # use duroxide::OrchestrationContext;
//! async fn fanout_example(ctx: OrchestrationContext) -> Vec<String> {
//! let futures = vec![
//! ctx.schedule_activity("Process", "item1"),
//! ctx.schedule_activity("Process", "item2"),
//! ctx.schedule_activity("Process", "item3"),
//! ];
//! let results = ctx.join(futures).await;
//! results.into_iter().filter_map(|r| r.ok()).collect()
//! }
//! ```
//!
//! ### Human-in-the-Loop (Timeout Pattern)
//! ```rust,no_run
//! # use duroxide::{OrchestrationContext, Either2};
//! # use std::time::Duration;
//! async fn approval_example(ctx: OrchestrationContext) -> String {
//! let timeout = ctx.schedule_timer(Duration::from_secs(30));
//! let approval = ctx.schedule_wait("ApprovalEvent");
//!
//! match ctx.select2(approval, timeout).await {
//! Either2::First(data) => data,
//! Either2::Second(()) => "timeout".to_string(),
//! }
//! }
//! ```
//!
//! ### Delays and Timeouts
//! ```rust,no_run
//! # use duroxide::{OrchestrationContext, Either2};
//! # use std::time::Duration;
//! async fn delay_example(ctx: OrchestrationContext) -> Result<String, String> {
//! // Use timer for orchestration-level delays
//! ctx.schedule_timer(Duration::from_secs(5)).await;
//!
//! // Process after delay
//! let result = ctx.schedule_activity("ProcessData", "input").await?;
//! Ok(result)
//! }
//!
//! async fn timeout_example(ctx: OrchestrationContext) -> Result<String, String> {
//! // Race work against timeout
//! let work = ctx.schedule_activity("SlowOperation", "input");
//! let timeout = ctx.schedule_timer(Duration::from_secs(30));
//!
//! match ctx.select2(work, timeout).await {
//! Either2::First(result) => result,
//! Either2::Second(()) => Err("Operation timed out".to_string()),
//! }
//! }
//! ```
//!
//! ### Fan-Out/Fan-In with Error Handling
//! ```rust,no_run
//! # use duroxide::OrchestrationContext;
//! async fn fanout_with_errors(ctx: OrchestrationContext, items: Vec<String>) -> Result<Vec<String>, String> {
//! // Schedule all work in parallel
//! let futures: Vec<_> = items.iter()
//! .map(|item| ctx.schedule_activity("ProcessItem", item.clone()))
//! .collect();
//!
//! // Wait for all to complete (deterministic order preserved)
//! let results = ctx.join(futures).await;
//!
//! // Process results with error handling
//! let mut successes = Vec::new();
//! for result in results {
//! match result {
//! Ok(value) => successes.push(value),
//! Err(e) => {
//! // Log error but continue processing other items
//! ctx.trace_error(format!("Item processing failed: {e}"));
//! }
//! }
//! }
//!
//! Ok(successes)
//! }
//! ```
//!
//! ### Retry Pattern
//! ```rust,no_run
//! # use duroxide::{OrchestrationContext, RetryPolicy, BackoffStrategy};
//! # use std::time::Duration;
//! async fn retry_example(ctx: OrchestrationContext) -> Result<String, String> {
//! // Retry with linear backoff: 5 attempts, delay increases linearly (1s, 2s, 3s, 4s)
//! let result = ctx.schedule_activity_with_retry(
//! "UnreliableOperation",
//! "input",
//! RetryPolicy::new(5)
//! .with_backoff(BackoffStrategy::Linear {
//! base: Duration::from_secs(1),
//! max: Duration::from_secs(10),
//! }),
//! ).await?;
//!
//! Ok(result)
//! }
//! ```
//!
//! ## Examples
//!
//! See the `examples/` directory for complete, runnable examples:
//! - `hello_world.rs` - Basic orchestration setup
//! - `fan_out_fan_in.rs` - Parallel processing pattern with error handling
//! - `timers_and_events.rs` - Human-in-the-loop workflows with timeouts
//! - `delays_and_timeouts.rs` - Correct usage of timers for delays and timeouts
//! - `with_observability.rs` - Using observability features (tracing, metrics)
//! - `metrics_cli.rs` - Querying system metrics via CLI
//!
//! Run examples with: `cargo run --example <name>`
//!
//! ## Architecture
//!
//! This crate provides:
//! - **Public data model**: `Event`, `Action` for history and decisions
//! - **Orchestration driver**: `run_turn`, `run_turn_with`, and `Executor`
//! - **OrchestrationContext**: Schedule activities, timers, and external events
//! - **Deterministic futures**: `schedule_*()` return standard `Future`s that can be composed with `join`/`select`
//! - **Runtime**: In-process execution engine with dispatchers and workers
//! - **Providers**: Pluggable storage backends (filesystem, in-memory)
//!
//! ### End-to-End System Architecture
//!
//! ```text
//! +-------------------------------------------------------------------------+
//! | Application Layer |
//! +-------------------------------------------------------------------------+
//! | |
//! | +--------------+ +------------------------------------+ |
//! | | Client |-------->| start_orchestration() | |
//! | | | | raise_event() | |
//! | | | | wait_for_orchestration() | |
//! | +--------------+ +------------------------------------+ |
//! | |
//! +-------------------------------------------------------------------------+
//! |
//! v
//! +-------------------------------------------------------------------------+
//! | Runtime Layer |
//! +-------------------------------------------------------------------------+
//! | |
//! | +-------------------------------------------------------------------+ |
//! | | Runtime | |
//! | | +----------------------+ +----------------------+ | |
//! | | | Orchestration | | Work | | |
//! | | | Dispatcher | | Dispatcher | | |
//! | | | (N concurrent) | | (N concurrent) | | |
//! | | +----------+-----------+ +----------+-----------+ | |
//! | | | | | |
//! | | | Processes turns | Executes activities| |
//! | | | | | |
//! | +-------------+--------------------------------+--------------------+ |
//! | | | |
//! | +-------------v--------------------------------v--------------------+ |
//! | | OrchestrationRegistry: maps names -> orchestration handlers | |
//! | +-------------------------------------------------------------------+ |
//! | |
//! | +-------------------------------------------------------------------+ |
//! | | ActivityRegistry: maps names -> activity handlers | |
//! | +-------------------------------------------------------------------+ |
//! | |
//! +-------------------------------------------------------------------------+
//! | |
//! | Fetches work items | Fetches work items
//! | (peek-lock) | (peek-lock)
//! v v
//! +-------------------------------------------------------------------------+
//! | Provider Layer |
//! +-------------------------------------------------------------------------+
//! | |
//! | +----------------------------+ +----------------------------+ |
//! | | Orchestrator Queue | | Worker Queue | |
//! | | - StartOrchestration | | - ActivityExecute | |
//! | | - ActivityCompleted | | | |
//! | | - ActivityFailed | | | |
//! | | - TimerFired (delayed) | | | |
//! | | - ExternalRaised | | | |
//! | | - ContinueAsNew | | | |
//! | +----------------------------+ +----------------------------+ |
//! | |
//! | +-------------------------------------------------------------------+ |
//! | | Provider (Storage) | |
//! | | - History (Events per instance/execution) | |
//! | | - Instance metadata | |
//! | | - Execution metadata | |
//! | | - Instance locks (peek-lock semantics) | |
//! | | - Queue management (enqueue/dequeue with visibility) | |
//! | +-------------------------------------------------------------------+ |
//! | |
//! | +-------------------------------------------------------------------+ |
//! | | Storage Backend (SQLite, etc.) | |
//! | +-------------------------------------------------------------------+ |
//! | |
//! +-------------------------------------------------------------------------+
//!
//! ### Execution Flow
//!
//! 1. **Client** starts orchestration → enqueues `StartOrchestration` to orchestrator queue
//! 2. **OrchestrationDispatcher** fetches work item (peek-lock), loads history from Provider
//! 3. **Runtime** calls user's orchestration function with `OrchestrationContext`
//! 4. **Orchestration** schedules activities/timers → Runtime appends `Event`s to history
//! 5. **Runtime** enqueues `ActivityExecute` to worker queue, `TimerFired` (delayed) to orchestrator queue
//! 6. **WorkDispatcher** fetches activity work item, executes via `ActivityRegistry`
//! 7. **Activity** completes → enqueues `ActivityCompleted`/`ActivityFailed` to orchestrator queue
//! 8. **OrchestrationDispatcher** processes completion → next orchestration turn
//! 9. **Runtime** atomically commits history + queue changes via `ack_orchestration_item()`
//!
//! All operations are deterministic and replayable from history.
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
// Public orchestration primitives and executor
pub mod client;
pub mod runtime;
// Re-export descriptor type for public API ergonomics
pub use runtime::OrchestrationDescriptor;
pub mod providers;
#[cfg(feature = "provider-test")]
pub mod provider_validations;
#[cfg(feature = "provider-test")]
pub mod provider_validation;
#[cfg(feature = "provider-test")]
pub mod provider_stress_tests;
#[cfg(feature = "provider-test")]
pub mod provider_stress_test;
// Re-export key runtime types for convenience
pub use client::{Client, ClientError};
pub use runtime::{
OrchestrationHandler, OrchestrationRegistry, OrchestrationRegistryBuilder, OrchestrationStatus, RuntimeOptions,
};
// Re-export management types for convenience
pub use providers::{
ExecutionInfo, InstanceInfo, ProviderAdmin, QueueDepths, ScheduledActivityIdentifier, SessionFetchConfig,
SystemMetrics, TagFilter,
};
// Re-export capability filtering types
pub use providers::{DispatcherCapabilityFilter, SemverRange, current_build_version};
// Re-export deletion/pruning types for Client API users
pub use providers::{DeleteInstanceResult, InstanceFilter, InstanceTree, PruneOptions, PruneResult};
// Type aliases for improved readability and maintainability
/// Shared reference to a Provider implementation
pub type ProviderRef = Arc<dyn providers::Provider>;
/// Shared reference to an OrchestrationHandler
pub type OrchestrationHandlerRef = Arc<dyn runtime::OrchestrationHandler>;
// ============================================================================
// Heterogeneous Select Result Types
// ============================================================================
// ============================================================================
// Schedule Kind and DurableFuture (Cancellation Support)
// ============================================================================
/// Identifies the kind of scheduled work for cancellation purposes.
///
/// When a `DurableFuture` is dropped without completing, the runtime uses
/// this discriminator to determine how to cancel the underlying work:
/// - **Activity**: Lock stealing via provider (DELETE from worker_queue)
/// - **Timer**: No-op (virtual construct, no external state)
/// - **ExternalWait**: No-op (virtual construct, no external state)
/// - **SubOrchestration**: Enqueue `CancelInstance` work item for child
#[derive(Debug, Clone)]
pub enum ScheduleKind {
/// A scheduled activity execution
Activity {
/// Activity name for debugging/logging
name: String,
},
/// A durable timer
Timer,
/// Waiting for an external event
ExternalWait {
/// Event name for debugging/logging
event_name: String,
},
/// Waiting for a persistent external event (mailbox semantics)
QueueDequeue {
/// Event name for debugging/logging
event_name: String,
},
/// A sub-orchestration
SubOrchestration {
/// Token for this schedule (used to look up resolved instance ID)
token: u64,
},
}
/// A wrapper around scheduled futures that supports cancellation on drop.
///
/// When a `DurableFuture` is dropped without completing (e.g., as a select loser,
/// or when going out of scope without being awaited), the underlying scheduled work
/// is cancelled:
///
/// - **Activities**: Lock stealing via provider (removes from worker queue)
/// - **Sub-orchestrations**: `CancelInstance` work item enqueued for child
/// - **Timers/External waits**: No-op (virtual constructs with no external state)
///
/// # Examples
///
/// ```rust,no_run
/// # use duroxide::OrchestrationContext;
/// # use std::time::Duration;
/// # async fn example(ctx: OrchestrationContext) -> Result<String, String> {
/// // Activity scheduled - if timer wins, activity gets cancelled
/// let activity = ctx.schedule_activity("SlowWork", "input");
/// let timeout = ctx.schedule_timer(Duration::from_secs(5));
///
/// match ctx.select2(activity, timeout).await {
/// duroxide::Either2::First(result) => result,
/// duroxide::Either2::Second(()) => Err("Timed out - activity cancelled".to_string()),
/// }
/// # }
/// ```
///
/// # Drop Semantics
///
/// Unlike regular Rust futures which are inert on drop, `DurableFuture` has
/// meaningful drop semantics similar to `File` (closes on drop) or `MutexGuard`
/// (releases lock on drop). This is intentional - we want unobserved scheduled
/// work to be cancelled rather than leaked.
///
/// **Note:** Using `std::mem::forget()` on a `DurableFuture` will bypass
/// cancellation, causing the scheduled work to run but its result to be lost.
pub struct DurableFuture<T> {
/// Token assigned at creation (before schedule_id is known)
token: u64,
/// What kind of schedule this represents
kind: ScheduleKind,
/// Reference to context for cancellation registration
ctx: OrchestrationContext,
/// Whether the future has completed (to skip cancellation)
completed: bool,
/// The underlying future
inner: std::pin::Pin<Box<dyn Future<Output = T> + Send>>,
}
impl<T: Send + 'static> DurableFuture<T> {
/// Create a new `DurableFuture` wrapping an inner future.
fn new(
token: u64,
kind: ScheduleKind,
ctx: OrchestrationContext,
inner: impl Future<Output = T> + Send + 'static,
) -> Self {
Self {
token,
kind,
ctx,
completed: false,
inner: Box::pin(inner),
}
}
/// Transform the output of this `DurableFuture` while preserving its
/// identity for cancellation, `join`, and `select` composability.
///
/// The mapping function runs synchronously after the underlying future
/// completes. Cancellation semantics are fully preserved: dropping the
/// returned `DurableFuture` cancels the original scheduled work.
///
/// # Example
///
/// ```rust,no_run
/// # use duroxide::OrchestrationContext;
/// # async fn example(ctx: OrchestrationContext) -> Result<String, String> {
/// // Map an activity result to extract a field
/// let length = ctx.schedule_activity("Greet", "World")
/// .map(|r| r.map(|s| s.len().to_string()));
/// let len_result = length.await?;
/// # Ok(len_result)
/// # }
/// ```
pub fn map<U: Send + 'static>(self, f: impl FnOnce(T) -> U + Send + 'static) -> DurableFuture<U> {
// Transfer ownership of cancellation guard to the new DurableFuture.
// We must defuse `self` so its Drop doesn't fire cancellation.
let token = self.token;
let kind = self.kind.clone();
let ctx = self.ctx.clone();
// Defuse: take the inner future out without running Drop.
let inner = unsafe {
let inner = std::ptr::read(&self.inner);
// Prevent Drop from running on the original (would cancel the token)
std::mem::forget(self);
inner
};
let mapped = async move {
let value = inner.await;
f(value)
};
DurableFuture::new(token, kind, ctx, mapped)
}
/// Set a routing tag on this scheduled activity.
///
/// Tags direct activities to specialized workers. A worker configured with
/// [`crate::providers::TagFilter::tags`]`(["gpu"])` will only process activities
/// tagged `"gpu"`.
///
/// This method uses **mutate-after-emit**: the action has already been emitted to
/// the context's action list, and `with_tag` reaches back to modify it in place.
/// This is safe because actions are not drained until the replay engine polls
/// the orchestration future (which hasn't happened yet — we're still inside the
/// user's `async` block).
///
/// # Panics
///
/// Panics if called on a non-activity `DurableFuture` (e.g., timer or sub-orchestration).
///
/// # Example
///
/// ```rust,no_run
/// # use duroxide::OrchestrationContext;
/// # async fn example(ctx: OrchestrationContext) -> Result<String, String> {
/// let result = ctx.schedule_activity("CompileRelease", "repo-url")
/// .with_tag("build-machine")
/// .await?;
/// # Ok(result)
/// # }
/// ```
pub fn with_tag(self, tag: impl Into<String>) -> Self {
match &self.kind {
ScheduleKind::Activity { .. } => {}
other => panic!("with_tag() can only be called on activity futures, got {:?}", other),
}
let tag_value = tag.into();
let mut inner = self.ctx.inner.lock().expect("Mutex should not be poisoned");
// Find the action with our token and set its tag.
// The token must exist: it was just emitted by schedule_activity_internal
// and emitted_actions is only drained when the replay engine polls
// (which hasn't happened yet — we're still in the user's async block).
let mut found = false;
for (token, action) in inner.emitted_actions.iter_mut() {
if *token == self.token {
match action {
Action::CallActivity { tag, .. } => {
*tag = Some(tag_value);
}
_ => panic!("Token matched but action is not CallActivity"),
}
found = true;
break;
}
}
assert!(
found,
"with_tag(): token {} not found in emitted_actions — actions were drained before with_tag() was called",
self.token
);
drop(inner);
self
}
}
impl<T> Future for DurableFuture<T> {
type Output = T;
fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<T> {
match self.inner.as_mut().poll(cx) {
Poll::Ready(value) => {
self.completed = true;
Poll::Ready(value)
}
Poll::Pending => Poll::Pending,
}
}
}
impl<T> Drop for DurableFuture<T> {
fn drop(&mut self) {
if !self.completed {
// Future dropped without completing - trigger cancellation.
// Note: During dehydration (TurnResult::Continue), the orchestration future
// is dropped after collect_cancelled_from_context() has already run, so these
// cancellations go into a context that's about to be dropped. This is safe
// because the next turn creates a fresh context.
self.ctx.mark_token_cancelled(self.token, &self.kind);
}
}
}
// DurableFuture is Send if T is Send (inner is already Send-boxed)
unsafe impl<T: Send> Send for DurableFuture<T> {}
/// Result type for `select2` - represents which of two futures completed first.
///
/// Use this when racing two futures with different output types:
/// ```rust,no_run
/// # use duroxide::{OrchestrationContext, Either2};
/// # use std::time::Duration;
/// # async fn example(ctx: OrchestrationContext) -> Result<String, String> {
/// let activity = ctx.schedule_activity("Work", "input");
/// let timeout = ctx.schedule_timer(Duration::from_secs(30));
///
/// match ctx.select2(activity, timeout).await {
/// Either2::First(result) => result,
/// Either2::Second(()) => Err("Timed out".to_string()),
/// }
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Either2<A, B> {
/// First future completed first
First(A),
/// Second future completed first
Second(B),
}
impl<A, B> Either2<A, B> {
/// Returns true if this is the First variant
pub fn is_first(&self) -> bool {
matches!(self, Either2::First(_))
}
/// Returns true if this is the Second variant
pub fn is_second(&self) -> bool {
matches!(self, Either2::Second(_))
}
/// Returns the index of the winner (0 for First, 1 for Second)
pub fn index(&self) -> usize {
match self {
Either2::First(_) => 0,
Either2::Second(_) => 1,
}
}
}
impl<T> Either2<T, T> {
/// For homogeneous Either2 (both types are the same), extract as (index, value).
/// This is useful for migration from the old `(usize, T)` return type.
pub fn into_tuple(self) -> (usize, T) {
match self {
Either2::First(v) => (0, v),
Either2::Second(v) => (1, v),
}
}
}
/// Result type for `select3` - represents which of three futures completed first.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Either3<A, B, C> {
/// First future completed first
First(A),
/// Second future completed first
Second(B),
/// Third future completed first
Third(C),
}
impl<A, B, C> Either3<A, B, C> {
/// Returns the index of the winner (0 for First, 1 for Second, 2 for Third)
pub fn index(&self) -> usize {
match self {
Either3::First(_) => 0,
Either3::Second(_) => 1,
Either3::Third(_) => 2,
}
}
}
impl<T> Either3<T, T, T> {
/// For homogeneous Either3 (all types are the same), extract as (index, value).
pub fn into_tuple(self) -> (usize, T) {
match self {
Either3::First(v) => (0, v),
Either3::Second(v) => (1, v),
Either3::Third(v) => (2, v),
}
}
}
// Reserved prefix for built-in system activities.
// User-registered activities cannot use names starting with this prefix.
pub(crate) const SYSCALL_ACTIVITY_PREFIX: &str = "__duroxide_syscall:";
// Built-in system activity names (constructed from prefix)
pub(crate) const SYSCALL_ACTIVITY_NEW_GUID: &str = "__duroxide_syscall:new_guid";
pub(crate) const SYSCALL_ACTIVITY_UTC_NOW_MS: &str = "__duroxide_syscall:utc_now_ms";
pub(crate) const SYSCALL_ACTIVITY_GET_KV_VALUE: &str = "__duroxide_syscall:get_kv_value";
/// Runtime introspection stats, available via [`Client::get_orchestration_stats`].
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct SystemStats {
/// Total events in history for the current execution.
pub history_event_count: u64,
/// Approximate serialized size of the full history in bytes.
pub history_size_bytes: u64,
/// Number of unprocessed queue messages carried forward from the previous execution.
pub queue_pending_count: u64,
/// Number of KV keys.
pub kv_user_key_count: u64,
/// Sum of all KV value sizes in bytes.
pub kv_total_value_bytes: u64,
}
use crate::_typed_codec::Codec;
// LogLevel is now defined locally in this file
use serde::{Deserialize, Serialize};
use std::time::{Duration as StdDuration, SystemTime, UNIX_EPOCH};
// Internal codec utilities for typed I/O (kept private; public API remains ergonomic)
mod combinators;
mod _typed_codec {
use serde::{Serialize, de::DeserializeOwned};
use serde_json::Value;
pub trait Codec {
fn encode<T: Serialize>(v: &T) -> Result<String, String>;
fn decode<T: DeserializeOwned>(s: &str) -> Result<T, String>;
}
pub struct Json;
impl Codec for Json {
fn encode<T: Serialize>(v: &T) -> Result<String, String> {
// If the value is a JSON string, return raw content to preserve historic behavior
match serde_json::to_value(v) {
Ok(Value::String(s)) => Ok(s),
Ok(val) => serde_json::to_string(&val).map_err(|e| e.to_string()),
Err(e) => Err(e.to_string()),
}
}
fn decode<T: DeserializeOwned>(s: &str) -> Result<T, String> {
// Try parse as JSON first
match serde_json::from_str::<T>(s) {
Ok(v) => Ok(v),
Err(_) => {
// Fallback: treat raw string as JSON string value
let val = Value::String(s.to_string());
serde_json::from_value(val).map_err(|e| e.to_string())
}
}
}
}
}
/// Initial execution ID for new orchestration instances.
/// All orchestrations start with execution_id = 1.
pub const INITIAL_EXECUTION_ID: u64 = 1;
/// Initial event ID for new executions.
/// The first event (OrchestrationStarted) always has event_id = 1.
pub const INITIAL_EVENT_ID: u64 = 1;
// =============================================================================
// Sub-orchestration instance ID conventions
// =============================================================================
/// Prefix for auto-generated sub-orchestration instance IDs.
/// IDs starting with this prefix will have parent prefix added: `{parent}::{sub::N}`
pub const SUB_ORCH_AUTO_PREFIX: &str = "sub::";
/// Prefix for placeholder instance IDs before event ID assignment.
/// These are replaced with `sub::{event_id}` during action processing.
pub(crate) const SUB_ORCH_PENDING_PREFIX: &str = "sub::pending_";
/// Determine if a sub-orchestration instance ID is auto-generated (needs parent prefix).
///
/// Auto-generated IDs start with "sub::" and will have the parent instance prefixed
/// to create a globally unique ID: `{parent_instance}::{child_instance}`.
///
/// Explicit IDs (those not starting with "sub::") are used exactly as provided.
#[inline]
pub fn is_auto_generated_sub_orch_id(instance: &str) -> bool {
instance.starts_with(SUB_ORCH_AUTO_PREFIX)
}
/// Build the auto-generated sub-orchestration suffix for a given parent execution
/// and scheduling event id.
///
/// The first execution uses `sub::{event_id}` for backward compatibility. Later
/// executions (after `continue_as_new`) include the execution id as
/// `sub::{execution_id}_{event_id}`: event ids reset on continue-as-new, so a parent
/// that schedules a sub-orchestration at the same position on each iteration would
/// otherwise regenerate an identical child id and collide with the now-terminal
/// child from the previous iteration.
#[inline]
pub(crate) fn auto_sub_orch_suffix(execution_id: u64, event_id: u64) -> String {
if execution_id == INITIAL_EXECUTION_ID {
format!("{SUB_ORCH_AUTO_PREFIX}{event_id}")
} else {
format!("{SUB_ORCH_AUTO_PREFIX}{execution_id}_{event_id}")
}
}
/// Build the full child instance ID, adding parent prefix only for auto-generated IDs.
///
/// - Auto-generated IDs (starting with "sub::"): `{parent}::{child}` (e.g., `parent-1::sub::5`)
/// - Explicit IDs: used exactly as provided (e.g., `my-custom-child-id`)
#[inline]
pub fn build_child_instance_id(parent_instance: &str, child_instance: &str) -> String {
if is_auto_generated_sub_orch_id(child_instance) {
format!("{parent_instance}::{child_instance}")
} else {
child_instance.to_string()
}
}
/// Structured error details for orchestration failures.
///
/// Errors are categorized into three types for proper metrics and logging:
/// - **Infrastructure**: Provider failures, data corruption (abort turn, never reach user code)
/// - **Configuration**: Deployment issues like unregistered activities, nondeterminism (abort turn)
/// - **Application**: Business logic failures (flow through normal orchestration code)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ErrorDetails {
/// Infrastructure failure (provider errors, data corruption).
/// These errors abort orchestration execution and never reach user code.
Infrastructure {
operation: String,
message: String,
retryable: bool,
},
/// Configuration error (unregistered orchestrations/activities, nondeterminism).
/// These errors abort orchestration execution and never reach user code.
Configuration {
kind: ConfigErrorKind,
resource: String,
message: Option<String>,
},
/// Application error (business logic failures).
/// These are the ONLY errors that orchestration code sees.
Application {
kind: AppErrorKind,
message: String,
retryable: bool,
},
/// Poison message error - message exceeded max fetch attempts.
///
/// This indicates a message that repeatedly fails to process.
/// Could be caused by:
/// - Malformed message data causing deserialization failures
/// - Message triggering bugs that crash the worker
/// - Transient infrastructure issues that became permanent
/// - Application code bugs triggered by specific input patterns
Poison {
/// Number of times the message was fetched
attempt_count: u32,
/// Maximum allowed attempts
max_attempts: u32,
/// Message type and identity
message_type: PoisonMessageType,
/// The poisoned message content (serialized JSON for debugging)
message: String,
},
}
/// Poison message type identification.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum PoisonMessageType {
/// Orchestration work item batch
Orchestration { instance: String, execution_id: u64 },
/// Activity execution
Activity {
instance: String,
execution_id: u64,
activity_name: String,
activity_id: u64,
},
/// History deserialization failure (e.g., unknown event types from a newer duroxide version)
FailedDeserialization {
instance: String,
execution_id: u64,
error: String,
},
}
/// Configuration error kinds.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ConfigErrorKind {
Nondeterminism,
}
/// Application error kinds.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum AppErrorKind {
ActivityFailed,
OrchestrationFailed,
Panicked,
Cancelled { reason: String },
}
impl ErrorDetails {
/// Get failure category for metrics/logging.
pub fn category(&self) -> &'static str {
match self {
ErrorDetails::Infrastructure { .. } => "infrastructure",
ErrorDetails::Configuration { .. } => "configuration",
ErrorDetails::Application { .. } => "application",