runtara-sdk 1.6.4

High-level SDK for building durable workflows with runtara
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
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
// Copyright (C) 2025 SyncMyOrders Sp. z o.o.
// SPDX-License-Identifier: AGPL-3.0-or-later
//! High-level types for the SDK.

/// Instance status as returned by status queries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstanceStatus {
    /// Status is unknown
    Unknown,
    /// Instance is queued but not yet started
    Pending,
    /// Instance is currently executing
    Running,
    /// Instance is sleeping/waiting for wake
    Suspended,
    /// Instance finished successfully
    Completed,
    /// Instance finished with an error
    Failed,
    /// Instance was cancelled by signal
    Cancelled,
}

/// Signal types that can be received from runtara-core.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignalType {
    /// Cancel execution
    Cancel,
    /// Pause execution (checkpoint and wait)
    Pause,
    /// Resume paused execution
    Resume,
}

/// A signal received from runtara-core.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signal {
    /// The type of signal
    pub signal_type: SignalType,
    /// Signal-specific payload data
    pub payload: Vec<u8>,
    /// Optional checkpoint_id when representing a custom signal
    pub checkpoint_id: Option<String>,
}

/// Checkpoint response with signal information.
///
/// The checkpoint API now returns pending signal information along with the
/// checkpoint state. This allows instances to efficiently check for cancel/pause
/// signals during checkpoint operations without additional RPC calls.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckpointResult {
    /// If true, an existing checkpoint was found and state is returned.
    /// If false, a new checkpoint was saved.
    pub found: bool,
    /// Checkpoint state (existing state if found, empty if saved).
    pub state: Vec<u8>,
    /// Pending instance-wide signal if any (cancel, pause, resume).
    /// Instance should handle this signal after processing the checkpoint.
    pub pending_signal: Option<Signal>,
    /// Pending checkpoint-scoped custom signal (if waiting on a specific checkpoint_id).
    pub custom_signal: Option<CustomSignal>,
}

/// Custom signal targeted to a specific checkpoint/wait key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CustomSignal {
    /// Target checkpoint/wait key
    pub checkpoint_id: String,
    /// Signal payload
    pub payload: Vec<u8>,
}

impl CheckpointResult {
    /// Returns Some(state) if an existing checkpoint was found (for resume).
    /// Returns None if a new checkpoint was saved.
    pub fn existing_state(&self) -> Option<&[u8]> {
        if self.found { Some(&self.state) } else { None }
    }

    /// Check if the instance should pause.
    pub fn should_pause(&self) -> bool {
        matches!(
            self.pending_signal.as_ref().map(|s| s.signal_type),
            Some(SignalType::Pause)
        )
    }

    /// Check if the instance should cancel.
    pub fn should_cancel(&self) -> bool {
        matches!(
            self.pending_signal.as_ref().map(|s| s.signal_type),
            Some(SignalType::Cancel)
        )
    }

    /// Check if the instance should exit due to a signal.
    pub fn should_exit(&self) -> bool {
        matches!(
            self.pending_signal.as_ref().map(|s| s.signal_type),
            Some(SignalType::Pause) | Some(SignalType::Cancel)
        )
    }
}

/// Instance status response with full details.
#[derive(Debug, Clone)]
pub struct StatusResponse {
    /// Whether the instance was found
    pub found: bool,
    /// Current status
    pub status: InstanceStatus,
    /// Last known checkpoint ID
    pub checkpoint_id: Option<String>,
    /// Output data if completed
    pub output: Option<Vec<u8>>,
    /// Error message if failed
    pub error: Option<String>,
}

// ============================================================================
// Retry Configuration
// ============================================================================

/// Retry strategy for durable functions.
///
/// Determines how delay between retry attempts is calculated.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RetryStrategy {
    /// Exponential backoff: delay * 2^(attempt-1)
    ///
    /// First retry: delay * 1
    /// Second retry: delay * 2
    /// Third retry: delay * 4
    /// ...
    #[default]
    ExponentialBackoff,
}

/// Configuration for retry behavior in durable functions.
///
/// Used by the `#[durable]` macro to control retry logic:
/// ```ignore
/// #[durable(max_retries = 3, strategy = ExponentialBackoff, delay = 1000)]
/// pub fn my_function(...) -> Result<T, E> { ... }
/// ```
#[derive(Debug, Clone)]
pub struct RetryConfig {
    /// Maximum number of retry attempts (0 = no retries, just one attempt).
    pub max_retries: u32,
    /// Base delay between retries in milliseconds.
    pub delay_ms: u64,
    /// Retry strategy for calculating delays.
    pub strategy: RetryStrategy,
}

