pub type Result<T> = std::result::Result<T, Error>;
pub(crate) const TASK_FAILED_SENTINEL_KEY: &str = "__orcher_task_failed__";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorCode {
WorkflowFailed,
WorkflowNotFound,
WorkflowAlreadyExists,
WorkflowCanceled,
WorkflowTimeout,
WorkflowNonDeterministic,
WorkflowStateError,
WorkflowVersionMismatch,
WorkflowReplayError,
TaskFailed,
TaskNotFound,
TaskTimeout,
TaskCanceled,
TaskHeartbeatFailed,
TaskRetryLimitExceeded,
TaskInvalidInput,
ConnectionFailed,
RequestTimeout,
AuthenticationFailed,
AuthorizationFailed,
ServerError,
InvalidRequest,
InvalidConfiguration,
StartupFailed,
ShutdownError,
HandlerNotFound,
ResourceExhausted,
PollingError,
SerializationError,
NetworkError,
IoError,
Internal,
}
impl std::fmt::Display for ErrorCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Self::WorkflowFailed => "WORKFLOW_FAILED",
Self::WorkflowNotFound => "WORKFLOW_NOT_FOUND",
Self::WorkflowAlreadyExists => "WORKFLOW_ALREADY_EXISTS",
Self::WorkflowCanceled => "WORKFLOW_CANCELED",
Self::WorkflowTimeout => "WORKFLOW_TIMEOUT",
Self::WorkflowNonDeterministic => "WORKFLOW_NON_DETERMINISTIC",
Self::WorkflowStateError => "WORKFLOW_STATE_ERROR",
Self::WorkflowVersionMismatch => "WORKFLOW_VERSION_MISMATCH",
Self::WorkflowReplayError => "WORKFLOW_REPLAY_ERROR",
Self::TaskFailed => "TASK_FAILED",
Self::TaskNotFound => "TASK_NOT_FOUND",
Self::TaskTimeout => "TASK_TIMEOUT",
Self::TaskCanceled => "TASK_CANCELED",
Self::TaskHeartbeatFailed => "TASK_HEARTBEAT_FAILED",
Self::TaskRetryLimitExceeded => "TASK_RETRY_LIMIT_EXCEEDED",
Self::TaskInvalidInput => "TASK_INVALID_INPUT",
Self::ConnectionFailed => "CONNECTION_FAILED",
Self::RequestTimeout => "REQUEST_TIMEOUT",
Self::AuthenticationFailed => "AUTHENTICATION_FAILED",
Self::AuthorizationFailed => "AUTHORIZATION_FAILED",
Self::ServerError => "SERVER_ERROR",
Self::InvalidRequest => "INVALID_REQUEST",
Self::InvalidConfiguration => "INVALID_CONFIGURATION",
Self::StartupFailed => "STARTUP_FAILED",
Self::ShutdownError => "SHUTDOWN_ERROR",
Self::HandlerNotFound => "HANDLER_NOT_FOUND",
Self::ResourceExhausted => "RESOURCE_EXHAUSTED",
Self::PollingError => "POLLING_ERROR",
Self::SerializationError => "SERIALIZATION_ERROR",
Self::NetworkError => "NETWORK_ERROR",
Self::IoError => "IO_ERROR",
Self::Internal => "INTERNAL",
};
write!(f, "{}", s)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Severity {
Low,
Medium,
High,
Critical,
}
impl std::fmt::Display for Severity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Self::Low => "LOW",
Self::Medium => "MEDIUM",
Self::High => "HIGH",
Self::Critical => "CRITICAL",
};
write!(f, "{}", s)
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("Workflow error: {0}")]
Workflow(#[from] WorkflowError),
#[error("Task error: {0}")]
Task(#[from] TaskError),
#[error("Client error: {0}")]
Client(#[from] ClientError),
#[error("Worker error: {0}")]
Worker(#[from] WorkerError),
#[error("Actor error: {0}")]
Actor(String),
#[error("Network error: {0}")]
Network(String),
#[error("Configuration error: {0}")]
Configuration(String),
#[error("Serialization error: {0}")]
Serialization(String),
#[error("Timeout: {0}")]
Timeout(String),
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("{0}")]
Other(String),
}
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum WorkflowError {
#[error("Task '{task_type}' failed after {attempts} attempts: {reason}")]
#[non_exhaustive]
TaskFailed {
task_type: String,
attempts: u32,
reason: String,
},
#[error("Timer '{timer_id}' failed: {reason}")]
#[non_exhaustive]
TimerFailed {
timer_id: String,
reason: String,
},
#[error("Child workflow '{workflow_type}' (ID: {workflow_id}) failed: {reason}")]
#[non_exhaustive]
ChildWorkflowFailed {
workflow_type: String,
workflow_id: String,
reason: String,
},
#[error("State error: {0}")]
StateError(
String,
),
#[error("Workflow was canceled")]
Canceled,
#[error("Workflow execution timed out after {timeout:?}")]
#[non_exhaustive]
Timeout {
timeout: std::time::Duration,
},
#[error("Workflow panicked: {0}")]
Panic(
String,
),
#[error("Non-deterministic workflow execution detected: {0}")]
NonDeterministic(
String,
),
#[error("Event '{event}' error: {reason}")]
#[non_exhaustive]
EventError {
event: String,
reason: String,
},
#[error("Query '{query}' error: {reason}")]
#[non_exhaustive]
QueryError {
query: String,
reason: String,
},
#[error("Invalid workflow state: {0}")]
InvalidState(
String,
),
#[error("Workflow '{workflow_id}' not found")]
#[non_exhaustive]
NotFound {
workflow_id: String,
},
#[error("Replay error: {0}")]
ReplayError(
String,
),
#[error("Restart fresh error: {0}")]
RestartFreshError(
String,
),
#[error("Version mismatch: expected {expected}, got {actual}")]
#[non_exhaustive]
VersionMismatch {
expected: String,
actual: String,
},
#[error("Workflow suspended: {reason}")]
#[non_exhaustive]
Suspended {
reason: String,
pending_operations: Vec<String>,
},
}
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum TaskError {
#[error("Task execution failed: {0}")]
ExecutionFailed(
String,
),
#[error("Task execution timed out after {timeout:?}")]
#[non_exhaustive]
Timeout {
timeout: std::time::Duration,
},
#[error("Task was canceled")]
Canceled,
#[error("Heartbeat failed: {0}")]
HeartbeatFailed(
String,
),
#[error("No heartbeat received within {timeout:?}")]
#[non_exhaustive]
HeartbeatTimeout {
timeout: std::time::Duration,
},
#[error("Task '{task_id}' not found")]
#[non_exhaustive]
NotFound {
task_id: String,
},
#[error("Task '{task_id}' already completed")]
#[non_exhaustive]
AlreadyCompleted {
task_id: String,
},
#[error("Task panicked: {0}")]
Panic(
String,
),
#[error("Task failed after {attempts} retry attempts")]
#[non_exhaustive]
RetryLimitExceeded {
attempts: u32,
},
#[error("Invalid task input: {0}")]
InvalidInput(
String,
),
#[error("Invalid task configuration: {0}")]
InvalidConfiguration(
String,
),
#[error("{message}")]
#[non_exhaustive]
Application {
error_type: String,
message: String,
non_retryable: bool,
},
}
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum ClientError {
#[error("Failed to connect to server at '{url}': {reason}")]
#[non_exhaustive]
ConnectionFailed {
url: String,
reason: String,
},
#[error("Request failed: {0}")]
RequestFailed(
String,
),
#[error("Request timed out after {timeout:?}")]
#[non_exhaustive]
Timeout {
timeout: std::time::Duration,
},
#[error("Invalid server URL: {0}")]
InvalidUrl(
String,
),
#[error("Authentication failed: {0}")]
AuthenticationFailed(
String,
),
#[error("Authorization failed: {0}")]
AuthorizationFailed(
String,
),
#[error("Workflow '{workflow_id}' not found")]
#[non_exhaustive]
WorkflowNotFound {
workflow_id: String,
},
#[error("Workflow '{workflow_id}' already exists")]
#[non_exhaustive]
WorkflowAlreadyExists {
workflow_id: String,
run_id: Option<String>,
},
#[error("Invalid workflow input: {0}")]
InvalidInput(
String,
),
#[error("Invalid response from server: {0}")]
InvalidResponse(
String,
),
#[error("Server error (status {status}): {message}")]
#[non_exhaustive]
ServerError {
status: u16,
message: String,
},
#[error("Serialization error: {0}")]
Serialization(
String,
),
#[error("Deserialization error: {0}")]
Deserialization(
String,
),
}
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum WorkerError {
#[error("Invalid configuration: {0}")]
InvalidConfiguration(
String,
),
#[error("Failed to start service: {0}")]
StartupFailed(
String,
),
#[error("Worker is already running")]
AlreadyRunning,
#[error("Worker is not running")]
NotRunning,
#[error("Failed to connect to server at '{url}': {reason}")]
#[non_exhaustive]
ConnectionFailed {
url: String,
reason: String,
},
#[error("Polling error: {0}")]
PollingError(
String,
),
#[error("Handler registration error: {0}")]
RegistrationError(
String,
),
#[error("No handler registered for '{handler_type}' with name '{name}'")]
#[non_exhaustive]
HandlerNotFound {
handler_type: String,
name: String,
},
#[error("Handler execution error: {0}")]
HandlerExecutionError(
String,
),
#[error("Shutdown error: {0}")]
ShutdownError(
String,
),
#[error("Shutdown timed out after {timeout:?}")]
#[non_exhaustive]
ShutdownTimeout {
timeout: std::time::Duration,
},
#[error("Resource exhausted: {resource}")]
#[non_exhaustive]
ResourceExhausted {
resource: String,
},
#[error("Task queue '{queue}' not found")]
#[non_exhaustive]
TaskQueueNotFound {
queue: String,
},
}
fn grpc_code_to_http_status(code: tonic::Code) -> u16 {
use tonic::Code;
match code {
Code::Ok => 200,
Code::InvalidArgument | Code::OutOfRange | Code::FailedPrecondition => 400,
Code::Unauthenticated => 401,
Code::PermissionDenied => 403,
Code::NotFound => 404,
Code::AlreadyExists | Code::Aborted => 409,
Code::Cancelled => 499,
Code::ResourceExhausted => 429,
Code::Unimplemented => 501,
Code::Unavailable => 503,
Code::DeadlineExceeded => 504,
_ => 500,
}
}
impl From<orcher_sdk_core::error::Error> for Error {
fn from(err: orcher_sdk_core::error::Error) -> Self {
use orcher_sdk_core::error::Error as CoreError;
match err {
CoreError::WorkflowNotFound { workflow_id, .. } => {
Error::Workflow(WorkflowError::NotFound { workflow_id })
}
CoreError::WorkflowAlreadyExists {
workflow_id,
run_id,
..
} => Error::Client(ClientError::WorkflowAlreadyExists {
workflow_id,
run_id,
}),
CoreError::WorkflowExecutionFailed { message, .. } => {
Error::Workflow(WorkflowError::Panic(message))
}
CoreError::WorkflowCancelled { .. } => Error::Workflow(WorkflowError::Canceled),
CoreError::WorkflowTerminated { reason, .. } => Error::Workflow(WorkflowError::Panic(
reason.unwrap_or_else(|| "Workflow terminated".to_string()),
)),
CoreError::TaskExecutionFailed { reason, .. } => {
Error::Task(TaskError::ExecutionFailed(reason))
}
CoreError::TaskCancelled { .. } => Error::Task(TaskError::Canceled),
CoreError::InvalidWorkflowState {
expected, actual, ..
} => Error::Workflow(WorkflowError::InvalidState(format!(
"Expected state: {}, got: {}",
expected, actual
))),
CoreError::DeterminismViolation { reason, .. } => {
Error::Workflow(WorkflowError::NonDeterministic(reason))
}
CoreError::InvalidExecutionJournal { reason, .. } => {
Error::Workflow(WorkflowError::ReplayError(reason))
}
CoreError::ReplayError(reason) => Error::Workflow(WorkflowError::ReplayError(reason)),
CoreError::Serialization(msg) => Error::Serialization(msg),
CoreError::Deserialization(msg) => Error::Serialization(msg),
CoreError::InvalidPayload { reason, .. } => Error::Serialization(reason),
CoreError::Codec(msg) => Error::Serialization(msg),
CoreError::Transport(err) => Error::Client(ClientError::ConnectionFailed {
url: "unknown".to_string(),
reason: err.to_string(),
}),
CoreError::GrpcStatus(status) => Error::Client(ClientError::ServerError {
status: grpc_code_to_http_status(status.code()),
message: status.message().to_string(),
}),
CoreError::Connection(msg) => Error::Client(ClientError::ConnectionFailed {
url: "unknown".to_string(),
reason: msg,
}),
CoreError::Authentication(msg) => Error::Client(ClientError::AuthenticationFailed(msg)),
CoreError::Authorization(msg) => Error::Client(ClientError::AuthorizationFailed(msg)),
CoreError::Configuration(msg) => Error::Configuration(msg),
CoreError::WorkerError(msg) => Error::Worker(WorkerError::PollingError(msg)),
CoreError::PollerError(msg) => Error::Worker(WorkerError::PollingError(msg)),
CoreError::Timeout { .. } => {
Error::Client(ClientError::Timeout {
timeout: std::time::Duration::from_secs(30), })
}
CoreError::ResourceExhausted { resource, .. } => {
Error::Worker(WorkerError::ResourceExhausted { resource })
}
CoreError::InvalidCommand { reason, .. } => {
Error::Workflow(WorkflowError::InvalidState(reason))
}
CoreError::InvalidEvent { reason, .. } => Error::Workflow(WorkflowError::EventError {
event: "unknown".to_string(),
reason,
}),
CoreError::Internal(msg) => Error::Other(msg),
CoreError::CacheError(msg) => Error::Other(msg),
CoreError::StateMachineError(msg) => Error::Workflow(WorkflowError::InvalidState(msg)),
CoreError::WithContext {
context, source, ..
} => {
let sdk_error: Error = (*source).into();
Error::Other(format!("{}: {}", context, sdk_error))
}
CoreError::Other(err) => Error::Other(err.to_string()),
other => Error::Other(other.to_string()),
}
}
}
impl From<serde_json::Error> for Error {
fn from(err: serde_json::Error) -> Self {
Error::Serialization(err.to_string())
}
}
impl From<anyhow::Error> for Error {
fn from(err: anyhow::Error) -> Self {
Error::Other(err.to_string())
}
}
impl Error {
pub fn is_suspend(&self) -> bool {
matches!(self, Error::Workflow(WorkflowError::Suspended { .. }))
}
pub fn is_retryable(&self) -> bool {
match self {
Error::Client(ClientError::ConnectionFailed { .. }) => true,
Error::Client(ClientError::Timeout { .. }) => true,
Error::Client(ClientError::RequestFailed(_)) => true,
Error::Client(ClientError::ServerError { status, .. }) => {
*status == 429 || (*status >= 500 && *status < 600)
}
Error::Worker(WorkerError::PollingError(_)) => true,
Error::Worker(WorkerError::ConnectionFailed { .. }) => true,
Error::Worker(WorkerError::ResourceExhausted { .. }) => true,
Error::Task(TaskError::ExecutionFailed(_)) => true,
Error::Task(TaskError::Timeout { .. }) => true,
Error::Task(TaskError::HeartbeatTimeout { .. }) => true,
Error::Task(TaskError::Application { non_retryable, .. }) => !non_retryable,
Error::Io(_) => true,
_ => false,
}
}
pub fn is_permanent(&self) -> bool {
match self {
Error::Configuration(_) => true,
Error::Workflow(WorkflowError::NonDeterministic(_)) => true,
Error::Workflow(WorkflowError::VersionMismatch { .. }) => true,
Error::Workflow(WorkflowError::InvalidState(_)) => true,
Error::Task(TaskError::InvalidInput(_)) => true,
Error::Task(TaskError::InvalidConfiguration(_)) => true,
Error::Task(TaskError::RetryLimitExceeded { .. }) => true,
Error::Task(TaskError::Application { non_retryable, .. }) => *non_retryable,
Error::Client(ClientError::AuthenticationFailed(_)) => true,
Error::Client(ClientError::AuthorizationFailed(_)) => true,
Error::Client(ClientError::InvalidUrl(_)) => true,
Error::Client(ClientError::InvalidInput(_)) => true,
Error::Client(ClientError::WorkflowAlreadyExists { .. }) => true,
Error::Worker(WorkerError::InvalidConfiguration(_)) => true,
Error::Worker(WorkerError::HandlerNotFound { .. }) => true,
Error::Client(ClientError::ServerError { status, .. }) => {
*status >= 400 && *status < 500 && *status != 429
}
_ => false,
}
}
pub fn with_context(self, context: impl Into<String>) -> Self {
Error::Other(format!("{}: {}", context.into(), self))
}
pub fn code(&self) -> ErrorCode {
match self {
Error::Workflow(w) => match w {
WorkflowError::TaskFailed { .. } => ErrorCode::TaskFailed,
WorkflowError::TimerFailed { .. } => ErrorCode::WorkflowFailed,
WorkflowError::ChildWorkflowFailed { .. } => ErrorCode::WorkflowFailed,
WorkflowError::StateError(_) => ErrorCode::WorkflowStateError,
WorkflowError::Canceled => ErrorCode::WorkflowCanceled,
WorkflowError::Timeout { .. } => ErrorCode::WorkflowTimeout,
WorkflowError::Panic(_) => ErrorCode::WorkflowFailed,
WorkflowError::NonDeterministic(_) => ErrorCode::WorkflowNonDeterministic,
WorkflowError::EventError { .. } => ErrorCode::WorkflowFailed,
WorkflowError::QueryError { .. } => ErrorCode::WorkflowFailed,
WorkflowError::InvalidState(_) => ErrorCode::WorkflowStateError,
WorkflowError::NotFound { .. } => ErrorCode::WorkflowNotFound,
WorkflowError::ReplayError(_) => ErrorCode::WorkflowReplayError,
WorkflowError::RestartFreshError(_) => ErrorCode::WorkflowFailed,
WorkflowError::VersionMismatch { .. } => ErrorCode::WorkflowVersionMismatch,
WorkflowError::Suspended { .. } => ErrorCode::Internal, },
Error::Task(t) => match t {
TaskError::ExecutionFailed(_) => ErrorCode::TaskFailed,
TaskError::Timeout { .. } => ErrorCode::TaskTimeout,
TaskError::Canceled => ErrorCode::TaskCanceled,
TaskError::HeartbeatFailed(_) => ErrorCode::TaskHeartbeatFailed,
TaskError::HeartbeatTimeout { .. } => ErrorCode::TaskHeartbeatFailed,
TaskError::NotFound { .. } => ErrorCode::TaskNotFound,
TaskError::AlreadyCompleted { .. } => ErrorCode::TaskFailed,
TaskError::Panic(_) => ErrorCode::TaskFailed,
TaskError::RetryLimitExceeded { .. } => ErrorCode::TaskRetryLimitExceeded,
TaskError::InvalidInput(_) => ErrorCode::TaskInvalidInput,
TaskError::InvalidConfiguration(_) => ErrorCode::InvalidConfiguration,
TaskError::Application { .. } => ErrorCode::TaskFailed,
},
Error::Client(c) => match c {
ClientError::ConnectionFailed { .. } => ErrorCode::ConnectionFailed,
ClientError::RequestFailed(_) => ErrorCode::ServerError,
ClientError::Timeout { .. } => ErrorCode::RequestTimeout,
ClientError::InvalidUrl(_) => ErrorCode::InvalidRequest,
ClientError::AuthenticationFailed(_) => ErrorCode::AuthenticationFailed,
ClientError::AuthorizationFailed(_) => ErrorCode::AuthorizationFailed,
ClientError::WorkflowNotFound { .. } => ErrorCode::WorkflowNotFound,
ClientError::WorkflowAlreadyExists { .. } => ErrorCode::WorkflowAlreadyExists,
ClientError::InvalidInput(_) => ErrorCode::InvalidRequest,
ClientError::InvalidResponse(_) => ErrorCode::ServerError,
ClientError::ServerError { .. } => ErrorCode::ServerError,
ClientError::Serialization(_) => ErrorCode::SerializationError,
ClientError::Deserialization(_) => ErrorCode::SerializationError,
},
Error::Worker(s) => match s {
WorkerError::InvalidConfiguration(_) => ErrorCode::InvalidConfiguration,
WorkerError::StartupFailed(_) => ErrorCode::StartupFailed,
WorkerError::AlreadyRunning => ErrorCode::InvalidConfiguration,
WorkerError::NotRunning => ErrorCode::InvalidConfiguration,
WorkerError::ConnectionFailed { .. } => ErrorCode::ConnectionFailed,
WorkerError::PollingError(_) => ErrorCode::PollingError,
WorkerError::RegistrationError(_) => ErrorCode::StartupFailed,
WorkerError::HandlerNotFound { .. } => ErrorCode::HandlerNotFound,
WorkerError::HandlerExecutionError(_) => ErrorCode::Internal,
WorkerError::ShutdownError(_) => ErrorCode::ShutdownError,
WorkerError::ShutdownTimeout { .. } => ErrorCode::ShutdownError,
WorkerError::ResourceExhausted { .. } => ErrorCode::ResourceExhausted,
WorkerError::TaskQueueNotFound { .. } => ErrorCode::HandlerNotFound,
},
Error::Actor(_) => ErrorCode::Internal,
Error::Network(_) => ErrorCode::NetworkError,
Error::Configuration(_) => ErrorCode::InvalidConfiguration,
Error::Serialization(_) => ErrorCode::SerializationError,
Error::Timeout(_) => ErrorCode::RequestTimeout,
Error::Io(_) => ErrorCode::IoError,
Error::Other(_) => ErrorCode::Internal,
}
}
pub fn severity(&self) -> Severity {
match self {
Error::Worker(WorkerError::StartupFailed(_)) => Severity::Critical,
Error::Worker(WorkerError::ConnectionFailed { .. }) => Severity::Critical,
Error::Configuration(_) => Severity::Critical,
Error::Workflow(WorkflowError::NonDeterministic(_)) => Severity::High,
Error::Workflow(WorkflowError::VersionMismatch { .. }) => Severity::High,
Error::Workflow(WorkflowError::Panic(_)) => Severity::High,
Error::Task(TaskError::Panic(_)) => Severity::High,
Error::Task(TaskError::RetryLimitExceeded { .. }) => Severity::High,
Error::Client(ClientError::AuthenticationFailed(_)) => Severity::High,
Error::Client(ClientError::AuthorizationFailed(_)) => Severity::High,
Error::Worker(WorkerError::ShutdownError(_)) => Severity::High,
Error::Worker(WorkerError::ShutdownTimeout { .. }) => Severity::High,
Error::Worker(WorkerError::ResourceExhausted { .. }) => Severity::High,
Error::Workflow(WorkflowError::TaskFailed { .. }) => Severity::Medium,
Error::Workflow(WorkflowError::ChildWorkflowFailed { .. }) => Severity::Medium,
Error::Workflow(WorkflowError::Timeout { .. }) => Severity::Medium,
Error::Task(TaskError::ExecutionFailed(_)) => Severity::Medium,
Error::Task(TaskError::Timeout { .. }) => Severity::Medium,
Error::Task(TaskError::HeartbeatFailed(_)) => Severity::Medium,
Error::Task(TaskError::HeartbeatTimeout { .. }) => Severity::Medium,
Error::Client(ClientError::ConnectionFailed { .. }) => Severity::Medium,
Error::Client(ClientError::Timeout { .. }) => Severity::Medium,
Error::Client(ClientError::ServerError { .. }) => Severity::Medium,
Error::Worker(WorkerError::PollingError(_)) => Severity::Medium,
Error::Network(_) => Severity::Medium,
Error::Io(_) => Severity::Medium,
Error::Workflow(WorkflowError::Canceled) => Severity::Low,
Error::Workflow(WorkflowError::Suspended { .. }) => Severity::Low,
Error::Workflow(WorkflowError::NotFound { .. }) => Severity::Low,
Error::Task(TaskError::Canceled) => Severity::Low,
Error::Task(TaskError::NotFound { .. }) => Severity::Low,
Error::Client(ClientError::WorkflowNotFound { .. }) => Severity::Low,
Error::Client(ClientError::WorkflowAlreadyExists { .. }) => Severity::Low,
Error::Serialization(_) => Severity::Low,
_ => Severity::Medium,
}
}
}
impl WorkflowError {
pub fn task_failed(
task_type: impl Into<String>,
attempts: u32,
reason: impl Into<String>,
) -> Self {
Self::TaskFailed {
task_type: task_type.into(),
attempts,
reason: reason.into(),
}
}
pub fn timer_failed(timer_id: impl Into<String>, reason: impl Into<String>) -> Self {
Self::TimerFailed {
timer_id: timer_id.into(),
reason: reason.into(),
}
}
pub fn child_workflow_failed(
workflow_type: impl Into<String>,
workflow_id: impl Into<String>,
reason: impl Into<String>,
) -> Self {
Self::ChildWorkflowFailed {
workflow_type: workflow_type.into(),
workflow_id: workflow_id.into(),
reason: reason.into(),
}
}
pub fn event_error(event: impl Into<String>, reason: impl Into<String>) -> Self {
Self::EventError {
event: event.into(),
reason: reason.into(),
}
}
pub fn query_error(query: impl Into<String>, reason: impl Into<String>) -> Self {
Self::QueryError {
query: query.into(),
reason: reason.into(),
}
}
pub fn not_found(workflow_id: impl Into<String>) -> Self {
Self::NotFound {
workflow_id: workflow_id.into(),
}
}
pub fn timeout(timeout: std::time::Duration) -> Self {
Self::Timeout { timeout }
}
pub fn non_deterministic(reason: impl Into<String>) -> Self {
Self::NonDeterministic(reason.into())
}
pub fn version_mismatch(expected: impl Into<String>, actual: impl Into<String>) -> Self {
Self::VersionMismatch {
expected: expected.into(),
actual: actual.into(),
}
}
pub fn suspended(reason: impl Into<String>, pending_operations: Vec<String>) -> Self {
Self::Suspended {
reason: reason.into(),
pending_operations,
}
}
}
impl TaskError {
pub fn execution_failed(reason: impl Into<String>) -> Self {
Self::ExecutionFailed(reason.into())
}
pub fn heartbeat_failed(reason: impl Into<String>) -> Self {
Self::HeartbeatFailed(reason.into())
}
pub fn timeout(timeout: std::time::Duration) -> Self {
Self::Timeout { timeout }
}
pub fn not_found(task_id: impl Into<String>) -> Self {
Self::NotFound {
task_id: task_id.into(),
}
}
pub fn retry_limit_exceeded(attempts: u32) -> Self {
Self::RetryLimitExceeded { attempts }
}
pub fn heartbeat_timeout(timeout: std::time::Duration) -> Self {
Self::HeartbeatTimeout { timeout }
}
pub fn already_completed(task_id: impl Into<String>) -> Self {
Self::AlreadyCompleted {
task_id: task_id.into(),
}
}
pub fn invalid_input(reason: impl Into<String>) -> Self {
Self::InvalidInput(reason.into())
}
pub fn application(error_type: impl Into<String>, message: impl Into<String>) -> Self {
Self::Application {
error_type: error_type.into(),
message: message.into(),
non_retryable: false,
}
}
pub fn non_retryable(error_type: impl Into<String>, message: impl Into<String>) -> Self {
Self::Application {
error_type: error_type.into(),
message: message.into(),
non_retryable: true,
}
}
}
impl ClientError {
pub fn connection_failed(url: impl Into<String>, reason: impl Into<String>) -> Self {
Self::ConnectionFailed {
url: url.into(),
reason: reason.into(),
}
}
pub fn server_error(status: u16, message: impl Into<String>) -> Self {
Self::ServerError {
status,
message: message.into(),
}
}
pub fn timeout(timeout: std::time::Duration) -> Self {
Self::Timeout { timeout }
}
pub fn workflow_not_found(workflow_id: impl Into<String>) -> Self {
Self::WorkflowNotFound {
workflow_id: workflow_id.into(),
}
}
pub fn workflow_already_exists(workflow_id: impl Into<String>) -> Self {
Self::WorkflowAlreadyExists {
workflow_id: workflow_id.into(),
run_id: None,
}
}
pub fn workflow_already_exists_with_run(
workflow_id: impl Into<String>,
run_id: impl Into<String>,
) -> Self {
Self::WorkflowAlreadyExists {
workflow_id: workflow_id.into(),
run_id: Some(run_id.into()),
}
}
pub fn request_failed(reason: impl Into<String>) -> Self {
Self::RequestFailed(reason.into())
}
pub fn serialization(reason: impl Into<String>) -> Self {
Self::Serialization(reason.into())
}
pub fn deserialization(reason: impl Into<String>) -> Self {
Self::Deserialization(reason.into())
}
}
impl WorkerError {
pub fn connection_failed(url: impl Into<String>, reason: impl Into<String>) -> Self {
Self::ConnectionFailed {
url: url.into(),
reason: reason.into(),
}
}
pub fn handler_not_found(handler_type: impl Into<String>, name: impl Into<String>) -> Self {
Self::HandlerNotFound {
handler_type: handler_type.into(),
name: name.into(),
}
}
pub fn invalid_configuration(reason: impl Into<String>) -> Self {
Self::InvalidConfiguration(reason.into())
}
pub fn startup_failed(reason: impl Into<String>) -> Self {
Self::StartupFailed(reason.into())
}
pub fn polling_error(reason: impl Into<String>) -> Self {
Self::PollingError(reason.into())
}
pub fn resource_exhausted(resource: impl Into<String>) -> Self {
Self::ResourceExhausted {
resource: resource.into(),
}
}
pub fn shutdown_timeout(timeout: std::time::Duration) -> Self {
Self::ShutdownTimeout { timeout }
}
pub fn task_queue_not_found(queue: impl Into<String>) -> Self {
Self::TaskQueueNotFound {
queue: queue.into(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_suspend_only_true_for_suspended() {
let suspended = Error::Workflow(WorkflowError::Suspended {
reason: "Task 'charge' scheduled for execution".to_string(),
pending_operations: vec!["charge_0".to_string()],
});
assert!(suspended.is_suspend());
let failed = Error::Workflow(WorkflowError::task_failed("charge", 3, "declined"));
assert!(!failed.is_suspend());
let other = Error::Serialization("bad json".to_string());
assert!(!other.is_suspend());
}
#[test]
fn test_workflow_error_display() {
let err = WorkflowError::task_failed("ProcessPayment", 3, "Network timeout");
assert_eq!(
err.to_string(),
"Task 'ProcessPayment' failed after 3 attempts: Network timeout"
);
}
#[test]
fn test_task_error_display() {
let err = TaskError::execution_failed("Database connection lost");
assert_eq!(
err.to_string(),
"Task execution failed: Database connection lost"
);
}
#[test]
fn test_client_error_display() {
let err = ClientError::server_error(500, "Internal server error");
assert_eq!(
err.to_string(),
"Server error (status 500): Internal server error"
);
}
#[test]
fn test_service_error_display() {
let err = WorkerError::handler_not_found("workflow", "OrderWorkflow");
assert_eq!(
err.to_string(),
"No handler registered for 'workflow' with name 'OrderWorkflow'"
);
}
#[test]
fn test_error_conversion() {
let workflow_err = WorkflowError::Canceled;
let err: Error = workflow_err.into();
assert!(matches!(err, Error::Workflow(_)));
}
#[test]
fn test_result_type() {
let ok_result: Result<i32> = Ok(42);
assert!(ok_result.is_ok());
let err_result: Result<i32> = Err(Error::Configuration("Invalid config".to_string()));
assert!(err_result.is_err());
}
#[test]
fn test_error_is_retryable() {
let err = Error::Client(ClientError::ConnectionFailed {
url: "http://test".to_string(),
reason: "timeout".to_string(),
});
assert!(err.is_retryable());
let err = Error::Client(ClientError::Timeout {
timeout: std::time::Duration::from_secs(30),
});
assert!(err.is_retryable());
let err = Error::Client(ClientError::ServerError {
status: 503,
message: "Service unavailable".to_string(),
});
assert!(err.is_retryable());
let err = Error::Configuration("Invalid config".to_string());
assert!(!err.is_retryable());
let err = Error::Client(ClientError::ServerError {
status: 400,
message: "Bad request".to_string(),
});
assert!(!err.is_retryable());
}
#[test]
fn test_error_is_permanent() {
let err = Error::Configuration("Invalid config".to_string());
assert!(err.is_permanent());
let err = Error::Client(ClientError::AuthenticationFailed(
"Invalid token".to_string(),
));
assert!(err.is_permanent());
let err = Error::Workflow(WorkflowError::NonDeterministic(
"Replay mismatch".to_string(),
));
assert!(err.is_permanent());
let err = Error::Client(ClientError::ServerError {
status: 404,
message: "Not found".to_string(),
});
assert!(err.is_permanent());
let err = Error::Client(ClientError::Timeout {
timeout: std::time::Duration::from_secs(30),
});
assert!(!err.is_permanent());
}
#[test]
fn test_error_with_context() {
let err = Error::Configuration("Invalid port".to_string());
let err_with_ctx = err.with_context("Failed to start server");
assert!(err_with_ctx.to_string().contains("Failed to start server"));
assert!(err_with_ctx.to_string().contains("Invalid port"));
}
#[test]
fn test_workflow_error_constructors() {
let err = WorkflowError::not_found("wf-123");
assert!(matches!(err, WorkflowError::NotFound { .. }));
let err = WorkflowError::timeout(std::time::Duration::from_secs(30));
assert!(matches!(err, WorkflowError::Timeout { .. }));
let err = WorkflowError::non_deterministic("mismatch");
assert!(matches!(err, WorkflowError::NonDeterministic(_)));
}
#[test]
fn test_task_error_constructors() {
let err = TaskError::not_found("task-456");
assert!(matches!(err, TaskError::NotFound { .. }));
let err = TaskError::timeout(std::time::Duration::from_secs(10));
assert!(matches!(err, TaskError::Timeout { .. }));
let err = TaskError::retry_limit_exceeded(5);
assert!(matches!(err, TaskError::RetryLimitExceeded { attempts: 5 }));
}
#[test]
fn a_refused_start_keeps_the_run_in_the_way() {
let err: Error =
orcher_sdk_core::error::Error::workflow_already_exists_with_run("order-7", "run-7")
.into();
assert_eq!(err.code(), ErrorCode::WorkflowAlreadyExists);
match err {
Error::Client(ClientError::WorkflowAlreadyExists {
workflow_id,
run_id,
}) => {
assert_eq!(workflow_id, "order-7");
assert_eq!(run_id.as_deref(), Some("run-7"));
}
other => panic!("expected WorkflowAlreadyExists, got {other:?}"),
}
}
#[test]
fn test_client_error_constructors() {
let err = ClientError::workflow_not_found("wf-789");
assert!(matches!(err, ClientError::WorkflowNotFound { .. }));
let err = ClientError::workflow_already_exists("wf-789");
assert!(matches!(err, ClientError::WorkflowAlreadyExists { .. }));
let err = ClientError::request_failed("network error");
assert!(matches!(err, ClientError::RequestFailed(_)));
}
#[test]
fn test_service_error_constructors() {
let err = WorkerError::polling_error("connection lost");
assert!(matches!(err, WorkerError::PollingError(_)));
let err = WorkerError::resource_exhausted("memory");
assert!(matches!(err, WorkerError::ResourceExhausted { .. }));
let err = WorkerError::task_queue_not_found("orders");
assert!(matches!(err, WorkerError::TaskQueueNotFound { .. }));
}
#[test]
fn test_sdk_core_error_conversion() {
use orcher_sdk_core::error::Error as CoreError;
let core_err = CoreError::workflow_not_found("wf-123");
let sdk_err: Error = core_err.into();
assert!(matches!(
sdk_err,
Error::Workflow(WorkflowError::NotFound { .. })
));
let core_err = CoreError::task_execution_failed("task-456", "failed");
let sdk_err: Error = core_err.into();
assert!(matches!(
sdk_err,
Error::Task(TaskError::ExecutionFailed(_))
));
let core_err = CoreError::connection("timeout");
let sdk_err: Error = core_err.into();
assert!(matches!(
sdk_err,
Error::Client(ClientError::ConnectionFailed { .. })
));
let core_err = CoreError::determinism_violation("replay mismatch");
let sdk_err: Error = core_err.into();
assert!(matches!(
sdk_err,
Error::Workflow(WorkflowError::NonDeterministic(_))
));
}
}
#[cfg(test)]
mod typed_client_error_tests {
use super::*;
use orcher_sdk_core::error::Error as CoreError;
#[test]
fn a_missing_workflow_maps_to_a_typed_not_found() {
let err: Error = CoreError::workflow_not_found("wf-1").into();
assert!(
matches!(err, Error::Workflow(WorkflowError::NotFound { .. })),
"expected a typed NotFound, got {err:?}"
);
}
#[test]
fn a_missing_workflow_is_not_retryable() {
let err: Error = CoreError::workflow_not_found("wf-1").into();
assert!(!err.is_retryable(), "a missing workflow was retried");
}
#[test]
fn transient_grpc_failures_are_retryable() {
for code in [
tonic::Code::Unavailable,
tonic::Code::DeadlineExceeded,
tonic::Code::ResourceExhausted,
] {
let err: Error = CoreError::GrpcStatus(tonic::Status::new(code, "boom")).into();
assert!(
err.is_retryable(),
"{code:?} should be retryable but was classified permanent"
);
}
}
#[test]
fn permanent_grpc_failures_are_not_retryable() {
for code in [
tonic::Code::NotFound,
tonic::Code::InvalidArgument,
tonic::Code::PermissionDenied,
tonic::Code::Unauthenticated,
tonic::Code::AlreadyExists,
] {
let err: Error = CoreError::GrpcStatus(tonic::Status::new(code, "nope")).into();
assert!(
!err.is_retryable(),
"{code:?} should be permanent but was classified retryable"
);
}
}
#[test]
fn grpc_status_is_translated_for_the_caller() {
let err: Error =
CoreError::GrpcStatus(tonic::Status::new(tonic::Code::NotFound, "missing")).into();
match err {
Error::Client(ClientError::ServerError { status, .. }) => assert_eq!(status, 404),
other => panic!("expected ServerError, got {other:?}"),
}
}
}