runtara-core 1.6.3

Core execution engine for runtara - manages instances, checkpoints, signals, and durable sleep
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
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
// Copyright (C) 2025 SyncMyOrders Sp. z o.o.
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Error types for runtara-core.
//!
//! Provides a unified error type that maps to RPC error responses,
//! including structured error types with category, severity, and retry hints.

#![allow(dead_code)] // Variants and methods used in tests and for future expansion

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;

// ============================================================================
// Structured Error Types
// ============================================================================

/// Error category for retry/routing decisions.
///
/// Two categories:
/// - **Transient**: Auto-retry likely to succeed (network, timeout, rate limit)
/// - **Permanent**: Don't auto-retry (validation, not found, auth, business rules)
///
/// To distinguish technical vs business errors within Permanent, use:
/// - `code`: e.g., `VALIDATION_*` for technical, `BUSINESS_*` or domain-specific codes
/// - `severity`: `Error` for technical failures, `Warning` for expected business outcomes
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCategory {
    /// Unknown category - use default retry policy.
    #[default]
    Unknown,
    /// Transient error - retry is likely to succeed (network, timeout, rate limit).
    Transient,
    /// Permanent error - don't retry (validation, not found, authorization, business rules).
    Permanent,
}

impl ErrorCategory {
    /// Returns the string representation of the category.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Unknown => "unknown",
            Self::Transient => "transient",
            Self::Permanent => "permanent",
        }
    }

    /// Parse a category from a string.
    pub fn parse(s: &str) -> Self {
        match s {
            "transient" => Self::Transient,
            "permanent" => Self::Permanent,
            // Legacy: map "business" to "permanent" for backwards compatibility
            "business" => Self::Permanent,
            _ => Self::Unknown,
        }
    }
}

/// Error severity for logging/alerting.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ErrorSeverity {
    /// Informational - expected errors that don't indicate a problem.
    Info,
    /// Warning - degraded but functional operation.
    Warning,
    /// Error - operation failed (default severity).
    #[default]
    Error,
    /// Critical - system-level failure requiring immediate attention.
    Critical,
}

impl ErrorSeverity {
    /// Returns the string representation of the severity.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Info => "info",
            Self::Warning => "warning",
            Self::Error => "error",
            Self::Critical => "critical",
        }
    }

    /// Parse a severity from a string.
    pub fn parse(s: &str) -> Self {
        match s {
            "info" => Self::Info,
            "warning" => Self::Warning,
            "critical" => Self::Critical,
            _ => Self::Error,
        }
    }
}

/// Hint for retry behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum RetryHint {
    /// Unknown - use default retry policy.
    #[default]
    Unknown,
    /// Retry immediately - transient glitch likely resolved.
    RetryImmediately,
    /// Retry with exponential backoff - standard retry strategy.
    RetryWithBackoff,
    /// Retry after specific duration in milliseconds (e.g., rate limit).
    #[serde(rename = "retry_after")]
    RetryAfter(u64),
    /// Do not retry - permanent error.
    DoNotRetry,
}

impl RetryHint {
    /// Returns the string representation of the hint.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Unknown => "unknown",
            Self::RetryImmediately => "retry_immediately",
            Self::RetryWithBackoff => "retry_with_backoff",
            Self::RetryAfter(_) => "retry_after",
            Self::DoNotRetry => "do_not_retry",
        }
    }

    /// Returns the retry delay in milliseconds if this is a RetryAfter hint.
    pub fn retry_after_ms(&self) -> Option<u64> {
        match self {
            Self::RetryAfter(ms) => Some(*ms),
            _ => None,
        }
    }

    /// Returns true if this error should be retried.
    pub fn should_retry(&self) -> bool {
        matches!(
            self,
            Self::RetryImmediately | Self::RetryWithBackoff | Self::RetryAfter(_)
        )
    }
}

/// Structured error with metadata for intelligent error handling.
///
/// This extends the basic error information with:
/// - Category: transient vs permanent (business errors are a subset of permanent)
/// - Severity: info/warning/error/critical for alerting
/// - Retry hint: whether and how to retry
/// - Attributes: additional context key-value pairs
/// - Cause: nested error for error chains
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StructuredError {
    /// Machine-readable error code (e.g., "RATE_LIMITED", "VALIDATION_ERROR")
    pub code: String,
    /// Human-readable error message
    pub message: String,
    /// Error category for routing/retry decisions
    #[serde(default)]
    pub category: ErrorCategory,
    /// Error severity for logging/alerting
    #[serde(default)]
    pub severity: ErrorSeverity,
    /// Hint for retry behavior
    #[serde(default)]
    pub retry_hint: RetryHint,
    /// Which step produced this error (if applicable)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_step_id: Option<String>,
    /// Additional context as key-value pairs
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub attributes: HashMap<String, String>,
    /// Nested cause error (for error chains)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cause: Option<Box<StructuredError>>,
}

