Skip to main content

orcher_sdk/
error.rs

1//! Error types for the Orcher Rust SDK.
2//!
3//! [`Error`] wraps one enum per area: workflows, tasks, the client and the worker.
4//!
5//! ## Error Conversion
6//!
7//! Errors from `sdk-core` convert into [`Error`] through `From`:
8//!
9//! ```rust
10//! use orcher_sdk::prelude::*;
11//!
12//! #[derive(Deserialize)]
13//! struct Config {
14//!     retries: u32,
15//! }
16//!
17//! fn parse(json: &str) -> Result<Config> {
18//!     // `?` converts the `serde_json::Error` into an `orcher_sdk::Error`.
19//!     Ok(serde_json::from_str(json)?)
20//! }
21//!
22//! assert!(parse(r#"{"retries": 3}"#).is_ok());
23//! assert!(matches!(parse("not json"), Err(Error::Serialization(_))));
24//! ```
25//!
26//! ## Error Classification
27//!
28//! [`Error::is_retryable`] and [`Error::is_permanent`] classify an error. An error can be
29//! neither, in which case the caller decides.
30//!
31//! ```rust
32//! use orcher_sdk::error::{ClientError, Error};
33//! use std::time::Duration;
34//!
35//! fn describe(error: &Error) -> &'static str {
36//!     if error.is_retryable() {
37//!         "retry the operation"
38//!     } else if error.is_permanent() {
39//!         "fatal, do not retry"
40//!     } else {
41//!         "the caller decides"
42//!     }
43//! }
44//!
45//! let timeout = Error::Client(ClientError::timeout(Duration::from_secs(5)));
46//! assert_eq!(describe(&timeout), "retry the operation");
47//!
48//! let bad_config = Error::Configuration("missing server URL".to_string());
49//! assert_eq!(describe(&bad_config), "fatal, do not retry");
50//! ```
51
52/// Result type alias for SDK operations.
53pub type Result<T> = std::result::Result<T, Error>;
54
55/// JSON marker key that encodes a terminal task failure as an injected replay result.
56///
57/// When a task fails terminally (retries exhausted, or moved to the dead-letter queue), the
58/// server delivers it to the worker as a `CompleteStep{failure}` job. The worker injects a small
59/// JSON object under this key, in the slot for that step, so that `execute_task`/`execute` decode
60/// it on replay and raise a catchable [`WorkflowError::TaskFailed`] instead of deserializing it
61/// as a success value. It mirrors the child-workflow failure marker. The key is part of the wire
62/// format and must stay byte-identical across SDKs.
63pub(crate) const TASK_FAILED_SENTINEL_KEY: &str = "__orcher_task_failed__";
64
65/// Machine-readable error code, shared by the Rust, TypeScript and Python SDKs.
66///
67/// The `Display` form (for example `TASK_FAILED`) is the same string in every SDK.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
69#[non_exhaustive]
70pub enum ErrorCode {
71    // Workflow errors
72    /// Workflow execution failed
73    WorkflowFailed,
74    /// Workflow not found
75    WorkflowNotFound,
76    /// Workflow already exists
77    WorkflowAlreadyExists,
78    /// Workflow was canceled
79    WorkflowCanceled,
80    /// Workflow timed out
81    WorkflowTimeout,
82    /// Non-deterministic workflow execution detected
83    WorkflowNonDeterministic,
84    /// Workflow state error
85    WorkflowStateError,
86    /// Workflow version mismatch
87    WorkflowVersionMismatch,
88    /// Workflow replay error
89    WorkflowReplayError,
90
91    // Task errors
92    /// Task execution failed
93    TaskFailed,
94    /// Task not found
95    TaskNotFound,
96    /// Task timed out
97    TaskTimeout,
98    /// Task was canceled
99    TaskCanceled,
100    /// Task heartbeat failed
101    TaskHeartbeatFailed,
102    /// Task retry limit exceeded
103    TaskRetryLimitExceeded,
104    /// Invalid task input
105    TaskInvalidInput,
106
107    // Client errors
108    /// Connection to server failed
109    ConnectionFailed,
110    /// Request timed out
111    RequestTimeout,
112    /// Authentication failed
113    AuthenticationFailed,
114    /// Authorization failed
115    AuthorizationFailed,
116    /// Server returned an error
117    ServerError,
118    /// Invalid request
119    InvalidRequest,
120
121    // Service errors
122    /// Invalid configuration
123    InvalidConfiguration,
124    /// Service startup failed
125    StartupFailed,
126    /// Service shutdown error
127    ShutdownError,
128    /// Handler not found
129    HandlerNotFound,
130    /// Resource exhausted
131    ResourceExhausted,
132    /// Polling error
133    PollingError,
134
135    // General errors
136    /// Serialization/deserialization error
137    SerializationError,
138    /// Network/transport error
139    NetworkError,
140    /// I/O error
141    IoError,
142    /// Internal/unknown error
143    Internal,
144}
145
146impl std::fmt::Display for ErrorCode {
147    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148        let s = match self {
149            Self::WorkflowFailed => "WORKFLOW_FAILED",
150            Self::WorkflowNotFound => "WORKFLOW_NOT_FOUND",
151            Self::WorkflowAlreadyExists => "WORKFLOW_ALREADY_EXISTS",
152            Self::WorkflowCanceled => "WORKFLOW_CANCELED",
153            Self::WorkflowTimeout => "WORKFLOW_TIMEOUT",
154            Self::WorkflowNonDeterministic => "WORKFLOW_NON_DETERMINISTIC",
155            Self::WorkflowStateError => "WORKFLOW_STATE_ERROR",
156            Self::WorkflowVersionMismatch => "WORKFLOW_VERSION_MISMATCH",
157            Self::WorkflowReplayError => "WORKFLOW_REPLAY_ERROR",
158            Self::TaskFailed => "TASK_FAILED",
159            Self::TaskNotFound => "TASK_NOT_FOUND",
160            Self::TaskTimeout => "TASK_TIMEOUT",
161            Self::TaskCanceled => "TASK_CANCELED",
162            Self::TaskHeartbeatFailed => "TASK_HEARTBEAT_FAILED",
163            Self::TaskRetryLimitExceeded => "TASK_RETRY_LIMIT_EXCEEDED",
164            Self::TaskInvalidInput => "TASK_INVALID_INPUT",
165            Self::ConnectionFailed => "CONNECTION_FAILED",
166            Self::RequestTimeout => "REQUEST_TIMEOUT",
167            Self::AuthenticationFailed => "AUTHENTICATION_FAILED",
168            Self::AuthorizationFailed => "AUTHORIZATION_FAILED",
169            Self::ServerError => "SERVER_ERROR",
170            Self::InvalidRequest => "INVALID_REQUEST",
171            Self::InvalidConfiguration => "INVALID_CONFIGURATION",
172            Self::StartupFailed => "STARTUP_FAILED",
173            Self::ShutdownError => "SHUTDOWN_ERROR",
174            Self::HandlerNotFound => "HANDLER_NOT_FOUND",
175            Self::ResourceExhausted => "RESOURCE_EXHAUSTED",
176            Self::PollingError => "POLLING_ERROR",
177            Self::SerializationError => "SERIALIZATION_ERROR",
178            Self::NetworkError => "NETWORK_ERROR",
179            Self::IoError => "IO_ERROR",
180            Self::Internal => "INTERNAL",
181        };
182        write!(f, "{}", s)
183    }
184}
185
186/// How urgently an error needs an operator's attention, shared by all SDKs.
187#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
188pub enum Severity {
189    /// Low severity — informational, operation can continue
190    Low,
191    /// Medium severity — degraded functionality, should investigate
192    Medium,
193    /// High severity — significant impact, needs attention
194    High,
195    /// Critical severity — service at risk, immediate action needed
196    Critical,
197}
198
199impl std::fmt::Display for Severity {
200    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201        let s = match self {
202            Self::Low => "LOW",
203            Self::Medium => "MEDIUM",
204            Self::High => "HIGH",
205            Self::Critical => "CRITICAL",
206        };
207        write!(f, "{}", s)
208    }
209}
210
211/// Main error type for the Orcher Rust SDK.
212///
213/// This enum, the per-area enums it wraps, and their variants with named
214/// fields are all `#[non_exhaustive]`: a new kind of error, or a new detail on
215/// an existing one, is not a breaking change. Match with a wildcard arm and
216/// `..` in struct patterns, and build errors with the constructors such as
217/// [`TaskError::application`] or [`ClientError::workflow_not_found`].
218#[derive(Debug, thiserror::Error)]
219#[non_exhaustive]
220pub enum Error {
221    /// Workflow execution error
222    #[error("Workflow error: {0}")]
223    Workflow(#[from] WorkflowError),
224
225    /// Task execution error
226    #[error("Task error: {0}")]
227    Task(#[from] TaskError),
228
229    /// Client operation error
230    #[error("Client error: {0}")]
231    Client(#[from] ClientError),
232
233    /// Worker error
234    #[error("Worker error: {0}")]
235    Worker(#[from] WorkerError),
236
237    /// Actor operation error
238    #[error("Actor error: {0}")]
239    Actor(String),
240
241    /// Network/RPC error
242    #[error("Network error: {0}")]
243    Network(String),
244
245    /// Configuration error
246    #[error("Configuration error: {0}")]
247    Configuration(String),
248
249    /// Serialization/deserialization error
250    #[error("Serialization error: {0}")]
251    Serialization(String),
252
253    /// Timeout error
254    #[error("Timeout: {0}")]
255    Timeout(String),
256
257    /// I/O error
258    #[error("I/O error: {0}")]
259    Io(#[from] std::io::Error),
260
261    /// Generic error
262    #[error("{0}")]
263    Other(String),
264}
265
266/// The failure type a cancelled task's failure is recorded under.
267const CANCELLED_FAILURE_TYPE: &str = "Cancelled";
268
269/// The category of a task failure that reached the workflow, as
270/// [`WorkflowError::TaskFailed`] carries it.
271///
272/// It mirrors the kernel protocol's failure code. New categories may be added,
273/// so match with a wildcard arm.
274#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
275#[non_exhaustive]
276pub enum TaskFailureCode {
277    /// Not categorized, for example a failure journaled before failures
278    /// carried a category, or one of a category this SDK does not know.
279    #[default]
280    Unspecified,
281    /// The task's code raised it.
282    Application,
283    /// A timeout expired.
284    TimedOut,
285    /// The task was cancelled.
286    Cancelled,
287    /// The task was terminated, without cleanup.
288    Terminated,
289    /// The workflow's code no longer replays its history.
290    NonDeterminism,
291    /// A payload was over the engine's size limit.
292    PayloadTooLarge,
293    /// A command was malformed or not allowed.
294    InvalidCommand,
295}
296
297impl TaskFailureCode {
298    /// Whether the task was cancelled rather than failing on its own.
299    pub fn is_cancelled(self) -> bool {
300        self == Self::Cancelled
301    }
302
303    /// Whether a timeout expired.
304    pub fn is_timed_out(self) -> bool {
305        self == Self::TimedOut
306    }
307
308    /// Whether the task's code raised it.
309    pub fn is_application(self) -> bool {
310        self == Self::Application
311    }
312
313    /// The category's stable name, for example `cancelled`.
314    pub fn as_str(self) -> &'static str {
315        match self {
316            Self::Unspecified => "unspecified",
317            Self::Application => "application",
318            Self::TimedOut => "timed_out",
319            Self::Cancelled => "cancelled",
320            Self::Terminated => "terminated",
321            Self::NonDeterminism => "non_determinism",
322            Self::PayloadTooLarge => "payload_too_large",
323            Self::InvalidCommand => "invalid_command",
324        }
325    }
326
327    /// The category named `name` by [`as_str`](Self::as_str); an unknown name
328    /// is [`Unspecified`](Self::Unspecified).
329    pub(crate) fn from_name(name: &str) -> Self {
330        match name {
331            "application" => Self::Application,
332            "timed_out" => Self::TimedOut,
333            "cancelled" => Self::Cancelled,
334            "terminated" => Self::Terminated,
335            "non_determinism" => Self::NonDeterminism,
336            "payload_too_large" => Self::PayloadTooLarge,
337            "invalid_command" => Self::InvalidCommand,
338            _ => Self::Unspecified,
339        }
340    }
341}
342
343impl std::fmt::Display for TaskFailureCode {
344    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
345        f.write_str(self.as_str())
346    }
347}
348
349/// Errors that can occur during workflow execution.
350#[derive(Debug, Clone, thiserror::Error)]
351#[non_exhaustive]
352pub enum WorkflowError {
353    /// A task executed by the workflow failed
354    #[error("Task '{task_type}' failed after {attempts} attempts: {reason}")]
355    #[non_exhaustive]
356    TaskFailed {
357        /// The type/name of the task that failed
358        task_type: String,
359        /// Number of retry attempts made
360        attempts: u32,
361        /// The reason for the failure
362        reason: String,
363        /// The failure's type, as a retry policy's non-retryable list names it:
364        /// the `error_type` of a [`TaskError::application`] failure, for
365        /// example. Empty for a failure of no particular type.
366        error_type: String,
367        /// The failure's category: whether the task's code raised it, it was
368        /// cancelled, or it timed out.
369        code: TaskFailureCode,
370    },
371
372    /// A timer operation failed
373    #[error("Timer '{timer_id}' failed: {reason}")]
374    #[non_exhaustive]
375    TimerFailed {
376        /// The ID of the timer that failed
377        timer_id: String,
378        /// The reason for the failure
379        reason: String,
380    },
381
382    /// A child workflow failed
383    #[error("Child workflow '{workflow_type}' (ID: {workflow_id}) failed: {reason}")]
384    #[non_exhaustive]
385    ChildWorkflowFailed {
386        /// The type of the child workflow
387        workflow_type: String,
388        /// The ID of the child workflow instance
389        workflow_id: String,
390        /// The reason for the failure
391        reason: String,
392    },
393
394    /// Workflow state management error
395    #[error("State error: {0}")]
396    StateError(
397        /// Description of the state error
398        String,
399    ),
400
401    /// Workflow was canceled
402    #[error("Workflow was canceled")]
403    Canceled,
404
405    /// Workflow timed out
406    #[error("Workflow execution timed out after {timeout:?}")]
407    #[non_exhaustive]
408    Timeout {
409        /// The timeout duration that was exceeded
410        timeout: std::time::Duration,
411    },
412
413    /// Workflow panicked
414    #[error("Workflow panicked: {0}")]
415    Panic(
416        /// The panic message
417        String,
418    ),
419
420    /// Workflow execution is not deterministic
421    #[error("Non-deterministic workflow execution detected: {0}")]
422    NonDeterministic(
423        /// Description of the non-determinism violation
424        String,
425    ),
426
427    /// Event handling error
428    #[error("Event '{event}' error: {reason}")]
429    #[non_exhaustive]
430    EventError {
431        /// The name of the event that failed
432        event: String,
433        /// The reason for the failure
434        reason: String,
435    },
436
437    /// Query handling error
438    #[error("Query '{query}' error: {reason}")]
439    #[non_exhaustive]
440    QueryError {
441        /// The name of the query that failed
442        query: String,
443        /// The reason for the failure
444        reason: String,
445    },
446
447    /// A saga's compensations ran, and at least one of them failed.
448    ///
449    /// Every compensation still runs when one fails; this reports the ones
450    /// that failed once all have run. Returned by [`Saga::compensate`], and by
451    /// a failed saga step whose compensating failed, which then carries the
452    /// step's own failure in `step_failure`.
453    ///
454    /// [`Saga::compensate`]: crate::workflow::Saga::compensate
455    #[error("{}", compensation_failed_message(failed, reason, step_failure.as_deref()))]
456    #[non_exhaustive]
457    CompensationFailed {
458        /// The compensation tasks that failed, in the order they ran.
459        failed: Vec<String>,
460        /// The first failed compensation's error.
461        reason: String,
462        /// The failure of the saga step that started the compensating, or
463        /// `None` when the workflow compensated the saga itself.
464        step_failure: Option<String>,
465    },
466
467    /// Invalid workflow state
468    #[error("Invalid workflow state: {0}")]
469    InvalidState(
470        /// Description of the invalid state
471        String,
472    ),
473
474    /// Workflow not found
475    #[error("Workflow '{workflow_id}' not found")]
476    #[non_exhaustive]
477    NotFound {
478        /// The ID of the workflow that was not found
479        workflow_id: String,
480    },
481
482    /// Replay error
483    #[error("Replay error: {0}")]
484    ReplayError(
485        /// Description of the replay error
486        String,
487    ),
488
489    /// Restarting the workflow fresh failed.
490    #[error("Restart fresh error: {0}")]
491    RestartFreshError(
492        /// Description of the restart error
493        String,
494    ),
495
496    /// Version mismatch error
497    #[error("Version mismatch: expected {expected}, got {actual}")]
498    #[non_exhaustive]
499    VersionMismatch {
500        /// The expected version
501        expected: String,
502        /// The actual version found
503        actual: String,
504    },
505
506    /// The workflow is waiting for operations it started to complete.
507    ///
508    /// This is control flow, not a failure. A workflow returns it when it calls
509    /// `ctx.execute()` and the result is not available yet. The workflow executor
510    /// catches it, sends the pending commands to the server, and replays the
511    /// workflow once results arrive. See [`Error::is_suspend`].
512    #[error("Workflow suspended: {reason}")]
513    #[non_exhaustive]
514    Suspended {
515        /// Human-readable reason for suspension
516        reason: String,
517        /// List of pending operation IDs (task IDs, timer IDs, etc.)
518        pending_operations: Vec<String>,
519    },
520}
521
522/// The message of [`WorkflowError::CompensationFailed`].
523fn compensation_failed_message(
524    failed: &[String],
525    reason: &str,
526    step_failure: Option<&str>,
527) -> String {
528    let first = failed.first().map(String::as_str).unwrap_or("unknown");
529    let mut message = if failed.len() > 1 {
530        format!(
531            "Saga compensation failed: {} compensations failed, the first '{first}': {reason}",
532            failed.len()
533        )
534    } else {
535        format!("Saga compensation failed: compensation '{first}' failed: {reason}")
536    };
537    if let Some(step) = step_failure {
538        message.push_str(&format!(
539            "; the compensating followed a failed step: {step}"
540        ));
541    }
542    message
543}
544
545/// Errors that can occur during task execution.
546#[derive(Debug, Clone, thiserror::Error)]
547#[non_exhaustive]
548pub enum TaskError {
549    /// Task execution failed
550    #[error("Task execution failed: {0}")]
551    ExecutionFailed(
552        /// Description of the execution failure
553        String,
554    ),
555
556    /// Task timed out
557    #[error("Task execution timed out after {timeout:?}")]
558    #[non_exhaustive]
559    Timeout {
560        /// The timeout duration that was exceeded
561        timeout: std::time::Duration,
562    },
563
564    /// Task was canceled
565    #[error("Task was canceled")]
566    Canceled,
567
568    /// Heartbeat failed
569    #[error("Heartbeat failed: {0}")]
570    HeartbeatFailed(
571        /// Details about the heartbeat failure
572        String,
573    ),
574
575    /// Heartbeat timeout (no heartbeat received)
576    #[error("No heartbeat received within {timeout:?}")]
577    #[non_exhaustive]
578    HeartbeatTimeout {
579        /// The timeout duration that was exceeded
580        timeout: std::time::Duration,
581    },
582
583    /// Task not found
584    #[error("Task '{task_id}' not found")]
585    #[non_exhaustive]
586    NotFound {
587        /// The ID of the task that was not found
588        task_id: String,
589    },
590
591    /// Task already completed
592    #[error("Task '{task_id}' already completed")]
593    #[non_exhaustive]
594    AlreadyCompleted {
595        /// The ID of the task that was already completed
596        task_id: String,
597    },
598
599    /// Task panic
600    #[error("Task panicked: {0}")]
601    Panic(
602        /// The panic message
603        String,
604    ),
605
606    /// Retry limit exceeded
607    #[error("Task failed after {attempts} retry attempts")]
608    #[non_exhaustive]
609    RetryLimitExceeded {
610        /// Number of retry attempts that were made
611        attempts: u32,
612    },
613
614    /// Invalid task input
615    #[error("Invalid task input: {0}")]
616    InvalidInput(
617        /// Description of the invalid input
618        String,
619    ),
620
621    /// Invalid task configuration
622    #[error("Invalid task configuration: {0}")]
623    InvalidConfiguration(
624        /// Description of the configuration error
625        String,
626    ),
627
628    /// A failure the task's own code names, reported to the engine under
629    /// `error_type` so a retry policy's non-retryable list can match it.
630    /// Build one with [`TaskError::application`] or
631    /// [`TaskError::non_retryable`].
632    #[error("{message}")]
633    #[non_exhaustive]
634    Application {
635        /// The name a retry policy lists the failure under.
636        error_type: String,
637        /// What went wrong.
638        message: String,
639        /// No retry can succeed: the engine does not retry the task,
640        /// whatever its policy allows.
641        non_retryable: bool,
642    },
643}
644
645/// Errors that can occur during client operations.
646#[derive(Debug, Clone, thiserror::Error)]
647#[non_exhaustive]
648pub enum ClientError {
649    /// Connection to server failed
650    #[error("Failed to connect to server at '{url}': {reason}")]
651    #[non_exhaustive]
652    ConnectionFailed {
653        /// The server URL that failed to connect
654        url: String,
655        /// The reason for connection failure
656        reason: String,
657    },
658
659    /// Request failed
660    #[error("Request failed: {0}")]
661    RequestFailed(
662        /// Details about the request failure
663        String,
664    ),
665
666    /// Request timed out
667    #[error("Request timed out after {timeout:?}")]
668    #[non_exhaustive]
669    Timeout {
670        /// The timeout duration that was exceeded
671        timeout: std::time::Duration,
672    },
673
674    /// Invalid server URL
675    #[error("Invalid server URL: {0}")]
676    InvalidUrl(
677        /// Description of the invalid URL
678        String,
679    ),
680
681    /// Authentication failed
682    #[error("Authentication failed: {0}")]
683    AuthenticationFailed(
684        /// Details about the authentication failure
685        String,
686    ),
687
688    /// Authorization failed
689    #[error("Authorization failed: {0}")]
690    AuthorizationFailed(
691        /// Details about the authorization failure
692        String,
693    ),
694
695    /// Workflow not found
696    #[error("Workflow '{workflow_id}' not found")]
697    #[non_exhaustive]
698    WorkflowNotFound {
699        /// The ID of the workflow that was not found
700        workflow_id: String,
701    },
702
703    /// The workflow id is already in use: its run is still open, or a closed
704    /// one the start's reuse policy does not allow reusing.
705    #[error("Workflow '{workflow_id}' already exists")]
706    #[non_exhaustive]
707    WorkflowAlreadyExists {
708        /// The ID of the workflow that already exists
709        workflow_id: String,
710        /// The run in the way, when the server named it: the one to wait on
711        /// for a caller that meant to start the workflow once.
712        run_id: Option<String>,
713    },
714
715    /// Invalid workflow input
716    #[error("Invalid workflow input: {0}")]
717    InvalidInput(
718        /// Description of the invalid input
719        String,
720    ),
721
722    /// Invalid response from server
723    #[error("Invalid response from server: {0}")]
724    InvalidResponse(
725        /// Description of the invalid response
726        String,
727    ),
728
729    /// Server returned an error
730    #[error("Server error (status {status}): {message}")]
731    #[non_exhaustive]
732    ServerError {
733        /// HTTP status code
734        status: u16,
735        /// Error message from server
736        message: String,
737    },
738
739    /// Serialization error
740    #[error("Serialization error: {0}")]
741    Serialization(
742        /// Details about the serialization error
743        String,
744    ),
745
746    /// Deserialization error
747    #[error("Deserialization error: {0}")]
748    Deserialization(
749        /// Details about the deserialization error
750        String,
751    ),
752}
753
754/// Errors that can occur in a worker.
755#[derive(Debug, Clone, thiserror::Error)]
756#[non_exhaustive]
757pub enum WorkerError {
758    /// Worker configuration is invalid
759    #[error("Invalid configuration: {0}")]
760    InvalidConfiguration(
761        /// Description of the configuration error
762        String,
763    ),
764
765    /// Worker failed to start
766    #[error("Failed to start service: {0}")]
767    StartupFailed(
768        /// Details about the startup failure
769        String,
770    ),
771
772    /// Worker already running
773    #[error("Worker is already running")]
774    AlreadyRunning,
775
776    /// Worker not running
777    #[error("Worker is not running")]
778    NotRunning,
779
780    /// Failed to connect to server
781    #[error("Failed to connect to server at '{url}': {reason}")]
782    #[non_exhaustive]
783    ConnectionFailed {
784        /// The server URL that failed to connect
785        url: String,
786        /// The reason for connection failure
787        reason: String,
788    },
789
790    /// Polling error
791    #[error("Polling error: {0}")]
792    PollingError(
793        /// Details about the polling error
794        String,
795    ),
796
797    /// Handler registration error
798    #[error("Handler registration error: {0}")]
799    RegistrationError(
800        /// Details about the registration error
801        String,
802    ),
803
804    /// Handler not found
805    #[error("No handler registered for '{handler_type}' with name '{name}'")]
806    #[non_exhaustive]
807    HandlerNotFound {
808        /// The type of handler (e.g., "workflow", "task")
809        handler_type: String,
810        /// The name of the handler that was not found
811        name: String,
812    },
813
814    /// Handler execution error
815    #[error("Handler execution error: {0}")]
816    HandlerExecutionError(
817        /// Details about the handler execution error
818        String,
819    ),
820
821    /// Shutdown error
822    #[error("Shutdown error: {0}")]
823    ShutdownError(
824        /// Details about the shutdown error
825        String,
826    ),
827
828    /// Shutdown timeout
829    #[error("Shutdown timed out after {timeout:?}")]
830    #[non_exhaustive]
831    ShutdownTimeout {
832        /// The timeout duration that was exceeded
833        timeout: std::time::Duration,
834    },
835
836    /// Resource exhausted
837    #[error("Resource exhausted: {resource}")]
838    #[non_exhaustive]
839    ResourceExhausted {
840        /// The name of the exhausted resource
841        resource: String,
842    },
843
844    /// Task queue not found
845    #[error("Task queue '{queue}' not found")]
846    #[non_exhaustive]
847    TaskQueueNotFound {
848        /// The name of the task queue that was not found
849        queue: String,
850    },
851}
852
853// ============================================================================
854// Error Conversions
855// ============================================================================
856
857/// Translate a gRPC status code to its conventional HTTP equivalent.
858///
859/// This exists so that error classification (retryable or not) and the status a
860/// user sees are both meaningful. The mapping is the standard one. The cases that
861/// matter most are UNAVAILABLE and DEADLINE_EXCEEDED landing in 5xx so they are
862/// retried, and NOT_FOUND landing in 4xx so it is not.
863fn grpc_code_to_http_status(code: orcher_sdk_core::error::Code) -> u16 {
864    use orcher_sdk_core::error::Code;
865    match code {
866        Code::Ok => 200,
867        Code::InvalidArgument | Code::OutOfRange | Code::FailedPrecondition => 400,
868        Code::Unauthenticated => 401,
869        Code::PermissionDenied => 403,
870        Code::NotFound => 404,
871        Code::AlreadyExists | Code::Aborted => 409,
872        Code::Cancelled => 499,
873        Code::ResourceExhausted => 429,
874        Code::Unimplemented => 501,
875        Code::Unavailable => 503,
876        Code::DeadlineExceeded => 504,
877        // Internal, Unknown, DataLoss and anything new default to 500, which is
878        // retryable — the safer side for a transient server-side failure.
879        _ => 500,
880    }
881}
882
883impl From<orcher_sdk_core::error::Error> for Error {
884    fn from(err: orcher_sdk_core::error::Error) -> Self {
885        use orcher_sdk_core::error::Error as CoreError;
886
887        match err {
888            // Workflow errors
889            CoreError::WorkflowNotFound { workflow_id, .. } => {
890                Error::Workflow(WorkflowError::NotFound { workflow_id })
891            }
892            CoreError::WorkflowAlreadyExists {
893                workflow_id,
894                run_id,
895                ..
896            } => Error::Client(ClientError::WorkflowAlreadyExists {
897                workflow_id,
898                run_id,
899            }),
900            CoreError::WorkflowExecutionFailed { message, .. } => {
901                Error::Workflow(WorkflowError::Panic(message))
902            }
903            CoreError::WorkflowCancelled { .. } => Error::Workflow(WorkflowError::Canceled),
904            CoreError::WorkflowTerminated { reason, .. } => Error::Workflow(WorkflowError::Panic(
905                reason.unwrap_or_else(|| "Workflow terminated".to_string()),
906            )),
907
908            // Task errors
909            CoreError::TaskExecutionFailed { reason, .. } => {
910                Error::Task(TaskError::ExecutionFailed(reason))
911            }
912            CoreError::TaskCancelled { .. } => Error::Task(TaskError::Canceled),
913
914            // State machine errors
915            CoreError::InvalidWorkflowState {
916                expected, actual, ..
917            } => Error::Workflow(WorkflowError::InvalidState(format!(
918                "Expected state: {}, got: {}",
919                expected, actual
920            ))),
921            CoreError::DeterminismViolation { reason, .. } => {
922                Error::Workflow(WorkflowError::NonDeterministic(reason))
923            }
924            CoreError::InvalidExecutionJournal { reason, .. } => {
925                Error::Workflow(WorkflowError::ReplayError(reason))
926            }
927            CoreError::ReplayError(reason) => Error::Workflow(WorkflowError::ReplayError(reason)),
928
929            // Serialization errors
930            CoreError::Serialization(msg) => Error::Serialization(msg),
931            CoreError::Deserialization(msg) => Error::Serialization(msg),
932            CoreError::InvalidPayload { reason, .. } => Error::Serialization(reason),
933            CoreError::Codec(msg) => Error::Serialization(msg),
934
935            // A call the engine refused.
936            CoreError::Status(status) => Error::Client(ClientError::ServerError {
937                // gRPC codes are 0-16, but `is_retryable` classifies ServerError by
938                // HTTP range. Storing the raw code would make every gRPC failure
939                // non-retryable, including UNAVAILABLE and DEADLINE_EXCEEDED, so
940                // translate to HTTP here at the boundary.
941                status: grpc_code_to_http_status(status.code()),
942                message: status.message().to_string(),
943            }),
944
945            // Connection and auth errors
946            CoreError::Connection(msg) => Error::Client(ClientError::ConnectionFailed {
947                url: "unknown".to_string(),
948                reason: msg,
949            }),
950            CoreError::Authentication(msg) => Error::Client(ClientError::AuthenticationFailed(msg)),
951            CoreError::Authorization(msg) => Error::Client(ClientError::AuthorizationFailed(msg)),
952
953            // Configuration errors
954            CoreError::Configuration(msg) => Error::Configuration(msg),
955
956            // Worker errors
957            CoreError::WorkerError(msg) => Error::Worker(WorkerError::PollingError(msg)),
958            CoreError::PollerError(msg) => Error::Worker(WorkerError::PollingError(msg)),
959
960            // Timeout errors
961            CoreError::Timeout { .. } => {
962                Error::Client(ClientError::Timeout {
963                    timeout: std::time::Duration::from_secs(30), // Default
964                })
965            }
966
967            // Resource exhaustion
968            CoreError::ResourceExhausted { resource, .. } => {
969                Error::Worker(WorkerError::ResourceExhausted { resource })
970            }
971
972            // Invalid commands/events
973            CoreError::InvalidCommand { reason, .. } => {
974                Error::Workflow(WorkflowError::InvalidState(reason))
975            }
976            CoreError::InvalidEvent { reason, .. } => Error::Workflow(WorkflowError::EventError {
977                event: "unknown".to_string(),
978                reason,
979            }),
980
981            // Internal errors
982            CoreError::Internal(msg) => Error::Other(msg),
983            CoreError::CacheError(msg) => Error::Other(msg),
984            CoreError::StateMachineError(msg) => Error::Workflow(WorkflowError::InvalidState(msg)),
985
986            // Context wrapper
987            CoreError::WithContext {
988                context, source, ..
989            } => {
990                let sdk_error: Error = (*source).into();
991                Error::Other(format!("{}: {}", context, sdk_error))
992            }
993
994            // Passthrough
995            CoreError::Other(err) => Error::Other(err.to_string()),
996
997            // Any variant sdk-core adds later.
998            other => Error::Other(other.to_string()),
999        }
1000    }
1001}
1002
1003impl From<serde_json::Error> for Error {
1004    fn from(err: serde_json::Error) -> Self {
1005        Error::Serialization(err.to_string())
1006    }
1007}
1008
1009impl From<anyhow::Error> for Error {
1010    fn from(err: anyhow::Error) -> Self {
1011        Error::Other(err.to_string())
1012    }
1013}
1014
1015// ============================================================================
1016// Error Classification
1017// ============================================================================
1018
1019impl Error {
1020    /// Whether this is the workflow suspension signal rather than a real error.
1021    ///
1022    /// Suspension is control flow: `ctx.execute_task`, `ctx.execute` and timers
1023    /// return [`WorkflowError::Suspended`] to hand control back to the runtime
1024    /// so it can schedule work and replay the workflow later. Combinators that
1025    /// inspect errors (sagas, `select`, retry wrappers) must propagate it
1026    /// unchanged and never treat it as a failed step.
1027    pub fn is_suspend(&self) -> bool {
1028        matches!(self, Error::Workflow(WorkflowError::Suspended { .. }))
1029    }
1030
1031    /// Whether this error is transient and may succeed on retry.
1032    ///
1033    /// Examples are connection failures, timeouts, 5xx and 429 server
1034    /// responses, and task failures not marked non-retryable.
1035    ///
1036    /// # Example
1037    ///
1038    /// ```rust
1039    /// use orcher_sdk::error::{ClientError, Error};
1040    ///
1041    /// let error = Error::Client(ClientError::server_error(503, "unavailable"));
1042    /// assert!(error.is_retryable());
1043    ///
1044    /// let error = Error::Client(ClientError::server_error(400, "bad request"));
1045    /// assert!(!error.is_retryable());
1046    /// ```
1047    pub fn is_retryable(&self) -> bool {
1048        match self {
1049            // Client errors - connection and timeout are retryable
1050            Error::Client(ClientError::ConnectionFailed { .. }) => true,
1051            Error::Client(ClientError::Timeout { .. }) => true,
1052            Error::Client(ClientError::RequestFailed(_)) => true,
1053            Error::Client(ClientError::ServerError { status, .. }) => {
1054                // 5xx are retryable and 4xx are not, except 429 (gRPC
1055                // RESOURCE_EXHAUSTED), which asks the caller to back off rather
1056                // than rejecting the request for good.
1057                *status == 429 || (*status >= 500 && *status < 600)
1058            }
1059
1060            // Service errors
1061            Error::Worker(WorkerError::PollingError(_)) => true,
1062            Error::Worker(WorkerError::ConnectionFailed { .. }) => true,
1063            Error::Worker(WorkerError::ResourceExhausted { .. }) => true,
1064
1065            // Task errors - execution failures and timeouts are retryable
1066            Error::Task(TaskError::ExecutionFailed(_)) => true,
1067            Error::Task(TaskError::Timeout { .. }) => true,
1068            Error::Task(TaskError::HeartbeatTimeout { .. }) => true,
1069            Error::Task(TaskError::Application { non_retryable, .. }) => !non_retryable,
1070
1071            // I/O errors are generally retryable
1072            Error::Io(_) => true,
1073
1074            // Most other errors are not retryable
1075            _ => false,
1076        }
1077    }
1078
1079    /// Whether this error is permanent, so retrying cannot fix it.
1080    ///
1081    /// Examples are invalid configuration, authentication failures,
1082    /// non-determinism and 4xx server responses other than 429.
1083    ///
1084    /// # Example
1085    ///
1086    /// ```rust
1087    /// use orcher_sdk::error::{Error, TaskError};
1088    ///
1089    /// let error: Error = TaskError::non_retryable("CardDeclined", "card declined").into();
1090    /// assert!(error.is_permanent());
1091    ///
1092    /// let error: Error = TaskError::application("Throttled", "slow down").into();
1093    /// assert!(!error.is_permanent());
1094    /// ```
1095    pub fn is_permanent(&self) -> bool {
1096        match self {
1097            // Configuration errors are permanent
1098            Error::Configuration(_) => true,
1099
1100            // Workflow state errors are permanent
1101            Error::Workflow(WorkflowError::NonDeterministic(_)) => true,
1102            Error::Workflow(WorkflowError::VersionMismatch { .. }) => true,
1103            Error::Workflow(WorkflowError::InvalidState(_)) => true,
1104
1105            // Task configuration errors are permanent
1106            Error::Task(TaskError::InvalidInput(_)) => true,
1107            Error::Task(TaskError::InvalidConfiguration(_)) => true,
1108            Error::Task(TaskError::RetryLimitExceeded { .. }) => true,
1109            Error::Task(TaskError::Application { non_retryable, .. }) => *non_retryable,
1110
1111            // Client authentication/authorization errors are permanent
1112            Error::Client(ClientError::AuthenticationFailed(_)) => true,
1113            Error::Client(ClientError::AuthorizationFailed(_)) => true,
1114            Error::Client(ClientError::InvalidUrl(_)) => true,
1115            Error::Client(ClientError::InvalidInput(_)) => true,
1116            Error::Client(ClientError::WorkflowAlreadyExists { .. }) => true,
1117
1118            // Service configuration errors are permanent
1119            Error::Worker(WorkerError::InvalidConfiguration(_)) => true,
1120            Error::Worker(WorkerError::HandlerNotFound { .. }) => true,
1121
1122            // Client 4xx errors are permanent (except 429)
1123            Error::Client(ClientError::ServerError { status, .. }) => {
1124                *status >= 400 && *status < 500 && *status != 429
1125            }
1126
1127            _ => false,
1128        }
1129    }
1130
1131    /// Wrap this error with a context message.
1132    ///
1133    /// The result is an [`Error::Other`] whose message is `"{context}: {self}"`,
1134    /// so the original variant is not preserved for matching.
1135    ///
1136    /// # Example
1137    ///
1138    /// ```rust
1139    /// use orcher_sdk::error::{Error, TaskError};
1140    ///
1141    /// let error: Error = TaskError::execution_failed("card declined").into();
1142    /// let error = error.with_context("Failed to execute payment task");
1143    /// assert!(error.to_string().starts_with("Failed to execute payment task: "));
1144    /// ```
1145    pub fn with_context(self, context: impl Into<String>) -> Self {
1146        Error::Other(format!("{}: {}", context.into(), self))
1147    }
1148
1149    /// The [`ErrorCode`] for this error, the same in every SDK.
1150    pub fn code(&self) -> ErrorCode {
1151        match self {
1152            Error::Workflow(w) => match w {
1153                WorkflowError::TaskFailed { .. } => ErrorCode::TaskFailed,
1154                WorkflowError::TimerFailed { .. } => ErrorCode::WorkflowFailed,
1155                WorkflowError::ChildWorkflowFailed { .. } => ErrorCode::WorkflowFailed,
1156                WorkflowError::StateError(_) => ErrorCode::WorkflowStateError,
1157                WorkflowError::Canceled => ErrorCode::WorkflowCanceled,
1158                WorkflowError::Timeout { .. } => ErrorCode::WorkflowTimeout,
1159                WorkflowError::Panic(_) => ErrorCode::WorkflowFailed,
1160                WorkflowError::NonDeterministic(_) => ErrorCode::WorkflowNonDeterministic,
1161                WorkflowError::EventError { .. } => ErrorCode::WorkflowFailed,
1162                WorkflowError::QueryError { .. } => ErrorCode::WorkflowFailed,
1163                WorkflowError::CompensationFailed { .. } => ErrorCode::WorkflowStateError,
1164                WorkflowError::InvalidState(_) => ErrorCode::WorkflowStateError,
1165                WorkflowError::NotFound { .. } => ErrorCode::WorkflowNotFound,
1166                WorkflowError::ReplayError(_) => ErrorCode::WorkflowReplayError,
1167                WorkflowError::RestartFreshError(_) => ErrorCode::WorkflowFailed,
1168                WorkflowError::VersionMismatch { .. } => ErrorCode::WorkflowVersionMismatch,
1169                WorkflowError::Suspended { .. } => ErrorCode::Internal, // not a real error
1170            },
1171            Error::Task(t) => match t {
1172                TaskError::ExecutionFailed(_) => ErrorCode::TaskFailed,
1173                TaskError::Timeout { .. } => ErrorCode::TaskTimeout,
1174                TaskError::Canceled => ErrorCode::TaskCanceled,
1175                TaskError::HeartbeatFailed(_) => ErrorCode::TaskHeartbeatFailed,
1176                TaskError::HeartbeatTimeout { .. } => ErrorCode::TaskHeartbeatFailed,
1177                TaskError::NotFound { .. } => ErrorCode::TaskNotFound,
1178                TaskError::AlreadyCompleted { .. } => ErrorCode::TaskFailed,
1179                TaskError::Panic(_) => ErrorCode::TaskFailed,
1180                TaskError::RetryLimitExceeded { .. } => ErrorCode::TaskRetryLimitExceeded,
1181                TaskError::InvalidInput(_) => ErrorCode::TaskInvalidInput,
1182                TaskError::InvalidConfiguration(_) => ErrorCode::InvalidConfiguration,
1183                TaskError::Application { .. } => ErrorCode::TaskFailed,
1184            },
1185            Error::Client(c) => match c {
1186                ClientError::ConnectionFailed { .. } => ErrorCode::ConnectionFailed,
1187                ClientError::RequestFailed(_) => ErrorCode::ServerError,
1188                ClientError::Timeout { .. } => ErrorCode::RequestTimeout,
1189                ClientError::InvalidUrl(_) => ErrorCode::InvalidRequest,
1190                ClientError::AuthenticationFailed(_) => ErrorCode::AuthenticationFailed,
1191                ClientError::AuthorizationFailed(_) => ErrorCode::AuthorizationFailed,
1192                ClientError::WorkflowNotFound { .. } => ErrorCode::WorkflowNotFound,
1193                ClientError::WorkflowAlreadyExists { .. } => ErrorCode::WorkflowAlreadyExists,
1194                ClientError::InvalidInput(_) => ErrorCode::InvalidRequest,
1195                ClientError::InvalidResponse(_) => ErrorCode::ServerError,
1196                ClientError::ServerError { .. } => ErrorCode::ServerError,
1197                ClientError::Serialization(_) => ErrorCode::SerializationError,
1198                ClientError::Deserialization(_) => ErrorCode::SerializationError,
1199            },
1200            Error::Worker(s) => match s {
1201                WorkerError::InvalidConfiguration(_) => ErrorCode::InvalidConfiguration,
1202                WorkerError::StartupFailed(_) => ErrorCode::StartupFailed,
1203                WorkerError::AlreadyRunning => ErrorCode::InvalidConfiguration,
1204                WorkerError::NotRunning => ErrorCode::InvalidConfiguration,
1205                WorkerError::ConnectionFailed { .. } => ErrorCode::ConnectionFailed,
1206                WorkerError::PollingError(_) => ErrorCode::PollingError,
1207                WorkerError::RegistrationError(_) => ErrorCode::StartupFailed,
1208                WorkerError::HandlerNotFound { .. } => ErrorCode::HandlerNotFound,
1209                WorkerError::HandlerExecutionError(_) => ErrorCode::Internal,
1210                WorkerError::ShutdownError(_) => ErrorCode::ShutdownError,
1211                WorkerError::ShutdownTimeout { .. } => ErrorCode::ShutdownError,
1212                WorkerError::ResourceExhausted { .. } => ErrorCode::ResourceExhausted,
1213                WorkerError::TaskQueueNotFound { .. } => ErrorCode::HandlerNotFound,
1214            },
1215            Error::Actor(_) => ErrorCode::Internal,
1216            Error::Network(_) => ErrorCode::NetworkError,
1217            Error::Configuration(_) => ErrorCode::InvalidConfiguration,
1218            Error::Serialization(_) => ErrorCode::SerializationError,
1219            Error::Timeout(_) => ErrorCode::RequestTimeout,
1220            Error::Io(_) => ErrorCode::IoError,
1221            Error::Other(_) => ErrorCode::Internal,
1222        }
1223    }
1224
1225    /// The [`Severity`] of this error, the same in every SDK.
1226    pub fn severity(&self) -> Severity {
1227        match self {
1228            // Critical: service cannot function
1229            Error::Worker(WorkerError::StartupFailed(_)) => Severity::Critical,
1230            Error::Worker(WorkerError::ConnectionFailed { .. }) => Severity::Critical,
1231            Error::Configuration(_) => Severity::Critical,
1232
1233            // High: significant impact, needs attention
1234            Error::Workflow(WorkflowError::NonDeterministic(_)) => Severity::High,
1235            Error::Workflow(WorkflowError::VersionMismatch { .. }) => Severity::High,
1236            Error::Workflow(WorkflowError::Panic(_)) => Severity::High,
1237            Error::Task(TaskError::Panic(_)) => Severity::High,
1238            Error::Task(TaskError::RetryLimitExceeded { .. }) => Severity::High,
1239            Error::Client(ClientError::AuthenticationFailed(_)) => Severity::High,
1240            Error::Client(ClientError::AuthorizationFailed(_)) => Severity::High,
1241            Error::Worker(WorkerError::ShutdownError(_)) => Severity::High,
1242            Error::Worker(WorkerError::ShutdownTimeout { .. }) => Severity::High,
1243            Error::Worker(WorkerError::ResourceExhausted { .. }) => Severity::High,
1244
1245            // Medium: degraded functionality
1246            Error::Workflow(WorkflowError::TaskFailed { .. }) => Severity::Medium,
1247            Error::Workflow(WorkflowError::ChildWorkflowFailed { .. }) => Severity::Medium,
1248            Error::Workflow(WorkflowError::Timeout { .. }) => Severity::Medium,
1249            Error::Task(TaskError::ExecutionFailed(_)) => Severity::Medium,
1250            Error::Task(TaskError::Timeout { .. }) => Severity::Medium,
1251            Error::Task(TaskError::HeartbeatFailed(_)) => Severity::Medium,
1252            Error::Task(TaskError::HeartbeatTimeout { .. }) => Severity::Medium,
1253            Error::Client(ClientError::ConnectionFailed { .. }) => Severity::Medium,
1254            Error::Client(ClientError::Timeout { .. }) => Severity::Medium,
1255            Error::Client(ClientError::ServerError { .. }) => Severity::Medium,
1256            Error::Worker(WorkerError::PollingError(_)) => Severity::Medium,
1257            Error::Network(_) => Severity::Medium,
1258            Error::Io(_) => Severity::Medium,
1259
1260            // Low: expected or informational
1261            Error::Workflow(WorkflowError::Canceled) => Severity::Low,
1262            Error::Workflow(WorkflowError::Suspended { .. }) => Severity::Low,
1263            Error::Workflow(WorkflowError::NotFound { .. }) => Severity::Low,
1264            Error::Task(TaskError::Canceled) => Severity::Low,
1265            Error::Task(TaskError::NotFound { .. }) => Severity::Low,
1266            Error::Client(ClientError::WorkflowNotFound { .. }) => Severity::Low,
1267            Error::Client(ClientError::WorkflowAlreadyExists { .. }) => Severity::Low,
1268            Error::Serialization(_) => Severity::Low,
1269
1270            // Default to Medium for uncovered cases
1271            _ => Severity::Medium,
1272        }
1273    }
1274}
1275
1276// ============================================================================
1277// Convenience Constructors
1278// ============================================================================
1279
1280impl WorkflowError {
1281    /// Create a task failed error
1282    pub fn task_failed(
1283        task_type: impl Into<String>,
1284        attempts: u32,
1285        reason: impl Into<String>,
1286    ) -> Self {
1287        Self::TaskFailed {
1288            task_type: task_type.into(),
1289            attempts,
1290            reason: reason.into(),
1291            error_type: String::new(),
1292            code: TaskFailureCode::Unspecified,
1293        }
1294    }
1295
1296    /// Sets a [`TaskFailed`](Self::TaskFailed) error's type and category; any
1297    /// other error is returned as it is.
1298    pub fn with_failure_type(self, error_type: impl Into<String>, code: TaskFailureCode) -> Self {
1299        match self {
1300            Self::TaskFailed {
1301                task_type,
1302                attempts,
1303                reason,
1304                ..
1305            } => Self::TaskFailed {
1306                task_type,
1307                attempts,
1308                reason,
1309                error_type: error_type.into(),
1310                code,
1311            },
1312            other => other,
1313        }
1314    }
1315
1316    /// The category of a [`TaskFailed`](Self::TaskFailed) error, or `None` for
1317    /// any other error.
1318    pub fn task_failure_code(&self) -> Option<TaskFailureCode> {
1319        match self {
1320            Self::TaskFailed { code, .. } => Some(*code),
1321            _ => None,
1322        }
1323    }
1324
1325    /// The type of a [`TaskFailed`](Self::TaskFailed) error, or `None` for any
1326    /// other error. Empty for a failure of no particular type.
1327    pub fn task_failure_type(&self) -> Option<&str> {
1328        match self {
1329            Self::TaskFailed { error_type, .. } => Some(error_type),
1330            _ => None,
1331        }
1332    }
1333
1334    /// Whether this is a [`TaskFailed`](Self::TaskFailed) error for a task that
1335    /// was cancelled: its category is [`TaskFailureCode::Cancelled`], or its
1336    /// type is `Cancelled`, which is how an engine that does not categorize
1337    /// failures records a cancellation.
1338    pub fn is_task_cancelled(&self) -> bool {
1339        match self {
1340            Self::TaskFailed {
1341                error_type, code, ..
1342            } => code.is_cancelled() || error_type == CANCELLED_FAILURE_TYPE,
1343            _ => false,
1344        }
1345    }
1346
1347    /// Create a timer failed error
1348    pub fn timer_failed(timer_id: impl Into<String>, reason: impl Into<String>) -> Self {
1349        Self::TimerFailed {
1350            timer_id: timer_id.into(),
1351            reason: reason.into(),
1352        }
1353    }
1354
1355    /// Create a child workflow failed error
1356    pub fn child_workflow_failed(
1357        workflow_type: impl Into<String>,
1358        workflow_id: impl Into<String>,
1359        reason: impl Into<String>,
1360    ) -> Self {
1361        Self::ChildWorkflowFailed {
1362            workflow_type: workflow_type.into(),
1363            workflow_id: workflow_id.into(),
1364            reason: reason.into(),
1365        }
1366    }
1367
1368    /// Create an event error
1369    pub fn event_error(event: impl Into<String>, reason: impl Into<String>) -> Self {
1370        Self::EventError {
1371            event: event.into(),
1372            reason: reason.into(),
1373        }
1374    }
1375
1376    /// Create a query error
1377    pub fn query_error(query: impl Into<String>, reason: impl Into<String>) -> Self {
1378        Self::QueryError {
1379            query: query.into(),
1380            reason: reason.into(),
1381        }
1382    }
1383
1384    /// Create a not found error
1385    pub fn not_found(workflow_id: impl Into<String>) -> Self {
1386        Self::NotFound {
1387            workflow_id: workflow_id.into(),
1388        }
1389    }
1390
1391    /// Create a timeout error
1392    pub fn timeout(timeout: std::time::Duration) -> Self {
1393        Self::Timeout { timeout }
1394    }
1395
1396    /// Create a non-deterministic error
1397    pub fn non_deterministic(reason: impl Into<String>) -> Self {
1398        Self::NonDeterministic(reason.into())
1399    }
1400
1401    /// Create a version mismatch error
1402    pub fn version_mismatch(expected: impl Into<String>, actual: impl Into<String>) -> Self {
1403        Self::VersionMismatch {
1404            expected: expected.into(),
1405            actual: actual.into(),
1406        }
1407    }
1408
1409    /// Create the suspension signal: the workflow waits on these operations
1410    pub fn suspended(reason: impl Into<String>, pending_operations: Vec<String>) -> Self {
1411        Self::Suspended {
1412            reason: reason.into(),
1413            pending_operations,
1414        }
1415    }
1416}
1417
1418impl TaskError {
1419    /// Create an execution failed error
1420    pub fn execution_failed(reason: impl Into<String>) -> Self {
1421        Self::ExecutionFailed(reason.into())
1422    }
1423
1424    /// Create a heartbeat failed error
1425    pub fn heartbeat_failed(reason: impl Into<String>) -> Self {
1426        Self::HeartbeatFailed(reason.into())
1427    }
1428
1429    /// Create a timeout error
1430    pub fn timeout(timeout: std::time::Duration) -> Self {
1431        Self::Timeout { timeout }
1432    }
1433
1434    /// Create a not found error
1435    pub fn not_found(task_id: impl Into<String>) -> Self {
1436        Self::NotFound {
1437            task_id: task_id.into(),
1438        }
1439    }
1440
1441    /// Create a retry limit exceeded error
1442    pub fn retry_limit_exceeded(attempts: u32) -> Self {
1443        Self::RetryLimitExceeded { attempts }
1444    }
1445
1446    /// Create a heartbeat timeout error
1447    pub fn heartbeat_timeout(timeout: std::time::Duration) -> Self {
1448        Self::HeartbeatTimeout { timeout }
1449    }
1450
1451    /// Create a task already completed error
1452    pub fn already_completed(task_id: impl Into<String>) -> Self {
1453        Self::AlreadyCompleted {
1454            task_id: task_id.into(),
1455        }
1456    }
1457
1458    /// Create an invalid input error
1459    pub fn invalid_input(reason: impl Into<String>) -> Self {
1460        Self::InvalidInput(reason.into())
1461    }
1462
1463    /// A failure of type `error_type`, retried unless the task's retry policy
1464    /// lists that type as non-retryable.
1465    pub fn application(error_type: impl Into<String>, message: impl Into<String>) -> Self {
1466        Self::Application {
1467            error_type: error_type.into(),
1468            message: message.into(),
1469            non_retryable: false,
1470        }
1471    }
1472
1473    /// A failure of type `error_type` that is never retried, whatever the
1474    /// task's retry policy allows.
1475    ///
1476    /// Returned by workflow code, it fails the workflow the same way: the
1477    /// workflow is not retried, whatever its retry policy allows. Any other
1478    /// error a workflow returns is retried as its policy says.
1479    pub fn non_retryable(error_type: impl Into<String>, message: impl Into<String>) -> Self {
1480        Self::Application {
1481            error_type: error_type.into(),
1482            message: message.into(),
1483            non_retryable: true,
1484        }
1485    }
1486}
1487
1488impl ClientError {
1489    /// Create a connection failed error
1490    pub fn connection_failed(url: impl Into<String>, reason: impl Into<String>) -> Self {
1491        Self::ConnectionFailed {
1492            url: url.into(),
1493            reason: reason.into(),
1494        }
1495    }
1496
1497    /// Create a server error
1498    pub fn server_error(status: u16, message: impl Into<String>) -> Self {
1499        Self::ServerError {
1500            status,
1501            message: message.into(),
1502        }
1503    }
1504
1505    /// Create a timeout error
1506    pub fn timeout(timeout: std::time::Duration) -> Self {
1507        Self::Timeout { timeout }
1508    }
1509
1510    /// Create a workflow not found error
1511    pub fn workflow_not_found(workflow_id: impl Into<String>) -> Self {
1512        Self::WorkflowNotFound {
1513            workflow_id: workflow_id.into(),
1514        }
1515    }
1516
1517    /// Create a workflow already exists error
1518    pub fn workflow_already_exists(workflow_id: impl Into<String>) -> Self {
1519        Self::WorkflowAlreadyExists {
1520            workflow_id: workflow_id.into(),
1521            run_id: None,
1522        }
1523    }
1524
1525    /// Create a workflow already exists error naming the run in the way
1526    pub fn workflow_already_exists_with_run(
1527        workflow_id: impl Into<String>,
1528        run_id: impl Into<String>,
1529    ) -> Self {
1530        Self::WorkflowAlreadyExists {
1531            workflow_id: workflow_id.into(),
1532            run_id: Some(run_id.into()),
1533        }
1534    }
1535
1536    /// Create a request failed error
1537    pub fn request_failed(reason: impl Into<String>) -> Self {
1538        Self::RequestFailed(reason.into())
1539    }
1540
1541    /// Create a serialization error
1542    pub fn serialization(reason: impl Into<String>) -> Self {
1543        Self::Serialization(reason.into())
1544    }
1545
1546    /// Create a deserialization error
1547    pub fn deserialization(reason: impl Into<String>) -> Self {
1548        Self::Deserialization(reason.into())
1549    }
1550}
1551
1552impl WorkerError {
1553    /// Create a connection failed error
1554    pub fn connection_failed(url: impl Into<String>, reason: impl Into<String>) -> Self {
1555        Self::ConnectionFailed {
1556            url: url.into(),
1557            reason: reason.into(),
1558        }
1559    }
1560
1561    /// Create a handler not found error
1562    pub fn handler_not_found(handler_type: impl Into<String>, name: impl Into<String>) -> Self {
1563        Self::HandlerNotFound {
1564            handler_type: handler_type.into(),
1565            name: name.into(),
1566        }
1567    }
1568
1569    /// Create an invalid configuration error
1570    pub fn invalid_configuration(reason: impl Into<String>) -> Self {
1571        Self::InvalidConfiguration(reason.into())
1572    }
1573
1574    /// Create a startup failed error
1575    pub fn startup_failed(reason: impl Into<String>) -> Self {
1576        Self::StartupFailed(reason.into())
1577    }
1578
1579    /// Create a polling error
1580    pub fn polling_error(reason: impl Into<String>) -> Self {
1581        Self::PollingError(reason.into())
1582    }
1583
1584    /// Create a resource exhausted error
1585    pub fn resource_exhausted(resource: impl Into<String>) -> Self {
1586        Self::ResourceExhausted {
1587            resource: resource.into(),
1588        }
1589    }
1590
1591    /// Create a shutdown timeout error
1592    pub fn shutdown_timeout(timeout: std::time::Duration) -> Self {
1593        Self::ShutdownTimeout { timeout }
1594    }
1595
1596    /// Create a task queue not found error
1597    pub fn task_queue_not_found(queue: impl Into<String>) -> Self {
1598        Self::TaskQueueNotFound {
1599            queue: queue.into(),
1600        }
1601    }
1602}
1603
1604#[cfg(test)]
1605mod tests {
1606    use super::*;
1607
1608    #[test]
1609    fn test_is_suspend_only_true_for_suspended() {
1610        let suspended = Error::Workflow(WorkflowError::Suspended {
1611            reason: "Task 'charge' scheduled for execution".to_string(),
1612            pending_operations: vec!["charge_0".to_string()],
1613        });
1614        assert!(suspended.is_suspend());
1615
1616        // A real task failure is not a suspend. This distinction keeps sagas
1617        // from compensating healthy workflows.
1618        let failed = Error::Workflow(WorkflowError::task_failed("charge", 3, "declined"));
1619        assert!(!failed.is_suspend());
1620
1621        let other = Error::Serialization("bad json".to_string());
1622        assert!(!other.is_suspend());
1623    }
1624
1625    /// A task failure carries the type and category it is given; other errors
1626    /// have neither.
1627    #[test]
1628    fn a_task_failure_carries_its_type_and_category() {
1629        let plain = WorkflowError::task_failed("charge", 1, "declined");
1630        assert_eq!(
1631            plain.task_failure_code(),
1632            Some(TaskFailureCode::Unspecified)
1633        );
1634        assert_eq!(plain.task_failure_type(), Some(""));
1635        assert!(!plain.is_task_cancelled());
1636
1637        let cancelled = plain
1638            .clone()
1639            .with_failure_type("Cancelled", TaskFailureCode::Cancelled);
1640        assert!(cancelled.is_task_cancelled());
1641        assert_eq!(cancelled.task_failure_type(), Some("Cancelled"));
1642
1643        // Either the category or the type alone marks a cancellation.
1644        assert!(plain
1645            .clone()
1646            .with_failure_type("", TaskFailureCode::Cancelled)
1647            .is_task_cancelled());
1648        assert!(plain
1649            .clone()
1650            .with_failure_type("Cancelled", TaskFailureCode::Application)
1651            .is_task_cancelled());
1652        assert!(!plain
1653            .with_failure_type("CardDeclined", TaskFailureCode::Application)
1654            .is_task_cancelled());
1655
1656        let other = WorkflowError::timer_failed("t", "boom")
1657            .with_failure_type("Cancelled", TaskFailureCode::Cancelled);
1658        assert_eq!(other.task_failure_code(), None);
1659        assert_eq!(other.task_failure_type(), None);
1660        assert!(!other.is_task_cancelled());
1661    }
1662
1663    #[test]
1664    fn test_workflow_error_display() {
1665        let err = WorkflowError::task_failed("ProcessPayment", 3, "Network timeout");
1666        assert_eq!(
1667            err.to_string(),
1668            "Task 'ProcessPayment' failed after 3 attempts: Network timeout"
1669        );
1670    }
1671
1672    #[test]
1673    fn test_task_error_display() {
1674        let err = TaskError::execution_failed("Database connection lost");
1675        assert_eq!(
1676            err.to_string(),
1677            "Task execution failed: Database connection lost"
1678        );
1679    }
1680
1681    #[test]
1682    fn test_client_error_display() {
1683        let err = ClientError::server_error(500, "Internal server error");
1684        assert_eq!(
1685            err.to_string(),
1686            "Server error (status 500): Internal server error"
1687        );
1688    }
1689
1690    #[test]
1691    fn test_service_error_display() {
1692        let err = WorkerError::handler_not_found("workflow", "OrderWorkflow");
1693        assert_eq!(
1694            err.to_string(),
1695            "No handler registered for 'workflow' with name 'OrderWorkflow'"
1696        );
1697    }
1698
1699    #[test]
1700    fn test_error_conversion() {
1701        let workflow_err = WorkflowError::Canceled;
1702        let err: Error = workflow_err.into();
1703        assert!(matches!(err, Error::Workflow(_)));
1704    }
1705
1706    #[test]
1707    fn test_result_type() {
1708        let ok_result: Result<i32> = Ok(42);
1709        assert!(ok_result.is_ok());
1710
1711        let err_result: Result<i32> = Err(Error::Configuration("Invalid config".to_string()));
1712        assert!(err_result.is_err());
1713    }
1714
1715    #[test]
1716    fn test_error_is_retryable() {
1717        // Retryable errors
1718        let err = Error::Client(ClientError::ConnectionFailed {
1719            url: "http://test".to_string(),
1720            reason: "timeout".to_string(),
1721        });
1722        assert!(err.is_retryable());
1723
1724        let err = Error::Client(ClientError::Timeout {
1725            timeout: std::time::Duration::from_secs(30),
1726        });
1727        assert!(err.is_retryable());
1728
1729        let err = Error::Client(ClientError::ServerError {
1730            status: 503,
1731            message: "Service unavailable".to_string(),
1732        });
1733        assert!(err.is_retryable());
1734
1735        // Non-retryable errors
1736        let err = Error::Configuration("Invalid config".to_string());
1737        assert!(!err.is_retryable());
1738
1739        let err = Error::Client(ClientError::ServerError {
1740            status: 400,
1741            message: "Bad request".to_string(),
1742        });
1743        assert!(!err.is_retryable());
1744    }
1745
1746    #[test]
1747    fn test_error_is_permanent() {
1748        // Permanent errors
1749        let err = Error::Configuration("Invalid config".to_string());
1750        assert!(err.is_permanent());
1751
1752        let err = Error::Client(ClientError::AuthenticationFailed(
1753            "Invalid token".to_string(),
1754        ));
1755        assert!(err.is_permanent());
1756
1757        let err = Error::Workflow(WorkflowError::NonDeterministic(
1758            "Replay mismatch".to_string(),
1759        ));
1760        assert!(err.is_permanent());
1761
1762        let err = Error::Client(ClientError::ServerError {
1763            status: 404,
1764            message: "Not found".to_string(),
1765        });
1766        assert!(err.is_permanent());
1767
1768        // Non-permanent errors
1769        let err = Error::Client(ClientError::Timeout {
1770            timeout: std::time::Duration::from_secs(30),
1771        });
1772        assert!(!err.is_permanent());
1773    }
1774
1775    #[test]
1776    fn test_error_with_context() {
1777        let err = Error::Configuration("Invalid port".to_string());
1778        let err_with_ctx = err.with_context("Failed to start server");
1779        assert!(err_with_ctx.to_string().contains("Failed to start server"));
1780        assert!(err_with_ctx.to_string().contains("Invalid port"));
1781    }
1782
1783    #[test]
1784    fn test_workflow_error_constructors() {
1785        let err = WorkflowError::not_found("wf-123");
1786        assert!(matches!(err, WorkflowError::NotFound { .. }));
1787
1788        let err = WorkflowError::timeout(std::time::Duration::from_secs(30));
1789        assert!(matches!(err, WorkflowError::Timeout { .. }));
1790
1791        let err = WorkflowError::non_deterministic("mismatch");
1792        assert!(matches!(err, WorkflowError::NonDeterministic(_)));
1793    }
1794
1795    #[test]
1796    fn test_task_error_constructors() {
1797        let err = TaskError::not_found("task-456");
1798        assert!(matches!(err, TaskError::NotFound { .. }));
1799
1800        let err = TaskError::timeout(std::time::Duration::from_secs(10));
1801        assert!(matches!(err, TaskError::Timeout { .. }));
1802
1803        let err = TaskError::retry_limit_exceeded(5);
1804        assert!(matches!(err, TaskError::RetryLimitExceeded { attempts: 5 }));
1805    }
1806
1807    /// A refused start names the run holding the id; losing it on the way up
1808    /// leaves a caller that meant to start the workflow once unable to reach
1809    /// the run already doing the work.
1810    #[test]
1811    fn a_refused_start_keeps_the_run_in_the_way() {
1812        let err: Error =
1813            orcher_sdk_core::error::Error::workflow_already_exists_with_run("order-7", "run-7")
1814                .into();
1815        assert_eq!(err.code(), ErrorCode::WorkflowAlreadyExists);
1816        match err {
1817            Error::Client(ClientError::WorkflowAlreadyExists {
1818                workflow_id,
1819                run_id,
1820            }) => {
1821                assert_eq!(workflow_id, "order-7");
1822                assert_eq!(run_id.as_deref(), Some("run-7"));
1823            }
1824            other => panic!("expected WorkflowAlreadyExists, got {other:?}"),
1825        }
1826    }
1827
1828    #[test]
1829    fn test_client_error_constructors() {
1830        let err = ClientError::workflow_not_found("wf-789");
1831        assert!(matches!(err, ClientError::WorkflowNotFound { .. }));
1832
1833        let err = ClientError::workflow_already_exists("wf-789");
1834        assert!(matches!(err, ClientError::WorkflowAlreadyExists { .. }));
1835
1836        let err = ClientError::request_failed("network error");
1837        assert!(matches!(err, ClientError::RequestFailed(_)));
1838    }
1839
1840    #[test]
1841    fn test_service_error_constructors() {
1842        let err = WorkerError::polling_error("connection lost");
1843        assert!(matches!(err, WorkerError::PollingError(_)));
1844
1845        let err = WorkerError::resource_exhausted("memory");
1846        assert!(matches!(err, WorkerError::ResourceExhausted { .. }));
1847
1848        let err = WorkerError::task_queue_not_found("orders");
1849        assert!(matches!(err, WorkerError::TaskQueueNotFound { .. }));
1850    }
1851
1852    #[test]
1853    fn test_sdk_core_error_conversion() {
1854        use orcher_sdk_core::error::Error as CoreError;
1855
1856        // Workflow errors
1857        let core_err = CoreError::workflow_not_found("wf-123");
1858        let sdk_err: Error = core_err.into();
1859        assert!(matches!(
1860            sdk_err,
1861            Error::Workflow(WorkflowError::NotFound { .. })
1862        ));
1863
1864        // Task errors
1865        let core_err = CoreError::task_execution_failed("task-456", "failed");
1866        let sdk_err: Error = core_err.into();
1867        assert!(matches!(
1868            sdk_err,
1869            Error::Task(TaskError::ExecutionFailed(_))
1870        ));
1871
1872        // Connection errors
1873        let core_err = CoreError::connection("timeout");
1874        let sdk_err: Error = core_err.into();
1875        assert!(matches!(
1876            sdk_err,
1877            Error::Client(ClientError::ConnectionFailed { .. })
1878        ));
1879
1880        // Determinism errors
1881        let core_err = CoreError::determinism_violation("replay mismatch");
1882        let sdk_err: Error = core_err.into();
1883        assert!(matches!(
1884            sdk_err,
1885            Error::Workflow(WorkflowError::NonDeterministic(_))
1886        ));
1887    }
1888}
1889
1890#[cfg(test)]
1891mod typed_client_error_tests {
1892    use super::*;
1893    use orcher_sdk_core::error::Error as CoreError;
1894
1895    /// A missing workflow keeps its type, so a caller can tell "this workflow
1896    /// does not exist" from "the server is down".
1897    #[test]
1898    fn a_missing_workflow_maps_to_a_typed_not_found() {
1899        let err: Error = CoreError::workflow_not_found("wf-1").into();
1900
1901        assert!(
1902            matches!(err, Error::Workflow(WorkflowError::NotFound { .. })),
1903            "expected a typed NotFound, got {err:?}"
1904        );
1905    }
1906
1907    /// A workflow that will never exist must not be retried, or a retry loop
1908    /// keeps hitting the server for nothing.
1909    #[test]
1910    fn a_missing_workflow_is_not_retryable() {
1911        let err: Error = CoreError::workflow_not_found("wf-1").into();
1912
1913        assert!(!err.is_retryable(), "a missing workflow was retried");
1914    }
1915
1916    /// Transient gRPC codes map into the HTTP retryable range, so they are
1917    /// retried.
1918    #[test]
1919    fn transient_grpc_failures_are_retryable() {
1920        for code in [
1921            orcher_sdk_core::error::Code::Unavailable,
1922            orcher_sdk_core::error::Code::DeadlineExceeded,
1923            orcher_sdk_core::error::Code::ResourceExhausted,
1924        ] {
1925            let err: Error =
1926                CoreError::Status(orcher_sdk_core::error::Status::new(code, "boom")).into();
1927            assert!(
1928                err.is_retryable(),
1929                "{code:?} should be retryable but was classified permanent"
1930            );
1931        }
1932    }
1933
1934    /// Permanent gRPC codes are not retried.
1935    #[test]
1936    fn permanent_grpc_failures_are_not_retryable() {
1937        for code in [
1938            orcher_sdk_core::error::Code::NotFound,
1939            orcher_sdk_core::error::Code::InvalidArgument,
1940            orcher_sdk_core::error::Code::PermissionDenied,
1941            orcher_sdk_core::error::Code::Unauthenticated,
1942            orcher_sdk_core::error::Code::AlreadyExists,
1943        ] {
1944            let err: Error =
1945                CoreError::Status(orcher_sdk_core::error::Status::new(code, "nope")).into();
1946            assert!(
1947                !err.is_retryable(),
1948                "{code:?} should be permanent but was classified retryable"
1949            );
1950        }
1951    }
1952
1953    /// The caller sees an HTTP status, not a raw gRPC ordinal that looks like
1954    /// an HTTP code and is not one.
1955    #[test]
1956    fn grpc_status_is_translated_for_the_caller() {
1957        let err: Error = CoreError::Status(orcher_sdk_core::error::Status::new(
1958            orcher_sdk_core::error::Code::NotFound,
1959            "missing",
1960        ))
1961        .into();
1962        match err {
1963            Error::Client(ClientError::ServerError { status, .. }) => assert_eq!(status, 404),
1964            other => panic!("expected ServerError, got {other:?}"),
1965        }
1966    }
1967}