1pub type Result<T> = std::result::Result<T, Error>;
54
55pub(crate) const TASK_FAILED_SENTINEL_KEY: &str = "__orcher_task_failed__";
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
69#[non_exhaustive]
70pub enum ErrorCode {
71 WorkflowFailed,
74 WorkflowNotFound,
76 WorkflowAlreadyExists,
78 WorkflowCanceled,
80 WorkflowTimeout,
82 WorkflowNonDeterministic,
84 WorkflowStateError,
86 WorkflowVersionMismatch,
88 WorkflowReplayError,
90
91 TaskFailed,
94 TaskNotFound,
96 TaskTimeout,
98 TaskCanceled,
100 TaskHeartbeatFailed,
102 TaskRetryLimitExceeded,
104 TaskInvalidInput,
106
107 ConnectionFailed,
110 RequestTimeout,
112 AuthenticationFailed,
114 AuthorizationFailed,
116 ServerError,
118 InvalidRequest,
120
121 InvalidConfiguration,
124 StartupFailed,
126 ShutdownError,
128 HandlerNotFound,
130 ResourceExhausted,
132 PollingError,
134
135 SerializationError,
138 NetworkError,
140 IoError,
142 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
188pub enum Severity {
189 Low,
191 Medium,
193 High,
195 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#[derive(Debug, thiserror::Error)]
219#[non_exhaustive]
220pub enum Error {
221 #[error("Workflow error: {0}")]
223 Workflow(#[from] WorkflowError),
224
225 #[error("Task error: {0}")]
227 Task(#[from] TaskError),
228
229 #[error("Client error: {0}")]
231 Client(#[from] ClientError),
232
233 #[error("Worker error: {0}")]
235 Worker(#[from] WorkerError),
236
237 #[error("Actor error: {0}")]
239 Actor(String),
240
241 #[error("Network error: {0}")]
243 Network(String),
244
245 #[error("Configuration error: {0}")]
247 Configuration(String),
248
249 #[error("Serialization error: {0}")]
251 Serialization(String),
252
253 #[error("Timeout: {0}")]
255 Timeout(String),
256
257 #[error("I/O error: {0}")]
259 Io(#[from] std::io::Error),
260
261 #[error("{0}")]
263 Other(String),
264}
265
266const CANCELLED_FAILURE_TYPE: &str = "Cancelled";
268
269#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
275#[non_exhaustive]
276pub enum TaskFailureCode {
277 #[default]
280 Unspecified,
281 Application,
283 TimedOut,
285 Cancelled,
287 Terminated,
289 NonDeterminism,
291 PayloadTooLarge,
293 InvalidCommand,
295}
296
297impl TaskFailureCode {
298 pub fn is_cancelled(self) -> bool {
300 self == Self::Cancelled
301 }
302
303 pub fn is_timed_out(self) -> bool {
305 self == Self::TimedOut
306 }
307
308 pub fn is_application(self) -> bool {
310 self == Self::Application
311 }
312
313 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 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#[derive(Debug, Clone, thiserror::Error)]
351#[non_exhaustive]
352pub enum WorkflowError {
353 #[error("Task '{task_type}' failed after {attempts} attempts: {reason}")]
355 #[non_exhaustive]
356 TaskFailed {
357 task_type: String,
359 attempts: u32,
361 reason: String,
363 error_type: String,
367 code: TaskFailureCode,
370 },
371
372 #[error("Timer '{timer_id}' failed: {reason}")]
374 #[non_exhaustive]
375 TimerFailed {
376 timer_id: String,
378 reason: String,
380 },
381
382 #[error("Child workflow '{workflow_type}' (ID: {workflow_id}) failed: {reason}")]
384 #[non_exhaustive]
385 ChildWorkflowFailed {
386 workflow_type: String,
388 workflow_id: String,
390 reason: String,
392 },
393
394 #[error("State error: {0}")]
396 StateError(
397 String,
399 ),
400
401 #[error("Workflow was canceled")]
403 Canceled,
404
405 #[error("Workflow execution timed out after {timeout:?}")]
407 #[non_exhaustive]
408 Timeout {
409 timeout: std::time::Duration,
411 },
412
413 #[error("Workflow panicked: {0}")]
415 Panic(
416 String,
418 ),
419
420 #[error("Non-deterministic workflow execution detected: {0}")]
422 NonDeterministic(
423 String,
425 ),
426
427 #[error("Event '{event}' error: {reason}")]
429 #[non_exhaustive]
430 EventError {
431 event: String,
433 reason: String,
435 },
436
437 #[error("Query '{query}' error: {reason}")]
439 #[non_exhaustive]
440 QueryError {
441 query: String,
443 reason: String,
445 },
446
447 #[error("{}", compensation_failed_message(failed, reason, step_failure.as_deref()))]
456 #[non_exhaustive]
457 CompensationFailed {
458 failed: Vec<String>,
460 reason: String,
462 step_failure: Option<String>,
465 },
466
467 #[error("Invalid workflow state: {0}")]
469 InvalidState(
470 String,
472 ),
473
474 #[error("Workflow '{workflow_id}' not found")]
476 #[non_exhaustive]
477 NotFound {
478 workflow_id: String,
480 },
481
482 #[error("Replay error: {0}")]
484 ReplayError(
485 String,
487 ),
488
489 #[error("Restart fresh error: {0}")]
491 RestartFreshError(
492 String,
494 ),
495
496 #[error("Version mismatch: expected {expected}, got {actual}")]
498 #[non_exhaustive]
499 VersionMismatch {
500 expected: String,
502 actual: String,
504 },
505
506 #[error("Workflow suspended: {reason}")]
513 #[non_exhaustive]
514 Suspended {
515 reason: String,
517 pending_operations: Vec<String>,
519 },
520}
521
522fn 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#[derive(Debug, Clone, thiserror::Error)]
547#[non_exhaustive]
548pub enum TaskError {
549 #[error("Task execution failed: {0}")]
551 ExecutionFailed(
552 String,
554 ),
555
556 #[error("Task execution timed out after {timeout:?}")]
558 #[non_exhaustive]
559 Timeout {
560 timeout: std::time::Duration,
562 },
563
564 #[error("Task was canceled")]
566 Canceled,
567
568 #[error("Heartbeat failed: {0}")]
570 HeartbeatFailed(
571 String,
573 ),
574
575 #[error("No heartbeat received within {timeout:?}")]
577 #[non_exhaustive]
578 HeartbeatTimeout {
579 timeout: std::time::Duration,
581 },
582
583 #[error("Task '{task_id}' not found")]
585 #[non_exhaustive]
586 NotFound {
587 task_id: String,
589 },
590
591 #[error("Task '{task_id}' already completed")]
593 #[non_exhaustive]
594 AlreadyCompleted {
595 task_id: String,
597 },
598
599 #[error("Task panicked: {0}")]
601 Panic(
602 String,
604 ),
605
606 #[error("Task failed after {attempts} retry attempts")]
608 #[non_exhaustive]
609 RetryLimitExceeded {
610 attempts: u32,
612 },
613
614 #[error("Invalid task input: {0}")]
616 InvalidInput(
617 String,
619 ),
620
621 #[error("Invalid task configuration: {0}")]
623 InvalidConfiguration(
624 String,
626 ),
627
628 #[error("{message}")]
633 #[non_exhaustive]
634 Application {
635 error_type: String,
637 message: String,
639 non_retryable: bool,
642 },
643}
644
645#[derive(Debug, Clone, thiserror::Error)]
647#[non_exhaustive]
648pub enum ClientError {
649 #[error("Failed to connect to server at '{url}': {reason}")]
651 #[non_exhaustive]
652 ConnectionFailed {
653 url: String,
655 reason: String,
657 },
658
659 #[error("Request failed: {0}")]
661 RequestFailed(
662 String,
664 ),
665
666 #[error("Request timed out after {timeout:?}")]
668 #[non_exhaustive]
669 Timeout {
670 timeout: std::time::Duration,
672 },
673
674 #[error("Invalid server URL: {0}")]
676 InvalidUrl(
677 String,
679 ),
680
681 #[error("Authentication failed: {0}")]
683 AuthenticationFailed(
684 String,
686 ),
687
688 #[error("Authorization failed: {0}")]
690 AuthorizationFailed(
691 String,
693 ),
694
695 #[error("Workflow '{workflow_id}' not found")]
697 #[non_exhaustive]
698 WorkflowNotFound {
699 workflow_id: String,
701 },
702
703 #[error("Workflow '{workflow_id}' already exists")]
706 #[non_exhaustive]
707 WorkflowAlreadyExists {
708 workflow_id: String,
710 run_id: Option<String>,
713 },
714
715 #[error("Invalid workflow input: {0}")]
717 InvalidInput(
718 String,
720 ),
721
722 #[error("Invalid response from server: {0}")]
724 InvalidResponse(
725 String,
727 ),
728
729 #[error("Server error (status {status}): {message}")]
731 #[non_exhaustive]
732 ServerError {
733 status: u16,
735 message: String,
737 },
738
739 #[error("Serialization error: {0}")]
741 Serialization(
742 String,
744 ),
745
746 #[error("Deserialization error: {0}")]
748 Deserialization(
749 String,
751 ),
752}
753
754#[derive(Debug, Clone, thiserror::Error)]
756#[non_exhaustive]
757pub enum WorkerError {
758 #[error("Invalid configuration: {0}")]
760 InvalidConfiguration(
761 String,
763 ),
764
765 #[error("Failed to start service: {0}")]
767 StartupFailed(
768 String,
770 ),
771
772 #[error("Worker is already running")]
774 AlreadyRunning,
775
776 #[error("Worker is not running")]
778 NotRunning,
779
780 #[error("Failed to connect to server at '{url}': {reason}")]
782 #[non_exhaustive]
783 ConnectionFailed {
784 url: String,
786 reason: String,
788 },
789
790 #[error("Polling error: {0}")]
792 PollingError(
793 String,
795 ),
796
797 #[error("Handler registration error: {0}")]
799 RegistrationError(
800 String,
802 ),
803
804 #[error("No handler registered for '{handler_type}' with name '{name}'")]
806 #[non_exhaustive]
807 HandlerNotFound {
808 handler_type: String,
810 name: String,
812 },
813
814 #[error("Handler execution error: {0}")]
816 HandlerExecutionError(
817 String,
819 ),
820
821 #[error("Shutdown error: {0}")]
823 ShutdownError(
824 String,
826 ),
827
828 #[error("Shutdown timed out after {timeout:?}")]
830 #[non_exhaustive]
831 ShutdownTimeout {
832 timeout: std::time::Duration,
834 },
835
836 #[error("Resource exhausted: {resource}")]
838 #[non_exhaustive]
839 ResourceExhausted {
840 resource: String,
842 },
843
844 #[error("Task queue '{queue}' not found")]
846 #[non_exhaustive]
847 TaskQueueNotFound {
848 queue: String,
850 },
851}
852
853fn 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 _ => 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 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 CoreError::TaskExecutionFailed { reason, .. } => {
910 Error::Task(TaskError::ExecutionFailed(reason))
911 }
912 CoreError::TaskCancelled { .. } => Error::Task(TaskError::Canceled),
913
914 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 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 CoreError::Status(status) => Error::Client(ClientError::ServerError {
937 status: grpc_code_to_http_status(status.code()),
942 message: status.message().to_string(),
943 }),
944
945 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 CoreError::Configuration(msg) => Error::Configuration(msg),
955
956 CoreError::WorkerError(msg) => Error::Worker(WorkerError::PollingError(msg)),
958 CoreError::PollerError(msg) => Error::Worker(WorkerError::PollingError(msg)),
959
960 CoreError::Timeout { .. } => {
962 Error::Client(ClientError::Timeout {
963 timeout: std::time::Duration::from_secs(30), })
965 }
966
967 CoreError::ResourceExhausted { resource, .. } => {
969 Error::Worker(WorkerError::ResourceExhausted { resource })
970 }
971
972 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 CoreError::Internal(msg) => Error::Other(msg),
983 CoreError::CacheError(msg) => Error::Other(msg),
984 CoreError::StateMachineError(msg) => Error::Workflow(WorkflowError::InvalidState(msg)),
985
986 CoreError::WithContext {
988 context, source, ..
989 } => {
990 let sdk_error: Error = (*source).into();
991 Error::Other(format!("{}: {}", context, sdk_error))
992 }
993
994 CoreError::Other(err) => Error::Other(err.to_string()),
996
997 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
1015impl Error {
1020 pub fn is_suspend(&self) -> bool {
1028 matches!(self, Error::Workflow(WorkflowError::Suspended { .. }))
1029 }
1030
1031 pub fn is_retryable(&self) -> bool {
1048 match self {
1049 Error::Client(ClientError::ConnectionFailed { .. }) => true,
1051 Error::Client(ClientError::Timeout { .. }) => true,
1052 Error::Client(ClientError::RequestFailed(_)) => true,
1053 Error::Client(ClientError::ServerError { status, .. }) => {
1054 *status == 429 || (*status >= 500 && *status < 600)
1058 }
1059
1060 Error::Worker(WorkerError::PollingError(_)) => true,
1062 Error::Worker(WorkerError::ConnectionFailed { .. }) => true,
1063 Error::Worker(WorkerError::ResourceExhausted { .. }) => true,
1064
1065 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 Error::Io(_) => true,
1073
1074 _ => false,
1076 }
1077 }
1078
1079 pub fn is_permanent(&self) -> bool {
1096 match self {
1097 Error::Configuration(_) => true,
1099
1100 Error::Workflow(WorkflowError::NonDeterministic(_)) => true,
1102 Error::Workflow(WorkflowError::VersionMismatch { .. }) => true,
1103 Error::Workflow(WorkflowError::InvalidState(_)) => true,
1104
1105 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 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 Error::Worker(WorkerError::InvalidConfiguration(_)) => true,
1120 Error::Worker(WorkerError::HandlerNotFound { .. }) => true,
1121
1122 Error::Client(ClientError::ServerError { status, .. }) => {
1124 *status >= 400 && *status < 500 && *status != 429
1125 }
1126
1127 _ => false,
1128 }
1129 }
1130
1131 pub fn with_context(self, context: impl Into<String>) -> Self {
1146 Error::Other(format!("{}: {}", context.into(), self))
1147 }
1148
1149 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, },
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 pub fn severity(&self) -> Severity {
1227 match self {
1228 Error::Worker(WorkerError::StartupFailed(_)) => Severity::Critical,
1230 Error::Worker(WorkerError::ConnectionFailed { .. }) => Severity::Critical,
1231 Error::Configuration(_) => Severity::Critical,
1232
1233 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 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 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 _ => Severity::Medium,
1272 }
1273 }
1274}
1275
1276impl WorkflowError {
1281 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 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 pub fn task_failure_code(&self) -> Option<TaskFailureCode> {
1319 match self {
1320 Self::TaskFailed { code, .. } => Some(*code),
1321 _ => None,
1322 }
1323 }
1324
1325 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 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 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 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 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 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 pub fn not_found(workflow_id: impl Into<String>) -> Self {
1386 Self::NotFound {
1387 workflow_id: workflow_id.into(),
1388 }
1389 }
1390
1391 pub fn timeout(timeout: std::time::Duration) -> Self {
1393 Self::Timeout { timeout }
1394 }
1395
1396 pub fn non_deterministic(reason: impl Into<String>) -> Self {
1398 Self::NonDeterministic(reason.into())
1399 }
1400
1401 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 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 pub fn execution_failed(reason: impl Into<String>) -> Self {
1421 Self::ExecutionFailed(reason.into())
1422 }
1423
1424 pub fn heartbeat_failed(reason: impl Into<String>) -> Self {
1426 Self::HeartbeatFailed(reason.into())
1427 }
1428
1429 pub fn timeout(timeout: std::time::Duration) -> Self {
1431 Self::Timeout { timeout }
1432 }
1433
1434 pub fn not_found(task_id: impl Into<String>) -> Self {
1436 Self::NotFound {
1437 task_id: task_id.into(),
1438 }
1439 }
1440
1441 pub fn retry_limit_exceeded(attempts: u32) -> Self {
1443 Self::RetryLimitExceeded { attempts }
1444 }
1445
1446 pub fn heartbeat_timeout(timeout: std::time::Duration) -> Self {
1448 Self::HeartbeatTimeout { timeout }
1449 }
1450
1451 pub fn already_completed(task_id: impl Into<String>) -> Self {
1453 Self::AlreadyCompleted {
1454 task_id: task_id.into(),
1455 }
1456 }
1457
1458 pub fn invalid_input(reason: impl Into<String>) -> Self {
1460 Self::InvalidInput(reason.into())
1461 }
1462
1463 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 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 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 pub fn server_error(status: u16, message: impl Into<String>) -> Self {
1499 Self::ServerError {
1500 status,
1501 message: message.into(),
1502 }
1503 }
1504
1505 pub fn timeout(timeout: std::time::Duration) -> Self {
1507 Self::Timeout { timeout }
1508 }
1509
1510 pub fn workflow_not_found(workflow_id: impl Into<String>) -> Self {
1512 Self::WorkflowNotFound {
1513 workflow_id: workflow_id.into(),
1514 }
1515 }
1516
1517 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 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 pub fn request_failed(reason: impl Into<String>) -> Self {
1538 Self::RequestFailed(reason.into())
1539 }
1540
1541 pub fn serialization(reason: impl Into<String>) -> Self {
1543 Self::Serialization(reason.into())
1544 }
1545
1546 pub fn deserialization(reason: impl Into<String>) -> Self {
1548 Self::Deserialization(reason.into())
1549 }
1550}
1551
1552impl WorkerError {
1553 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 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 pub fn invalid_configuration(reason: impl Into<String>) -> Self {
1571 Self::InvalidConfiguration(reason.into())
1572 }
1573
1574 pub fn startup_failed(reason: impl Into<String>) -> Self {
1576 Self::StartupFailed(reason.into())
1577 }
1578
1579 pub fn polling_error(reason: impl Into<String>) -> Self {
1581 Self::PollingError(reason.into())
1582 }
1583
1584 pub fn resource_exhausted(resource: impl Into<String>) -> Self {
1586 Self::ResourceExhausted {
1587 resource: resource.into(),
1588 }
1589 }
1590
1591 pub fn shutdown_timeout(timeout: std::time::Duration) -> Self {
1593 Self::ShutdownTimeout { timeout }
1594 }
1595
1596 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 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 #[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 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 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 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 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 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 #[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 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 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 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 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 #[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 #[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 #[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 #[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 #[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}