impl StructuredError {
    /// Create a new structured error with minimal info.
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
            category: ErrorCategory::Unknown,
            severity: ErrorSeverity::Error,
            retry_hint: RetryHint::Unknown,
            source_step_id: None,
            attributes: HashMap::new(),
            cause: None,
        }
    }

    /// Create a transient error (retry recommended).
    pub fn transient(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
            category: ErrorCategory::Transient,
            severity: ErrorSeverity::Error,
            retry_hint: RetryHint::RetryWithBackoff,
            source_step_id: None,
            attributes: HashMap::new(),
            cause: None,
        }
    }

    /// Create a permanent error (don't retry).
    ///
    /// Use for: validation errors, not found, authorization failures, business rule violations.
    ///
    /// For business errors (expected outcomes like "credit limit exceeded"), use
    /// `.with_severity(ErrorSeverity::Warning)` to distinguish from technical failures.
    pub fn permanent(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
            category: ErrorCategory::Permanent,
            severity: ErrorSeverity::Error,
            retry_hint: RetryHint::DoNotRetry,
            source_step_id: None,
            attributes: HashMap::new(),
            cause: None,
        }
    }

    /// Set the source step ID.
    pub fn with_step(mut self, step_id: impl Into<String>) -> Self {
        self.source_step_id = Some(step_id.into());
        self
    }

    /// Add an attribute.
    pub fn with_attr(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.attributes.insert(key.into(), value.into());
        self
    }

    /// Set a cause error.
    pub fn with_cause(mut self, cause: StructuredError) -> Self {
        self.cause = Some(Box::new(cause));
        self
    }

    /// Set the severity.
    pub fn with_severity(mut self, severity: ErrorSeverity) -> Self {
        self.severity = severity;
        self
    }

    /// Set the retry hint.
    pub fn with_retry_hint(mut self, hint: RetryHint) -> Self {
        self.retry_hint = hint;
        self
    }

    /// Returns true if this is a transient error.
    pub fn is_transient(&self) -> bool {
        self.category == ErrorCategory::Transient
    }

    /// Returns true if this is a permanent error.
    pub fn is_permanent(&self) -> bool {
        self.category == ErrorCategory::Permanent
    }

    /// Returns true if this error should be retried.
    pub fn should_retry(&self) -> bool {
        self.retry_hint.should_retry()
    }
}

impl fmt::Display for StructuredError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}] {}", self.code, self.message)
    }
}

impl std::error::Error for StructuredError {}

// ============================================================================
// CoreError (existing)
// ============================================================================

/// Result type using CoreError
pub type Result<T> = std::result::Result<T, CoreError>;

/// Core errors that can occur during request processing.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum CoreError {
    /// Instance was not found in the database.
    InstanceNotFound {
        /// The instance ID that was not found.
        instance_id: String,
    },

    /// Instance already exists (duplicate registration).
    InstanceAlreadyExists {
        /// The instance ID that already exists.
        instance_id: String,
    },

    /// Instance is in an invalid state for the requested operation.
    InvalidInstanceState {
        /// The instance ID.
        instance_id: String,
        /// The expected status.
        expected: String,
        /// The actual status.
        actual: String,
    },

    /// Checkpoint was not found.
    CheckpointNotFound {
        /// The instance ID.
        instance_id: String,
        /// The checkpoint ID that was not found.
        checkpoint_id: Option<String>,
    },

    /// Checkpoint save failed.
    CheckpointSaveFailed {
        /// The instance ID.
        instance_id: String,
        /// The reason for failure.
        reason: String,
    },

    /// Signal delivery failed.
    SignalDeliveryFailed {
        /// The instance ID.
        instance_id: String,
        /// The signal type that failed.
        signal_type: String,
        /// The reason for failure.
        reason: String,
    },

    /// Input validation failed.
    ValidationError {
        /// The field that failed validation.
        field: String,
        /// The validation error message.
        message: String,
    },

    /// Database operation failed.
    DatabaseError {
        /// The operation that failed.
        operation: String,
        /// Error details.
        details: String,
    },
}

