-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathmod.rs
More file actions
1609 lines (1534 loc) · 57.4 KB
/
Copy pathmod.rs
File metadata and controls
1609 lines (1534 loc) · 57.4 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
use std::sync::Arc;
use tracing::info;
use crate::_typed_codec::{Codec, Json};
use crate::providers::{
DeleteInstanceResult, ExecutionInfo, InstanceFilter, InstanceInfo, InstanceTree, Provider, ProviderAdmin,
ProviderError, PruneOptions, PruneResult, QueueDepths, SystemMetrics, WorkItem,
};
use crate::{EventKind, OrchestrationStatus};
use serde::Serialize;
/// Client-specific error type that wraps provider errors and adds client-specific errors.
///
/// This enum allows callers to distinguish between:
/// - Provider errors (storage failures, can be retryable or permanent)
/// - Client-specific errors (validation, capability not available, etc.)
#[derive(Debug, Clone)]
pub enum ClientError {
/// Provider operation failed (wraps ProviderError)
Provider(ProviderError),
/// Management capability not available
ManagementNotAvailable,
/// Invalid input (client validation)
InvalidInput { message: String },
/// Operation timed out
Timeout,
/// Instance is still running (for delete without force)
InstanceStillRunning { instance_id: String },
/// Cannot delete a sub-orchestration directly (must delete root)
CannotDeleteSubOrchestration { instance_id: String },
/// Instance not found
InstanceNotFound { instance_id: String },
}
impl ClientError {
/// Check if this error is retryable (only applies to Provider errors)
pub fn is_retryable(&self) -> bool {
match self {
ClientError::Provider(e) => e.is_retryable(),
ClientError::ManagementNotAvailable => false,
ClientError::InvalidInput { .. } => false,
ClientError::Timeout => true,
ClientError::InstanceStillRunning { .. } => false,
ClientError::CannotDeleteSubOrchestration { .. } => false,
ClientError::InstanceNotFound { .. } => false,
}
}
}
impl std::fmt::Display for ClientError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ClientError::Provider(e) => write!(f, "{e}"),
ClientError::ManagementNotAvailable => write!(
f,
"Management features not available - provider doesn't implement ProviderAdmin"
),
ClientError::InvalidInput { message } => write!(f, "Invalid input: {message}"),
ClientError::Timeout => write!(f, "Operation timed out"),
ClientError::InstanceStillRunning { instance_id } => write!(
f,
"Instance {instance_id} is still running. Use force=true or cancel first."
),
ClientError::CannotDeleteSubOrchestration { instance_id } => write!(
f,
"Cannot delete sub-orchestration {instance_id} directly. Delete the root orchestration instead."
),
ClientError::InstanceNotFound { instance_id } => {
write!(f, "Instance {instance_id} not found")
}
}
}
}
impl std::error::Error for ClientError {}
impl From<ProviderError> for ClientError {
fn from(e: ProviderError) -> Self {
ClientError::Provider(e)
}
}
// Constants for polling behavior in wait_for_orchestration
/// Initial delay between status polls (5ms)
const INITIAL_POLL_DELAY_MS: u64 = 5;
/// Maximum delay between status polls (100ms)
const MAX_POLL_DELAY_MS: u64 = 100;
/// Multiplier for exponential backoff
const POLL_DELAY_MULTIPLIER: u64 = 2;
/// Client for orchestration control-plane operations with automatic capability discovery.
///
/// The Client provides APIs for managing orchestration instances:
/// - Starting orchestrations
/// - Raising external events
/// - Cancelling instances
/// - Checking status
/// - Waiting for completion
/// - Rich management features (when available)
///
/// # Automatic Capability Discovery
///
/// The Client automatically discovers provider capabilities through the `Provider::as_management_capability()` method.
/// When a provider implements `ProviderAdmin`, rich management features become available:
///
/// ```ignore
/// let client = Client::new(provider);
///
/// // Control plane (always available)
/// client.start_orchestration("order-1", "ProcessOrder", "{}").await?;
///
/// // Management (automatically discovered)
/// if client.has_management_capability() {
/// let instances = client.list_all_instances().await?;
/// let metrics = client.get_system_metrics().await?;
/// } else {
/// println!("Management features not available");
/// }
/// ```
///
/// # Design
///
/// The Client communicates with the Runtime **only through the shared Provider** (no direct coupling).
/// This allows the Client to be used from any process, even one without a running Runtime.
///
/// # Thread Safety
///
/// Client is `Clone` and can be safely shared across threads.
///
/// # Example Usage
///
/// ```ignore
/// use duroxide::{Client, OrchestrationStatus};
/// use duroxide::providers::sqlite::SqliteProvider;
/// use std::sync::Arc;
///
/// use duroxide::ClientError;
/// let store = Arc::new(SqliteProvider::new("sqlite:./data.db").await?);
/// let client = Client::new(store);
///
/// // Start an orchestration
/// client.start_orchestration("order-123", "ProcessOrder", r#"{"customer_id": "c1"}"#).await?;
///
/// // Check status
/// let status = client.get_orchestration_status("order-123").await?;
/// println!("Status: {:?}", status);
///
/// // Wait for completion
/// let result = client.wait_for_orchestration("order-123", std::time::Duration::from_secs(30)).await.unwrap();
/// match result {
/// OrchestrationStatus::Completed { output, .. } => println!("Done: {}", output),
/// OrchestrationStatus::Failed { details, .. } => {
/// eprintln!("Failed ({}): {}", details.category(), details.display_message());
/// }
/// _ => {}
/// }
/// ```
pub struct Client {
store: Arc<dyn Provider>,
}
/// Reject instance ids that collide with the reserved sub-orchestration markers.
///
/// Child sub-orchestration instance ids reserve the `sub::` marker (see
/// [`crate::auto_sub_orch_suffix`], the canonical formatter). The first parent
/// execution uses `{parent}::sub::{event_id}`; executions after continue-as-new use
/// `{parent}::sub::{execution_id}_{event_id}`. A user-supplied id matching either form
/// could pre-occupy a future child id, so the `sub::` prefix and `::sub::` infix are
/// reserved. Other uses of `::` remain valid.
fn validate_instance_id(instance: &str) -> Result<(), ClientError> {
if instance.starts_with(crate::SUB_ORCH_AUTO_PREFIX) || instance.contains("::sub::") {
return Err(ClientError::InvalidInput {
message: format!(
"instance id '{instance}' uses the reserved sub-orchestration marker 'sub::'"
),
});
}
Ok(())
}
impl Client {
/// Create a client bound to a Provider instance.
///
/// # Parameters
///
/// * `store` - Arc-wrapped Provider (same instance used by Runtime)
///
/// # Example
///
/// ```ignore
/// let store = Arc::new(SqliteProvider::new("sqlite::memory:").await.unwrap());
/// let client = Client::new(store.clone());
/// // Multiple clients can share the same store
/// let client2 = client.clone();
/// ```
pub fn new(store: Arc<dyn Provider>) -> Self {
Self { store }
}
/// Start an orchestration instance with string input.
///
/// # Parameters
///
/// * `instance` - Unique instance ID (e.g., "order-123", "user-payment-456")
/// * `orchestration` - Name of registered orchestration (e.g., "ProcessOrder")
/// * `input` - JSON string input (will be passed to orchestration)
///
/// # Returns
///
/// * `Ok(())` - Instance was enqueued for processing
/// * `Err(msg)` - Failed to enqueue (storage error)
///
/// # Behavior
///
/// - Enqueues a StartOrchestration work item
/// - Returns immediately (doesn't wait for orchestration to start/complete)
/// - Use `wait_for_orchestration()` to wait for completion
///
/// # Instance ID Requirements
///
/// - Must be unique across all orchestrations
/// - Can be any string (alphanumeric + hyphens recommended)
/// - Reusing an instance ID that already exists will fail
/// - Must not use the reserved sub-orchestration marker `sub::` (as a prefix
/// or in the `::sub::` form); these are reserved for auto-generated child
/// instance ids. Such ids are rejected with [`ClientError::InvalidInput`].
///
/// # Example
///
/// ```rust,no_run
/// # use duroxide::{Client, ClientError};
/// # use std::sync::Arc;
/// # async fn example(client: Client) -> Result<(), ClientError> {
/// // Start with JSON string input
/// client.start_orchestration(
/// "order-123",
/// "ProcessOrder",
/// r#"{"customer_id": "c1", "items": ["item1", "item2"]}"#
/// ).await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns `ClientError::InvalidInput` if the instance id uses the reserved
/// `sub::` marker.
/// Returns `ClientError::Provider` if the provider fails to enqueue the orchestration.
pub async fn start_orchestration(
&self,
instance: impl Into<String>,
orchestration: impl Into<String>,
input: impl Into<String>,
) -> Result<(), ClientError> {
let instance = instance.into();
validate_instance_id(&instance)?;
let item = WorkItem::StartOrchestration {
instance,
orchestration: orchestration.into(),
input: input.into(),
version: None,
parent_instance: None,
parent_id: None,
execution_id: crate::INITIAL_EXECUTION_ID,
};
self.store
.enqueue_for_orchestrator(item, None)
.await
.map_err(ClientError::from)
}
/// Start an orchestration instance pinned to a specific version.
///
/// # Errors
///
/// Returns `ClientError::InvalidInput` if the instance id uses the reserved
/// `sub::` marker.
/// Returns `ClientError::Provider` if the provider fails to enqueue the orchestration.
pub async fn start_orchestration_versioned(
&self,
instance: impl Into<String>,
orchestration: impl Into<String>,
version: impl Into<String>,
input: impl Into<String>,
) -> Result<(), ClientError> {
let instance = instance.into();
validate_instance_id(&instance)?;
let item = WorkItem::StartOrchestration {
instance,
orchestration: orchestration.into(),
input: input.into(),
version: Some(version.into()),
parent_instance: None,
parent_id: None,
execution_id: crate::INITIAL_EXECUTION_ID,
};
self.store
.enqueue_for_orchestrator(item, None)
.await
.map_err(ClientError::from)
}
// Note: No delayed scheduling API. Clients should use normal start APIs.
/// Start an orchestration with typed input (serialized to JSON).
///
/// # Errors
///
/// Returns `ClientError::InvalidInput` if serialization fails.
/// Returns `ClientError::Provider` if the provider fails to enqueue the orchestration.
pub async fn start_orchestration_typed<In: Serialize>(
&self,
instance: impl Into<String>,
orchestration: impl Into<String>,
input: In,
) -> Result<(), ClientError> {
let payload = Json::encode(&input).map_err(|e| ClientError::InvalidInput {
message: format!("encode: {e}"),
})?;
self.start_orchestration(instance, orchestration, payload).await
}
/// Start a versioned orchestration with typed input (serialized to JSON).
///
/// # Errors
///
/// Returns `ClientError::InvalidInput` if serialization fails.
/// Returns `ClientError::Provider` if the provider fails to enqueue the orchestration.
pub async fn start_orchestration_versioned_typed<In: Serialize>(
&self,
instance: impl Into<String>,
orchestration: impl Into<String>,
version: impl Into<String>,
input: In,
) -> Result<(), ClientError> {
let payload = Json::encode(&input).map_err(|e| ClientError::InvalidInput {
message: format!("encode: {e}"),
})?;
self.start_orchestration_versioned(instance, orchestration, version, payload)
.await
}
/// Raise an external event into a running orchestration instance.
///
/// # Purpose
///
/// Send a signal/message to a running orchestration that is waiting for an external event.
/// The orchestration must have called `ctx.schedule_wait(event_name)` to receive the event.
///
/// # Parameters
///
/// * `instance` - Instance ID of the running orchestration
/// * `event_name` - Name of the event (must match `schedule_wait` name)
/// * `data` - Payload data (JSON string, passed to orchestration)
///
/// # Behavior
///
/// - Enqueues ExternalRaised work item to orchestrator queue
/// - If instance isn't waiting for this event (yet), it's buffered
/// - Event is matched by NAME (not correlation ID)
/// - Multiple events with same name can be raised
///
/// # Example
///
/// ```rust,no_run
/// # use duroxide::{Client, ClientError};
/// # async fn example(client: Client) -> Result<(), ClientError> {
/// // Orchestration waiting for approval
/// // ctx.schedule_wait("ApprovalEvent").await
///
/// // External system/human approves
/// client.raise_event(
/// "order-123",
/// "ApprovalEvent",
/// r#"{"approved": true, "by": "manager@company.com"}"#
/// ).await?;
/// # Ok(())
/// # }
/// ```
///
/// # Use Cases
///
/// - Human approval workflows
/// - Webhook callbacks
/// - Inter-orchestration communication
/// - External system integration
///
/// # Error Cases
///
/// - Instance doesn't exist: Event is buffered, orchestration processes when started
/// - Instance already completed: Event is ignored gracefully
///
/// # Errors
///
/// Returns `ClientError::Provider` if the provider fails to enqueue the event.
pub async fn raise_event(
&self,
instance: impl Into<String>,
event_name: impl Into<String>,
data: impl Into<String>,
) -> Result<(), ClientError> {
let item = WorkItem::ExternalRaised {
instance: instance.into(),
name: event_name.into(),
data: data.into(),
};
self.store
.enqueue_for_orchestrator(item, None)
.await
.map_err(ClientError::from)
}
/// Raise a positional external event with typed data.
///
/// Serializes `data` as JSON before sending. Same semantics as [`Self::raise_event`].
///
/// # Errors
///
/// Returns [`ClientError`] if the provider fails to enqueue the event.
pub async fn raise_event_typed<T: serde::Serialize>(
&self,
instance: impl Into<String>,
event_name: impl Into<String>,
data: &T,
) -> Result<(), ClientError> {
let payload = crate::_typed_codec::Json::encode(data).expect("Serialization should not fail");
self.raise_event(instance, event_name, payload).await
}
/// Enqueue a message into a named queue for an orchestration instance.
///
/// Queue messages use FIFO mailbox semantics:
/// - Matched to [`OrchestrationContext::dequeue_event`] subscriptions in order
/// - Stick around until consumed (even if no subscription exists yet)
/// - Survive `continue_as_new` boundaries
/// - Not affected by subscription cancellation
///
/// # Errors
///
/// Returns [`ClientError`] if the provider fails to enqueue the message.
pub async fn enqueue_event(
&self,
instance: impl Into<String>,
queue: impl Into<String>,
data: impl Into<String>,
) -> Result<(), ClientError> {
let item = WorkItem::QueueMessage {
instance: instance.into(),
name: queue.into(),
data: data.into(),
};
self.store
.enqueue_for_orchestrator(item, None)
.await
.map_err(ClientError::from)
}
/// Enqueue a typed message into a named queue for an orchestration instance.
///
/// Serializes `data` as JSON before enqueuing. Same semantics as [`Self::enqueue_event`].
///
/// # Errors
///
/// Returns [`ClientError`] if the provider fails to enqueue the message.
pub async fn enqueue_event_typed<T: serde::Serialize>(
&self,
instance: impl Into<String>,
queue: impl Into<String>,
data: &T,
) -> Result<(), ClientError> {
let payload = crate::_typed_codec::Json::encode(data).expect("Serialization should not fail");
self.enqueue_event(instance, queue, payload).await
}
/// Raise a persistent external event that uses mailbox semantics.
///
/// Prefer [`Self::enqueue_event`] — this is a deprecated alias.
///
/// # Errors
///
/// Returns [`ClientError`] if the provider fails to enqueue the event.
#[deprecated(note = "Use enqueue_event() instead")]
pub async fn raise_event_persistent(
&self,
instance: impl Into<String>,
event_name: impl Into<String>,
data: impl Into<String>,
) -> Result<(), ClientError> {
self.enqueue_event(instance, event_name, data).await
}
/// V2: Raise an external event with topic-based pub/sub matching.
///
/// Same as `raise_event`, but includes a `topic` for pub/sub matching.
/// The orchestration must have called `ctx.schedule_wait2(name, topic)` to receive the event.
/// Feature-gated for replay engine extensibility verification.
///
/// # Errors
///
/// Returns [`ClientError`] if the provider fails to enqueue the event.
#[cfg(feature = "replay-version-test")]
pub async fn raise_event2(
&self,
instance: impl Into<String>,
event_name: impl Into<String>,
topic: impl Into<String>,
data: impl Into<String>,
) -> Result<(), ClientError> {
let item = WorkItem::ExternalRaised2 {
instance: instance.into(),
name: event_name.into(),
topic: topic.into(),
data: data.into(),
};
self.store
.enqueue_for_orchestrator(item, None)
.await
.map_err(ClientError::from)
}
/// Request cancellation of an orchestration instance.
///
/// # Purpose
///
/// Gracefully cancel a running orchestration. The orchestration will complete its current
/// turn and then fail deterministically with a "canceled: {reason}" error.
///
/// # Parameters
///
/// * `instance` - Instance ID to cancel
/// * `reason` - Reason for cancellation (included in error message)
///
/// # Behavior
///
/// 1. Enqueues CancelInstance work item
/// 2. Runtime appends OrchestrationCancelRequested event
/// 3. Next turn, orchestration sees cancellation and fails deterministically
/// 4. Final status: `OrchestrationStatus::Failed { details: Application::Cancelled }`
///
/// # Deterministic Cancellation
///
/// Cancellation is **deterministic** - the orchestration fails at a well-defined point:
/// - Not mid-activity (activities complete)
/// - Not mid-turn (current turn finishes)
/// - Failure is recorded in history (replays consistently)
///
/// # Propagation
///
/// If the orchestration has child sub-orchestrations, they are also cancelled.
///
/// # Example
///
/// ```ignore
/// // Cancel a long-running order
/// client.cancel_instance("order-123", "Customer requested cancellation").await?;
///
/// // Wait for cancellation to complete
/// let status = client.wait_for_orchestration("order-123", std::time::Duration::from_secs(5)).await?;
/// match status {
/// OrchestrationStatus::Failed { details, .. } if matches!(
/// details,
/// duroxide::ErrorDetails::Application {
/// kind: duroxide::AppErrorKind::Cancelled { .. },
/// ..
/// }
/// ) => {
/// println!("Successfully cancelled");
/// }
/// _ => {}
/// }
/// ```
///
/// # Error Cases
///
/// - Instance already completed: Cancellation is no-op
/// - Instance doesn't exist: Cancellation is no-op
///
/// # Errors
///
/// Returns `ClientError::Provider` if the provider fails to enqueue the cancellation.
pub async fn cancel_instance(
&self,
instance: impl Into<String>,
reason: impl Into<String>,
) -> Result<(), ClientError> {
let item = WorkItem::CancelInstance {
instance: instance.into(),
reason: reason.into(),
};
self.store
.enqueue_for_orchestrator(item, None)
.await
.map_err(ClientError::from)
}
/// Get the current status of an orchestration by inspecting its history.
///
/// # Purpose
///
/// Query the current state of an orchestration instance without waiting.
///
/// # Parameters
///
/// * `instance` - Instance ID to query
///
/// # Returns
///
/// * `OrchestrationStatus::NotFound` - Instance doesn't exist
/// * `OrchestrationStatus::Running` - Instance is still executing
/// * `OrchestrationStatus::Completed { output, .. }` - Instance completed successfully
/// * `OrchestrationStatus::Failed { error }` - Instance failed (includes cancellations)
///
/// # Behavior
///
/// - Reads instance history from provider
/// - Scans for terminal events (Completed/Failed)
/// - For multi-execution instances (ContinueAsNew), returns status of LATEST execution
///
/// # Performance
///
/// This method reads from storage (not cached). For polling, use `wait_for_orchestration` instead.
///
/// # Example
///
/// ```rust,no_run
/// # use duroxide::{Client, ClientError, OrchestrationStatus};
/// # async fn example(client: Client) -> Result<(), ClientError> {
/// let status = client.get_orchestration_status("order-123").await?;
///
/// match status {
/// OrchestrationStatus::NotFound => println!("Instance not found"),
/// OrchestrationStatus::Running { .. } => println!("Still processing"),
/// OrchestrationStatus::Completed { output, .. } => println!("Done: {}", output),
/// OrchestrationStatus::Failed { details, .. } => eprintln!("Error: {}", details.display_message()),
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns `ClientError::Provider` if the provider fails to read the orchestration history.
pub async fn get_orchestration_status(&self, instance: &str) -> Result<OrchestrationStatus, ClientError> {
let hist = self.store.read(instance).await.map_err(ClientError::from)?;
// Query custom status (lightweight, always available)
let (custom_status, custom_status_version) = match self.store.get_custom_status(instance, 0).await {
Ok(Some((cs, v))) => (cs, v),
Ok(None) => (None, 0),
Err(_) => (None, 0), // Best-effort: don't fail status query for custom_status errors
};
// Find terminal events first
for e in hist.iter().rev() {
match &e.kind {
EventKind::OrchestrationCompleted { output } => {
return Ok(OrchestrationStatus::Completed {
output: output.clone(),
custom_status,
custom_status_version,
});
}
EventKind::OrchestrationFailed { details } => {
return Ok(OrchestrationStatus::Failed {
details: details.clone(),
custom_status,
custom_status_version,
});
}
_ => {}
}
}
// If we ever saw a start, it's running
if hist
.iter()
.any(|e| matches!(&e.kind, EventKind::OrchestrationStarted { .. }))
{
Ok(OrchestrationStatus::Running {
custom_status,
custom_status_version,
})
} else {
Ok(OrchestrationStatus::NotFound)
}
}
/// Wait until terminal state or timeout using provider reads.
///
/// # Purpose
///
/// Poll for orchestration completion with exponential backoff, returning when terminal or timeout.
///
/// # Parameters
///
/// * `instance` - Instance ID to wait for
/// * `timeout` - Maximum time to wait before returning timeout error
///
/// # Returns
///
/// * `Ok(OrchestrationStatus::Completed { output, .. })` - Orchestration completed successfully
/// * `Ok(OrchestrationStatus::Failed { details, .. })` - Orchestration failed (includes cancellations)
/// * `Err(ClientError::Timeout)` - Timeout elapsed while still Running
/// * `Err(ClientError::Provider(e))` - Provider/Storage error
///
/// **Note:** Never returns `NotFound` or `Running` - only terminal states or timeout.
///
/// # Polling Behavior
///
/// - First check: Immediate (no delay)
/// - Subsequent checks: Exponential backoff starting at 5ms, doubling each iteration, max 100ms
/// - Continues until terminal state or timeout
///
/// # Example
///
/// ```ignore
/// // Start orchestration
/// client.start_orchestration("order-123", "ProcessOrder", "{}").await?;
///
/// // Wait up to 30 seconds
/// match client.wait_for_orchestration("order-123", std::time::Duration::from_secs(30)).await {
/// Ok(OrchestrationStatus::Completed { output, .. }) => {
/// println!("Success: {}", output);
/// }
/// Ok(OrchestrationStatus::Failed { details, .. }) => {
/// eprintln!("Failed ({}): {}", details.category(), details.display_message());
/// }
/// Err(ClientError::Timeout) => {
/// println!("Still running after 30s, instance: order-123");
/// // Instance is still running - can wait more or cancel
/// }
/// _ => unreachable!("wait_for_orchestration only returns terminal or timeout"),
/// }
/// ```
///
/// # Use Cases
///
/// - Synchronous request/response workflows
/// - Testing (wait for workflow to complete)
/// - CLI tools (block until done)
/// - Health checks
///
/// # For Long-Running Workflows
///
/// Don't wait for hours/days:
/// ```ignore
/// // Start workflow
/// client.start_orchestration("batch-job", "ProcessBatch", "{}").await.unwrap();
///
/// // DON'T wait for hours
/// // let status = client.wait_for_orchestration("batch-job", Duration::from_hours(24)).await;
///
/// // DO poll periodically
/// loop {
/// match client.get_orchestration_status("batch-job").await {
/// OrchestrationStatus::Completed { .. } => break,
/// OrchestrationStatus::Failed { .. } => break,
/// _ => tokio::time::sleep(std::time::Duration::from_secs(60)).await,
/// }
/// }
/// ```
///
/// # Errors
///
/// Returns `ClientError::Provider` if the provider fails to read the orchestration status.
/// Returns `ClientError::Timeout` if the orchestration doesn't complete within the timeout.
pub async fn wait_for_orchestration(
&self,
instance: &str,
timeout: std::time::Duration,
) -> Result<OrchestrationStatus, ClientError> {
let deadline = std::time::Instant::now() + timeout;
// quick path
match self.get_orchestration_status(instance).await {
Ok(s @ OrchestrationStatus::Completed { .. }) => return Ok(s),
Ok(s @ OrchestrationStatus::Failed { .. }) => return Ok(s),
Err(e) => return Err(e),
_ => {}
}
// poll with backoff
let mut delay_ms: u64 = INITIAL_POLL_DELAY_MS;
while std::time::Instant::now() < deadline {
match self.get_orchestration_status(instance).await {
Ok(s @ OrchestrationStatus::Completed { .. }) => return Ok(s),
Ok(s @ OrchestrationStatus::Failed { .. }) => return Ok(s),
Err(e) => return Err(e),
_ => {
tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
delay_ms = (delay_ms.saturating_mul(POLL_DELAY_MULTIPLIER)).min(MAX_POLL_DELAY_MS);
}
}
}
Err(ClientError::Timeout)
}
/// Typed wait helper: decodes output on Completed, returns Err(String) on Failed.
///
/// # Errors
///
/// Returns `ClientError::Provider` if the provider fails to read the orchestration status.
/// Returns `ClientError::Timeout` if the orchestration doesn't complete within the timeout.
/// Returns `ClientError::InvalidInput` if deserialization of the output fails.
pub async fn wait_for_orchestration_typed<Out: serde::de::DeserializeOwned>(
&self,
instance: &str,
timeout: std::time::Duration,
) -> Result<Result<Out, String>, ClientError> {
match self.wait_for_orchestration(instance, timeout).await? {
OrchestrationStatus::Completed { output, .. } => match Json::decode::<Out>(&output) {
Ok(v) => Ok(Ok(v)),
Err(e) => Err(ClientError::InvalidInput {
message: format!("decode failed: {e}"),
}),
},
OrchestrationStatus::Failed { details, .. } => Ok(Err(details.display_message())),
_ => unreachable!("wait_for_orchestration returns only terminal or timeout"),
}
}
/// Wait for custom_status to change, polling the provider at `poll_interval`.
///
/// Returns the full `OrchestrationStatus` when:
/// - The `custom_status_version` exceeds `last_seen_version`
/// - The orchestration reaches a terminal state (Completed/Failed)
/// - The timeout elapses (returns `Err(ClientError::Timeout)`)
///
/// # Parameters
///
/// * `instance` - Instance ID to monitor
/// * `last_seen_version` - The version the caller last observed (0 to get any status)
/// * `poll_interval` - How often to check the provider
/// * `timeout` - Maximum time to wait
///
/// # Example
///
/// ```ignore
/// let mut version = 0u64;
/// loop {
/// match client.wait_for_status_change("order-123", version, Duration::from_millis(200), Duration::from_secs(30)).await {
/// Ok(OrchestrationStatus::Running { custom_status, custom_status_version }) => {
/// println!("Progress: {:?}", custom_status);
/// version = custom_status_version;
/// }
/// Ok(OrchestrationStatus::Completed { output, .. }) => {
/// println!("Done: {output}");
/// break;
/// }
/// _ => break,
/// }
/// }
/// ```
///
/// # Errors
///
/// Returns [`ClientError`] if the provider fails or the instance doesn't exist.
pub async fn wait_for_status_change(
&self,
instance: &str,
last_seen_version: u64,
poll_interval: std::time::Duration,
timeout: std::time::Duration,
) -> Result<OrchestrationStatus, ClientError> {
let deadline = std::time::Instant::now() + timeout;
while std::time::Instant::now() < deadline {
// Lightweight check: just custom_status + version
match self.store.get_custom_status(instance, last_seen_version).await {
Ok(Some(_)) => {
// Version changed — return full status
return self.get_orchestration_status(instance).await;
}
Ok(None) => {
// No change — check if terminal before sleeping
// (get_custom_status returns None if version hasn't changed,
// but also if the instance doesn't exist or is terminal)
}
Err(e) => return Err(ClientError::from(e)),
}
// Also check for terminal state (in case orchestration completed
// without ever updating custom_status)
match self.get_orchestration_status(instance).await? {
OrchestrationStatus::Running { .. } | OrchestrationStatus::NotFound => {
// Still running — sleep and retry
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
tokio::time::sleep(poll_interval.min(remaining)).await;
}
terminal => return Ok(terminal),
}
}
Err(ClientError::Timeout)
}
// ===== Key-Value Store =====
/// Read a single KV entry for a given instance.
///
/// Reads directly from the provider's materialized `kv_store` table.
/// Returns `Ok(None)` if the key doesn't exist.
///
/// # Errors
///
/// Returns `ClientError` if the provider fails to read.
pub async fn get_kv_value(&self, instance: &str, key: &str) -> Result<Option<String>, ClientError> {
self.store.get_kv_value(instance, key).await.map_err(ClientError::from)
}
/// Read a typed KV entry for a given instance.
///
/// Deserializes the stored JSON value into `T`.
/// Returns `Ok(None)` if the key doesn't exist.
///
/// # Errors
///
/// Returns `ClientError` if the provider fails or deserialization fails.
pub async fn get_kv_value_typed<T: serde::de::DeserializeOwned>(
&self,
instance: &str,
key: &str,
) -> Result<Option<T>, ClientError> {
match self.get_kv_value(instance, key).await? {
None => Ok(None),
Some(s) => serde_json::from_str(&s)
.map(Some)
.map_err(|e| ClientError::InvalidInput {
message: format!("KV deserialization error: {e}"),
}),
}
}
/// Read all KV entries for a given instance.
///
/// Returns a map of key→value pairs. Returns an empty map if no keys exist.
///
/// # Errors
///
/// Returns `ClientError` if the provider fails to read.
pub async fn get_kv_all_values(
&self,
instance: &str,
) -> Result<std::collections::HashMap<String, String>, ClientError> {
self.store.get_kv_all_values(instance).await.map_err(ClientError::from)
}
/// Poll a KV key until it becomes `Some`, or timeout.
///
/// Uses exponential backoff (same as [`wait_for_orchestration`](Self::wait_for_orchestration)).
///
/// # Example
///
/// ```ignore
/// let value = client.wait_for_kv_value(
/// "my-instance", "response:op-1",
/// Duration::from_secs(5),
/// ).await?;
/// println!("Got: {value}");
/// ```
///
/// # Errors
///
/// Returns `ClientError::Timeout` if the key is still `None` after `timeout`.
/// Returns `ClientError` if a provider read fails.
pub async fn wait_for_kv_value(
&self,
instance: &str,
key: &str,
timeout: std::time::Duration,
) -> Result<String, ClientError> {
let deadline = std::time::Instant::now() + timeout;
// quick path
if let Some(val) = self.get_kv_value(instance, key).await? {
return Ok(val);
}
// poll with backoff
let mut delay_ms: u64 = INITIAL_POLL_DELAY_MS;
while std::time::Instant::now() < deadline {
if let Some(val) = self.get_kv_value(instance, key).await? {
return Ok(val);
}
tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
delay_ms = (delay_ms.saturating_mul(POLL_DELAY_MULTIPLIER)).min(MAX_POLL_DELAY_MS);
}
Err(ClientError::Timeout)
}
/// Poll a typed KV key until it becomes `Some`, or timeout.
///
/// Same as [`wait_for_kv_value`](Self::wait_for_kv_value) but deserializes
/// the JSON value into `T`.
///
/// # Errors