impl RetryConfig {
    /// Create a new retry configuration.
    pub fn new(max_retries: u32, delay_ms: u64, strategy: RetryStrategy) -> Self {
        Self {
            max_retries,
            delay_ms,
            strategy,
        }
    }

    /// Calculate delay for a given attempt (1-indexed).
    ///
    /// Returns the duration to wait before the given retry attempt.
    /// Attempt 1 is the first retry (after the initial failure).
    pub fn delay_for_attempt(&self, attempt: u32) -> std::time::Duration {
        let multiplier = match self.strategy {
            RetryStrategy::ExponentialBackoff => 2u64.saturating_pow(attempt.saturating_sub(1)),
        };
        std::time::Duration::from_millis(self.delay_ms.saturating_mul(multiplier))
    }
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_retries: 0,
            delay_ms: 1000,
            strategy: RetryStrategy::default(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ============================================================================
    // InstanceStatus Tests
    // ============================================================================

    #[test]
    fn test_instance_status_clone_eq() {
        let status = InstanceStatus::Running;
        let cloned = status;
        assert_eq!(status, cloned);
    }

    #[test]
    fn test_instance_status_debug() {
        let status = InstanceStatus::Completed;
        let debug_str = format!("{:?}", status);
        assert!(debug_str.contains("Completed"));
    }

    // ============================================================================
    // SignalType Tests
    // ============================================================================

    #[test]
    fn test_signal_type_clone_eq() {
        let signal = SignalType::Pause;
        let cloned = signal;
        assert_eq!(signal, cloned);
    }

    // ============================================================================
    // Signal Tests
    // ============================================================================

    #[test]
    fn test_signal_creation() {
        let signal = Signal {
            signal_type: SignalType::Cancel,
            payload: vec![1, 2, 3],
            checkpoint_id: Some("checkpoint-1".to_string()),
        };

        assert_eq!(signal.signal_type, SignalType::Cancel);
        assert_eq!(signal.payload, vec![1, 2, 3]);
        assert_eq!(signal.checkpoint_id, Some("checkpoint-1".to_string()));
    }

    #[test]
    fn test_signal_without_checkpoint() {
        let signal = Signal {
            signal_type: SignalType::Pause,
            payload: vec![],
            checkpoint_id: None,
        };

        assert_eq!(signal.signal_type, SignalType::Pause);
        assert!(signal.payload.is_empty());
        assert!(signal.checkpoint_id.is_none());
    }

    #[test]
    fn test_signal_clone() {
        let signal = Signal {
            signal_type: SignalType::Resume,
            payload: vec![42],
            checkpoint_id: Some("cp".to_string()),
        };

        let cloned = signal.clone();
        assert_eq!(signal, cloned);
    }

    #[test]
    fn test_signal_debug() {
        let signal = Signal {
            signal_type: SignalType::Cancel,
            payload: vec![1],
            checkpoint_id: None,
        };
        let debug_str = format!("{:?}", signal);
        assert!(debug_str.contains("Cancel"));
    }

    // ============================================================================
    // CheckpointResult Tests
    // ============================================================================

    #[test]
    fn test_checkpoint_result_existing_state_found() {
        let result = CheckpointResult {
            found: true,
            state: vec![1, 2, 3],
            pending_signal: None,
            custom_signal: None,
        };

        assert!(result.found);
        assert_eq!(result.existing_state(), Some(&[1u8, 2, 3][..]));
    }

    #[test]
    fn test_checkpoint_result_existing_state_not_found() {
        let result = CheckpointResult {
            found: false,
            state: vec![1, 2, 3], // State might be present but found=false means new checkpoint
            pending_signal: None,
            custom_signal: None,
        };

        assert!(!result.found);
        assert_eq!(result.existing_state(), None);
    }

    #[test]
    fn test_checkpoint_result_should_pause() {
        let result = CheckpointResult {
            found: false,
            state: vec![],
            pending_signal: Some(Signal {
                signal_type: SignalType::Pause,
                payload: vec![],
                checkpoint_id: None,
            }),
            custom_signal: None,
        };

        assert!(result.should_pause());
        assert!(!result.should_cancel());
        assert!(result.should_exit()); // Pause means exit
    }

    #[test]
    fn test_checkpoint_result_should_cancel() {
        let result = CheckpointResult {
            found: false,
            state: vec![],
            pending_signal: Some(Signal {
                signal_type: SignalType::Cancel,
                payload: vec![],
                checkpoint_id: None,
            }),
            custom_signal: None,
        };

        assert!(result.should_cancel());
        assert!(!result.should_pause());
        assert!(result.should_exit()); // Cancel means exit
    }

    #[test]
    fn test_checkpoint_result_should_not_exit_on_resume() {
        let result = CheckpointResult {
            found: false,
            state: vec![],
            pending_signal: Some(Signal {
                signal_type: SignalType::Resume,
                payload: vec![],
                checkpoint_id: None,
            }),
            custom_signal: None,
        };

        assert!(!result.should_pause());
        assert!(!result.should_cancel());
        assert!(!result.should_exit()); // Resume doesn't mean exit
    }

    #[test]
    fn test_checkpoint_result_no_signal() {
        let result = CheckpointResult {
            found: true,
            state: vec![42],
            pending_signal: None,
            custom_signal: None,
        };

        assert!(!result.should_pause());
        assert!(!result.should_cancel());
        assert!(!result.should_exit());
    }

    #[test]
    fn test_checkpoint_result_with_custom_signal() {
        let result = CheckpointResult {
            found: false,
            state: vec![],
            pending_signal: None,
            custom_signal: Some(CustomSignal {
                checkpoint_id: "wait-key".to_string(),
                payload: vec![10, 20, 30],
            }),
        };

        // Custom signal doesn't affect should_pause/cancel/exit
        assert!(!result.should_pause());
        assert!(!result.should_cancel());
        assert!(!result.should_exit());

        // But we can access it
        let custom = result.custom_signal.as_ref().unwrap();
        assert_eq!(custom.checkpoint_id, "wait-key");
        assert_eq!(custom.payload, vec![10, 20, 30]);
    }

    #[test]
    fn test_checkpoint_result_clone() {
        let result = CheckpointResult {
            found: true,
            state: vec![1, 2, 3],
            pending_signal: Some(Signal {
                signal_type: SignalType::Pause,
                payload: vec![4],
                checkpoint_id: Some("cp".to_string()),
            }),
            custom_signal: Some(CustomSignal {
                checkpoint_id: "key".to_string(),
                payload: vec![5],
            }),
        };

        let cloned = result.clone();
        assert_eq!(result, cloned);
    }

    #[test]
    fn test_checkpoint_result_empty_state() {
        let result = CheckpointResult {
            found: true,
            state: vec![],
            pending_signal: None,
            custom_signal: None,
        };

        // Empty state is still "found"
        assert_eq!(result.existing_state(), Some(&[][..]));
    }

    // ============================================================================
    // CustomSignal Tests
    // ============================================================================

    #[test]
    fn test_custom_signal_creation() {
        let signal = CustomSignal {
            checkpoint_id: "my-wait-key".to_string(),
            payload: vec![1, 2, 3, 4],
        };

        assert_eq!(signal.checkpoint_id, "my-wait-key");
        assert_eq!(signal.payload, vec![1, 2, 3, 4]);
    }

    #[test]
    fn test_custom_signal_empty_payload() {
        let signal = CustomSignal {
            checkpoint_id: "empty-payload".to_string(),
            payload: vec![],
        };

        assert!(signal.payload.is_empty());
    }

    #[test]
    fn test_custom_signal_clone_eq() {
        let signal = CustomSignal {
            checkpoint_id: "test".to_string(),
            payload: vec![42],
        };

        let cloned = signal.clone();
        assert_eq!(signal, cloned);
    }

    // ============================================================================
    // StatusResponse Tests
    // ============================================================================

    #[test]
    fn test_status_response_not_found() {
        let response = StatusResponse {
            found: false,
            status: InstanceStatus::Unknown,
            checkpoint_id: None,
            output: None,
            error: None,
        };

        assert!(!response.found);
        assert_eq!(response.status, InstanceStatus::Unknown);
    }

    #[test]
    fn test_status_response_completed() {
        let response = StatusResponse {
            found: true,
            status: InstanceStatus::Completed,
            checkpoint_id: Some("final".to_string()),
            output: Some(vec![1, 2, 3]),
            error: None,
        };

        assert!(response.found);
        assert_eq!(response.status, InstanceStatus::Completed);
        assert_eq!(response.output, Some(vec![1, 2, 3]));
        assert!(response.error.is_none());
    }

    #[test]
    fn test_status_response_failed() {
        let response = StatusResponse {
            found: true,
            status: InstanceStatus::Failed,
            checkpoint_id: Some("step-3".to_string()),
            output: None,
            error: Some("something went wrong".to_string()),
        };

        assert!(response.found);
        assert_eq!(response.status, InstanceStatus::Failed);
        assert!(response.output.is_none());
        assert_eq!(response.error, Some("something went wrong".to_string()));
    }

    #[test]
    fn test_status_response_clone() {
        let response = StatusResponse {
            found: true,
            status: InstanceStatus::Running,
            checkpoint_id: Some("cp".to_string()),
            output: Some(vec![42]),
            error: None,
        };

        let cloned = response.clone();
        assert_eq!(cloned.found, response.found);
        assert_eq!(cloned.status, response.status);
        assert_eq!(cloned.checkpoint_id, response.checkpoint_id);
        assert_eq!(cloned.output, response.output);
    }

    // ============================================================================
    // RetryConfig Tests
    // ============================================================================

    #[test]
    fn test_retry_config_default() {
        let config = RetryConfig::default();
        assert_eq!(config.max_retries, 0);
        assert_eq!(config.delay_ms, 1000);
        assert_eq!(config.strategy, RetryStrategy::ExponentialBackoff);
    }

    #[test]
    fn test_retry_config_delay_calculation() {
        let config = RetryConfig::new(3, 100, RetryStrategy::ExponentialBackoff);

        // Attempt 1 (first retry): 100ms * 2^0 = 100ms
        assert_eq!(
            config.delay_for_attempt(1),
            std::time::Duration::from_millis(100)
        );

        // Attempt 2 (second retry): 100ms * 2^1 = 200ms
        assert_eq!(
            config.delay_for_attempt(2),
            std::time::Duration::from_millis(200)
        );

        // Attempt 3 (third retry): 100ms * 2^2 = 400ms
        assert_eq!(
            config.delay_for_attempt(3),
            std::time::Duration::from_millis(400)
        );
    }

    #[test]
    fn test_retry_strategy_default() {
        assert_eq!(RetryStrategy::default(), RetryStrategy::ExponentialBackoff);
    }

    #[test]
    fn test_retry_config_new() {
        let config = RetryConfig::new(5, 500, RetryStrategy::ExponentialBackoff);
        assert_eq!(config.max_retries, 5);
        assert_eq!(config.delay_ms, 500);
        assert_eq!(config.strategy, RetryStrategy::ExponentialBackoff);
    }

    #[test]
    fn test_retry_config_delay_attempt_zero() {
        let config = RetryConfig::new(3, 100, RetryStrategy::ExponentialBackoff);
        // Attempt 0 uses saturating_sub, so 2^(0-1) = 2^u32::MAX = saturates
        // Actually: 0.saturating_sub(1) = 0, so 2^0 = 1
        assert_eq!(
            config.delay_for_attempt(0),
            std::time::Duration::from_millis(100)
        );
    }

    #[test]
    fn test_retry_config_delay_large_attempt() {
        let config = RetryConfig::new(10, 100, RetryStrategy::ExponentialBackoff);
        // Attempt 10: 100ms * 2^9 = 100 * 512 = 51200ms
        assert_eq!(
            config.delay_for_attempt(10),
            std::time::Duration::from_millis(51200)
        );
    }

    #[test]
    fn test_retry_config_delay_overflow_protection() {
        // Test that we don't overflow with very large values
        let config = RetryConfig::new(100, u64::MAX, RetryStrategy::ExponentialBackoff);
        // This should use saturating_mul and not panic
        let _delay = config.delay_for_attempt(64); // 2^63 would overflow
        // Just verify it doesn't panic
    }

    #[test]
    fn test_retry_config_clone() {
        let config = RetryConfig::new(3, 200, RetryStrategy::ExponentialBackoff);
        let cloned = config.clone();
        assert_eq!(config.max_retries, cloned.max_retries);
        assert_eq!(config.delay_ms, cloned.delay_ms);
        assert_eq!(config.strategy, cloned.strategy);
    }

    #[test]
    fn test_retry_config_debug() {
        let config = RetryConfig::new(2, 1000, RetryStrategy::ExponentialBackoff);
        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("max_retries"));
        assert!(debug_str.contains("delay_ms"));
        assert!(debug_str.contains("strategy"));
    }
}