impl CoreError {
    /// Get the error code string for this error type.
    pub fn error_code(&self) -> &'static str {
        match self {
            Self::InstanceNotFound { .. } => "INSTANCE_NOT_FOUND",
            Self::InstanceAlreadyExists { .. } => "INSTANCE_ALREADY_EXISTS",
            Self::InvalidInstanceState { .. } => "INVALID_INSTANCE_STATE",
            Self::CheckpointNotFound { .. } => "CHECKPOINT_NOT_FOUND",
            Self::CheckpointSaveFailed { .. } => "CHECKPOINT_SAVE_FAILED",
            Self::SignalDeliveryFailed { .. } => "SIGNAL_DELIVERY_FAILED",
            Self::ValidationError { .. } => "VALIDATION_ERROR",
            Self::DatabaseError { .. } => "DATABASE_ERROR",
        }
    }
}

impl fmt::Display for CoreError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InstanceNotFound { instance_id } => {
                write!(f, "Instance '{}' not found", instance_id)
            }
            Self::InstanceAlreadyExists { instance_id } => {
                write!(f, "Instance '{}' already exists", instance_id)
            }
            Self::InvalidInstanceState {
                instance_id,
                expected,
                actual,
            } => {
                write!(
                    f,
                    "Instance '{}' is in invalid state: expected '{}', got '{}'",
                    instance_id, expected, actual
                )
            }
            Self::CheckpointNotFound {
                instance_id,
                checkpoint_id,
            } => {
                if let Some(cp_id) = checkpoint_id {
                    write!(
                        f,
                        "Checkpoint '{}' not found for instance '{}'",
                        cp_id, instance_id
                    )
                } else {
                    write!(f, "No checkpoints found for instance '{}'", instance_id)
                }
            }
            Self::CheckpointSaveFailed {
                instance_id,
                reason,
            } => {
                write!(
                    f,
                    "Failed to save checkpoint for instance '{}': {}",
                    instance_id, reason
                )
            }
            Self::SignalDeliveryFailed {
                instance_id,
                signal_type,
                reason,
            } => {
                write!(
                    f,
                    "Failed to deliver {} signal to instance '{}': {}",
                    signal_type, instance_id, reason
                )
            }
            Self::ValidationError { field, message } => {
                write!(f, "Validation error for '{}': {}", field, message)
            }
            Self::DatabaseError { operation, details } => {
                write!(f, "Database error during '{}': {}", operation, details)
            }
        }
    }
}

impl std::error::Error for CoreError {}

impl From<sqlx::Error> for CoreError {
    fn from(err: sqlx::Error) -> Self {
        CoreError::DatabaseError {
            operation: "query".to_string(),
            details: err.to_string(),
        }
    }
}

impl From<serde_json::Error> for CoreError {
    fn from(err: serde_json::Error) -> Self {
        CoreError::DatabaseError {
            operation: "json".to_string(),
            details: err.to_string(),
        }
    }
}

impl From<CoreError> for StructuredError {
    fn from(err: CoreError) -> Self {
        let (category, severity) = match &err {
            CoreError::InstanceNotFound { .. } => (ErrorCategory::Permanent, ErrorSeverity::Error),
            CoreError::InstanceAlreadyExists { .. } => {
                (ErrorCategory::Permanent, ErrorSeverity::Warning)
            }
            CoreError::InvalidInstanceState { .. } => {
                (ErrorCategory::Permanent, ErrorSeverity::Error)
            }
            CoreError::CheckpointNotFound { .. } => {
                (ErrorCategory::Permanent, ErrorSeverity::Error)
            }
            CoreError::CheckpointSaveFailed { .. } => {
                (ErrorCategory::Transient, ErrorSeverity::Error)
            }
            CoreError::SignalDeliveryFailed { .. } => {
                (ErrorCategory::Transient, ErrorSeverity::Warning)
            }
            CoreError::ValidationError { .. } => (ErrorCategory::Permanent, ErrorSeverity::Error),
            CoreError::DatabaseError { .. } => (ErrorCategory::Transient, ErrorSeverity::Critical),
        };

        let retry_hint = if category == ErrorCategory::Transient {
            RetryHint::RetryWithBackoff
        } else {
            RetryHint::DoNotRetry
        };

        Self {
            code: err.error_code().to_string(),
            message: err.to_string(),
            category,
            severity,
            retry_hint,
            source_step_id: None,
            attributes: HashMap::new(),
            cause: None,
        }
    }
}

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

    #[test]
    fn test_core_error_codes() {
        let test_cases = vec![
            (
                CoreError::InstanceNotFound {
                    instance_id: "test-id".to_string(),
                },
                "INSTANCE_NOT_FOUND",
            ),
            (
                CoreError::InstanceAlreadyExists {
                    instance_id: "test-id".to_string(),
                },
                "INSTANCE_ALREADY_EXISTS",
            ),
            (
                CoreError::InvalidInstanceState {
                    instance_id: "test-id".to_string(),
                    expected: "running".to_string(),
                    actual: "pending".to_string(),
                },
                "INVALID_INSTANCE_STATE",
            ),
            (
                CoreError::CheckpointNotFound {
                    instance_id: "test-id".to_string(),
                    checkpoint_id: Some("cp-1".to_string()),
                },
                "CHECKPOINT_NOT_FOUND",
            ),
            (
                CoreError::CheckpointSaveFailed {
                    instance_id: "test-id".to_string(),
                    reason: "disk full".to_string(),
                },
                "CHECKPOINT_SAVE_FAILED",
            ),
            (
                CoreError::SignalDeliveryFailed {
                    instance_id: "test-id".to_string(),
                    signal_type: "cancel".to_string(),
                    reason: "timeout".to_string(),
                },
                "SIGNAL_DELIVERY_FAILED",
            ),
            (
                CoreError::ValidationError {
                    field: "instance_id".to_string(),
                    message: "invalid UUID".to_string(),
                },
                "VALIDATION_ERROR",
            ),
            (
                CoreError::DatabaseError {
                    operation: "insert".to_string(),
                    details: "connection refused".to_string(),
                },
                "DATABASE_ERROR",
            ),
        ];

        for (error, expected_code) in test_cases {
            assert_eq!(
                error.error_code(),
                expected_code,
                "Error {:?} should have code {}",
                error,
                expected_code
            );
            assert!(!error.to_string().is_empty(), "Message should not be empty");
        }
    }

    #[test]
    fn test_core_error_display() {
        // Test InstanceNotFound
        let err = CoreError::InstanceNotFound {
            instance_id: "abc-123".to_string(),
        };
        assert_eq!(err.to_string(), "Instance 'abc-123' not found");

        // Test InstanceAlreadyExists
        let err = CoreError::InstanceAlreadyExists {
            instance_id: "abc-123".to_string(),
        };
        assert_eq!(err.to_string(), "Instance 'abc-123' already exists");

        // Test InvalidInstanceState
        let err = CoreError::InvalidInstanceState {
            instance_id: "abc-123".to_string(),
            expected: "running".to_string(),
            actual: "pending".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "Instance 'abc-123' is in invalid state: expected 'running', got 'pending'"
        );

        // Test CheckpointNotFound with checkpoint_id
        let err = CoreError::CheckpointNotFound {
            instance_id: "abc-123".to_string(),
            checkpoint_id: Some("cp-1".to_string()),
        };
        assert_eq!(
            err.to_string(),
            "Checkpoint 'cp-1' not found for instance 'abc-123'"
        );

        // Test CheckpointNotFound without checkpoint_id
        let err = CoreError::CheckpointNotFound {
            instance_id: "abc-123".to_string(),
            checkpoint_id: None,
        };
        assert_eq!(
            err.to_string(),
            "No checkpoints found for instance 'abc-123'"
        );

        // Test ValidationError
        let err = CoreError::ValidationError {
            field: "instance_id".to_string(),
            message: "must be a valid UUID".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "Validation error for 'instance_id': must be a valid UUID"
        );

        // Test DatabaseError
        let err = CoreError::DatabaseError {
            operation: "insert".to_string(),
            details: "connection refused".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "Database error during 'insert': connection refused"
        );
    }

    #[test]
    fn test_error_code_method() {
        assert_eq!(
            CoreError::InstanceNotFound {
                instance_id: "x".to_string()
            }
            .error_code(),
            "INSTANCE_NOT_FOUND"
        );
        assert_eq!(
            CoreError::ValidationError {
                field: "x".to_string(),
                message: "y".to_string()
            }
            .error_code(),
            "VALIDATION_ERROR"
        );
    }
}