use std::error::Error;
use std::fmt;
pub(crate) type Source = Box<dyn Error + Send + Sync + 'static>;
const CHAIN_WALK_LIMIT: usize = 11;
pub(crate) fn write_chain(
f: &mut fmt::Formatter<'_>,
frame: &dyn fmt::Display,
mut source: Option<&(dyn Error + 'static)>,
) -> fmt::Result {
write!(f, "{frame}")?;
while let Some(s) = source {
write!(f, ": {s}")?;
source = s.source();
}
Ok(())
}
pub(crate) fn chain_string(err: &(dyn Error + 'static)) -> String {
let mut frames = Vec::new();
let mut link = Some(err);
while let Some(e) = link {
if !e.is::<TypedError>() {
frames.push(e.to_string());
}
link = e.source();
}
frames.join(": ")
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct WireError {
error_type: Option<String>,
error_message: Option<String>,
error_data: Option<String>,
stack_trace: Vec<String>,
}
impl WireError {
pub(crate) fn new(
error_type: Option<impl Into<String>>,
error_message: Option<impl Into<String>>,
) -> Self {
Self {
error_type: error_type.map(Into::into),
error_message: error_message.map(Into::into),
error_data: None,
stack_trace: Vec::new(),
}
}
pub(crate) fn with_error_message(mut self, error_message: Option<impl Into<String>>) -> Self {
self.error_message = error_message.map(Into::into);
self
}
pub(crate) fn with_error_data(mut self, error_data: Option<impl Into<String>>) -> Self {
self.error_data = error_data.map(Into::into);
self
}
pub(crate) fn with_stack_trace(mut self, stack_trace: Vec<String>) -> Self {
self.stack_trace = stack_trace;
self
}
pub fn error_type(&self) -> Option<&str> {
self.error_type.as_deref()
}
pub fn error_message(&self) -> Option<&str> {
self.error_message.as_deref()
}
pub fn error_data(&self) -> Option<&str> {
self.error_data.as_deref()
}
pub fn stack_trace(&self) -> &[String] {
&self.stack_trace
}
pub(crate) fn to_error_object(&self) -> aws_sdk_lambda::types::ErrorObject {
let mut builder = aws_sdk_lambda::types::ErrorObject::builder();
if let Some(t) = self.error_type() {
builder = builder.error_type(t);
}
if let Some(m) = self.error_message() {
builder = builder.error_message(m);
}
if let Some(d) = self.error_data() {
builder = builder.error_data(d);
}
for frame in self.stack_trace() {
builder = builder.stack_trace(frame);
}
builder.build()
}
}
impl fmt::Display for WireError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match (self.error_type.as_deref(), self.error_message.as_deref()) {
(Some(t), Some(m)) => write!(f, "{t}: {m}"),
(None, Some(m)) => write!(f, "{m}"),
(Some(t), None) => write!(f, "{t}"),
(None, None) => write!(f, "unknown error"),
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ReplayedFailure {
wire: WireError,
}
impl ReplayedFailure {
pub(crate) fn new(wire: WireError) -> Self {
Self { wire }
}
pub(crate) fn source_from(wire: WireError) -> Source {
Box::new(Self::new(wire))
}
pub fn error_type(&self) -> Option<&str> {
self.wire.error_type()
}
pub fn error_message(&self) -> Option<&str> {
self.wire.error_message()
}
pub fn wire(&self) -> &WireError {
&self.wire
}
}
impl fmt::Display for ReplayedFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match (self.wire.error_message(), self.wire.error_type()) {
(Some(m), _) => write!(f, "{m}"),
(None, Some(t)) => write!(f, "{t}"),
(None, None) => write!(f, "unknown error"),
}
}
}
impl Error for ReplayedFailure {}
#[derive(Debug)]
pub(crate) struct ContextualError {
context: String,
source: Source,
}
impl ContextualError {
pub(crate) fn source_from(context: impl Into<String>, source: impl Into<Source>) -> Source {
Box::new(Self {
context: context.into(),
source: source.into(),
})
}
}
impl fmt::Display for ContextualError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write_chain(f, &self.context, self.source())
} else {
write!(f, "{}", self.context)
}
}
}
impl Error for ContextualError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&*self.source as &(dyn Error + 'static))
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct TypedError {
error_type: String,
inner: Source,
error_data: Option<String>,
}
impl TypedError {
#[must_use]
pub fn new<E: Error + Send + Sync + 'static>(err: E) -> Self {
Self {
error_type: short_type_name(std::any::type_name::<E>()),
inner: Box::new(err),
error_data: None,
}
}
#[must_use]
pub fn with_type(error_type: impl Into<String>, err: impl Into<Source>) -> Self {
Self {
error_type: error_type.into(),
inner: err.into(),
error_data: None,
}
}
#[must_use]
pub fn with_error_data(mut self, error_data: impl Into<String>) -> Self {
self.error_data = Some(error_data.into());
self
}
pub fn error_data(&self) -> Option<&str> {
self.error_data.as_deref()
}
pub fn error_type(&self) -> &str {
&self.error_type
}
pub fn inner(&self) -> &(dyn Error + 'static) {
&*self.inner
}
}
impl fmt::Display for TypedError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write_chain(f, &self.error_type, self.source())
} else {
write!(f, "{}", self.error_type)
}
}
}
impl Error for TypedError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&*self.inner as &(dyn Error + 'static))
}
}
fn short_type_name(full: &str) -> String {
let mut result = String::with_capacity(full.len());
let mut segment = String::new();
for c in full.chars() {
match c {
':' => segment.clear(),
'<' | '>' | ',' | ' ' | '(' | ')' | '[' | ']' | '&' | ';' => {
result.push_str(&segment);
segment.clear();
result.push(c);
}
_ => segment.push(c),
}
}
result.push_str(&segment);
result
}
pub(crate) fn wire_error_for(err: &(dyn Error + 'static), fallback_type: &str) -> WireError {
let error_type = if let Some(op) = err.downcast_ref::<OperationError>() {
op.wire()
.and_then(WireError::error_type)
.map(str::to_owned)
.or_else(|| typed_error_name(err))
.unwrap_or_else(|| op.kind().wire_type_name().to_owned())
} else if let Some(replayed) = err.downcast_ref::<ReplayedFailure>() {
replayed.error_type().unwrap_or(fallback_type).to_owned()
} else {
typed_error_name(err).unwrap_or_else(|| fallback_type.to_owned())
};
wire_error_with_type(err, &error_type)
}
fn typed_error_name(err: &(dyn Error + 'static)) -> Option<String> {
let mut link: Option<&(dyn Error + 'static)> = Some(err);
for _ in 0..CHAIN_WALK_LIMIT {
let e = link?;
if let Some(typed) = e.downcast_ref::<TypedError>() {
return Some(typed.error_type().to_owned());
}
link = e.source();
}
None
}
pub(crate) fn wire_error_with_type(err: &(dyn Error + 'static), error_type: &str) -> WireError {
let mut error_data = None;
let mut stack_trace = Vec::new();
let mut link: Option<&(dyn Error + 'static)> = Some(err);
let mut walked = 0;
while let Some(e) = link {
if walked >= CHAIN_WALK_LIMIT {
break;
}
if let Some(w) = wire_identity(e) {
if error_data.is_none() {
error_data = w.error_data().map(str::to_owned);
}
if stack_trace.is_empty() {
stack_trace = w.stack_trace().to_vec();
}
} else if let Some(typed) = e.downcast_ref::<TypedError>()
&& error_data.is_none()
{
error_data = typed.error_data().map(str::to_owned);
}
if error_data.is_some() && !stack_trace.is_empty() {
break;
}
link = e.source();
walked += 1;
}
WireError::new(Some(error_type), Some(wire_message(err)))
.with_error_data(error_data)
.with_stack_trace(stack_trace)
}
pub(crate) fn wire_message(err: &(dyn Error + 'static)) -> String {
let mut link = err;
for _ in 0..CHAIN_WALK_LIMIT {
if let Some(wire) = wire_identity(link) {
return wire
.error_message()
.map_or_else(|| chain_string(err), str::to_owned);
}
if !is_propagation_carrier(link) {
break;
}
match link.source() {
Some(source) => link = source,
None => break,
}
}
chain_string(err)
}
fn is_propagation_carrier(err: &(dyn Error + 'static)) -> bool {
err.is::<OperationError>()
|| err.is::<StepError>()
|| err.is::<WaitError>()
|| err.is::<InvokeError>()
|| err.is::<CallbackError>()
|| err.is::<WaitForConditionError>()
|| err.is::<ChildContextError>()
|| err.is::<CombinatorError>()
|| err.is::<ChildFnError>()
|| err.is::<ContextualError>()
|| err.is::<TypedError>()
}
pub(crate) const CHECKPOINT_INVOCATION_FAILED_ERROR_TYPE: &str =
"CheckpointUnrecoverableInvocationError";
pub(crate) const SERDES_FAILED_ERROR_TYPE: &str = "SerdesFailedError";
pub(crate) const EXECUTION_CLIENT_ERROR_TYPE: &str = "DurableExecutionClientError";
pub(crate) const SERIALIZATION_FAILED_ERROR_TYPE: &str = "SerializationError";
pub(crate) fn serialization_failure_wire(err: &(dyn Error + 'static)) -> WireError {
wire_error_with_type(err, SERIALIZATION_FAILED_ERROR_TYPE)
}
pub(crate) const WFC_EXHAUSTED_ERROR_TYPE: &str = "WaitForCondition.MaxChecksExceeded";
pub(crate) const CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE: &str =
"CheckpointUnrecoverableExecutionError";
pub(crate) fn checkpoint_execution_failure_wire(
err: &crate::client::ExecutionClientError,
) -> WireError {
WireError::new(
Some(CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE),
Some(format!(
"[Unrecoverable Execution] Checkpoint failed: {}",
crate::client::client_error_record_message(err)
)),
)
}
pub(crate) fn checkpoint_invocation_failure_message(
err: &crate::client::ExecutionClientError,
) -> String {
format!(
"[Unrecoverable Invocation] Checkpoint failed: {}",
crate::client::client_error_record_message(err)
)
}
fn wire_identity<'a>(err: &'a (dyn Error + 'static)) -> Option<&'a WireError> {
if let Some(op) = err.downcast_ref::<OperationError>() {
return op.wire();
}
if let Some(replayed) = err.downcast_ref::<ReplayedFailure>() {
return Some(replayed.wire());
}
None
}
#[derive(Debug)]
#[non_exhaustive]
pub struct OperationError {
kind: OperationErrorKind,
context: Option<Box<OperationContext>>,
}
#[derive(Debug, Default)]
struct OperationContext {
operation_id: Option<String>,
status: Option<String>,
wire: Option<WireError>,
}
impl OperationError {
pub fn kind(&self) -> &OperationErrorKind {
&self.kind
}
pub fn operation_id(&self) -> Option<&str> {
self.context.as_ref()?.operation_id.as_deref()
}
pub fn status(&self) -> Option<&str> {
self.context.as_ref()?.status.as_deref()
}
pub fn wire(&self) -> Option<&WireError> {
self.context.as_ref()?.wire.as_ref()
}
pub(crate) fn from_kind(kind: OperationErrorKind) -> Self {
Self {
kind,
context: None,
}
}
pub(crate) fn with_operation(
mut self,
operation_id: impl Into<String>,
status: impl Into<String>,
) -> Self {
let context = self.context.get_or_insert_default();
context.operation_id = Some(operation_id.into());
context.status = Some(status.into());
self
}
pub(crate) fn with_wire(mut self, wire: WireError) -> Self {
self.context.get_or_insert_default().wire = Some(wire);
self
}
#[doc(hidden)]
#[must_use]
pub fn __test_error() -> Self {
Self::from_kind(OperationErrorKind::Step(StepError::new(
StepErrorKind::ExecutionFailed,
Some(Source::from("test")),
)))
}
fn family(&self) -> &'static str {
match &self.kind {
OperationErrorKind::Step(_) => "step",
OperationErrorKind::Wait(_) => "wait",
OperationErrorKind::Invoke(_) => "invoke",
OperationErrorKind::Callback(_) => "callback",
OperationErrorKind::WaitForCondition(_) => "wait_for_condition",
OperationErrorKind::ChildContext(_) => "child_context",
OperationErrorKind::Combinator(_) => "combinator",
OperationErrorKind::NonDeterministicExecution(_) => "non_deterministic_execution",
}
}
}
impl fmt::Display for OperationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
struct Frame<'a>(&'a OperationError);
impl fmt::Display for Frame<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "operation error: {}", self.0.family())
}
}
if f.alternate() {
write_chain(f, &Frame(self), self.source())
} else {
write!(f, "{}", Frame(self))
}
}
}
impl Error for OperationError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match &self.kind {
OperationErrorKind::Step(e) => Some(e),
OperationErrorKind::Wait(e) => Some(e),
OperationErrorKind::Invoke(e) => Some(e),
OperationErrorKind::Callback(e) => Some(e),
OperationErrorKind::WaitForCondition(e) => Some(e),
OperationErrorKind::ChildContext(e) => Some(e),
OperationErrorKind::Combinator(e) => Some(e),
OperationErrorKind::NonDeterministicExecution(e) => Some(e),
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum OperationErrorKind {
Step(StepError),
Wait(WaitError),
Invoke(InvokeError),
Callback(CallbackError),
WaitForCondition(WaitForConditionError),
ChildContext(ChildContextError),
Combinator(CombinatorError),
NonDeterministicExecution(NonDeterministicExecutionError),
}
impl OperationErrorKind {
pub(crate) fn wire_type_name(&self) -> &'static str {
match self {
Self::Step(_) => "StepError",
Self::Wait(_) => "WaitError",
Self::Invoke(_) => "InvokeError",
Self::Callback(_) => "CallbackError",
Self::WaitForCondition(_) => "WaitForConditionError",
Self::ChildContext(_) => "ChildContextError",
Self::Combinator(_) => "PromiseCombinatorError",
Self::NonDeterministicExecution(_) => "NonDeterministicExecutionError",
}
}
}
impl fmt::Display for OperationErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Step(e) => write!(f, "step: {e}"),
Self::Wait(e) => write!(f, "wait: {e}"),
Self::Invoke(e) => write!(f, "invoke: {e}"),
Self::Callback(e) => write!(f, "callback: {e}"),
Self::WaitForCondition(e) => write!(f, "wait_for_condition: {e}"),
Self::ChildContext(e) => write!(f, "child_context: {e}"),
Self::Combinator(e) => write!(f, "combinator: {e}"),
Self::NonDeterministicExecution(e) => write!(f, "non_deterministic_execution: {e}"),
}
}
}
pub(crate) const STEP_INTERRUPTED_MESSAGE: &str = "The step execution process was initiated but failed to reach completion due to an interruption.";
#[derive(Debug)]
#[non_exhaustive]
pub struct StepError {
kind: StepErrorKind,
source: Option<Source>,
}
impl StepError {
pub fn kind(&self) -> &StepErrorKind {
&self.kind
}
#[must_use]
pub fn execution_failed(source: impl Into<crate::BoxError>) -> Self {
Self::new(StepErrorKind::ExecutionFailed, Some(source.into()))
}
#[must_use]
pub fn interrupted() -> Self {
Self::new(
StepErrorKind::Interrupted,
Some(STEP_INTERRUPTED_MESSAGE.into()),
)
}
pub(crate) fn new(kind: StepErrorKind, source: Option<Source>) -> Self {
Self { kind, source }
}
pub(crate) fn into_source(self) -> Option<Source> {
self.source
}
}
impl fmt::Display for StepError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write_chain(f, &self.kind, self.source())
} else {
write!(f, "{}", self.kind)
}
}
}
impl Error for StepError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_deref().map(|s| s as &(dyn Error + 'static))
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum StepErrorKind {
#[non_exhaustive]
ExecutionFailed,
#[non_exhaustive]
SerializationFailed,
#[non_exhaustive]
Interrupted,
}
impl fmt::Display for StepErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ExecutionFailed => write!(f, "execution failed"),
Self::SerializationFailed => write!(f, "serialization failed"),
Self::Interrupted => write!(f, "step interrupted"),
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct WaitError {
kind: WaitErrorKind,
source: Option<Source>,
}
impl WaitError {
pub fn kind(&self) -> &WaitErrorKind {
&self.kind
}
pub(crate) fn new(kind: WaitErrorKind, source: Option<Source>) -> Self {
Self { kind, source }
}
}
impl fmt::Display for WaitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write_chain(f, &self.kind, self.source())
} else {
write!(f, "{}", self.kind)
}
}
}
impl Error for WaitError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_deref().map(|s| s as &(dyn Error + 'static))
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum WaitErrorKind {
UnexpectedStatus(UnexpectedStatus),
}
impl fmt::Display for WaitErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnexpectedStatus(details) => write!(f, "{details}"),
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct UnexpectedStatus {
status: String,
}
impl UnexpectedStatus {
pub(crate) fn new(status: impl Into<String>) -> Self {
Self {
status: status.into(),
}
}
pub fn status(&self) -> &str {
&self.status
}
}
impl fmt::Display for UnexpectedStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "unexpected checkpointed status: {}", self.status)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct InvokeError {
kind: InvokeErrorKind,
source: Option<Source>,
}
impl InvokeError {
pub fn kind(&self) -> &InvokeErrorKind {
&self.kind
}
pub(crate) fn new(kind: InvokeErrorKind, source: Option<Source>) -> Self {
Self { kind, source }
}
}
impl fmt::Display for InvokeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write_chain(f, &self.kind, self.source())
} else {
write!(f, "{}", self.kind)
}
}
}
impl Error for InvokeError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_deref().map(|s| s as &(dyn Error + 'static))
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum InvokeErrorKind {
#[non_exhaustive]
FunctionFailed,
#[non_exhaustive]
SerializationFailed,
}
impl fmt::Display for InvokeErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::FunctionFailed => write!(f, "function failed"),
Self::SerializationFailed => write!(f, "serialization failed"),
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct CallbackError {
kind: CallbackErrorKind,
source: Option<Source>,
}
impl CallbackError {
pub fn kind(&self) -> &CallbackErrorKind {
&self.kind
}
pub(crate) fn new(kind: CallbackErrorKind, source: Option<Source>) -> Self {
Self { kind, source }
}
}
impl fmt::Display for CallbackError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write_chain(f, &self.kind, self.source())
} else {
write!(f, "{}", self.kind)
}
}
}
impl Error for CallbackError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_deref().map(|s| s as &(dyn Error + 'static))
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum CallbackErrorKind {
#[non_exhaustive]
TimedOut,
#[non_exhaustive]
HeartbeatTimedOut,
#[non_exhaustive]
ExternalFailure,
#[non_exhaustive]
DeserializationFailed,
#[non_exhaustive]
Internal,
#[non_exhaustive]
SubmitterFailed,
}
impl fmt::Display for CallbackErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TimedOut => write!(f, "callback timed out"),
Self::HeartbeatTimedOut => write!(f, "callback heartbeat timed out"),
Self::ExternalFailure => write!(f, "external failure"),
Self::DeserializationFailed => write!(f, "deserialization failed"),
Self::Internal => write!(f, "internal error"),
Self::SubmitterFailed => write!(f, "submitter failed"),
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct WaitForConditionError {
kind: WaitForConditionErrorKind,
source: Option<Source>,
}
impl WaitForConditionError {
pub fn kind(&self) -> &WaitForConditionErrorKind {
&self.kind
}
pub(crate) fn new(kind: WaitForConditionErrorKind, source: Option<Source>) -> Self {
Self { kind, source }
}
}
impl fmt::Display for WaitForConditionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write_chain(f, &self.kind, self.source())
} else {
write!(f, "{}", self.kind)
}
}
}
impl Error for WaitForConditionError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_deref().map(|s| s as &(dyn Error + 'static))
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum WaitForConditionErrorKind {
#[non_exhaustive]
CheckFailed,
MaxChecksExceeded(MaxChecksExceeded),
#[non_exhaustive]
SerializationFailed,
}
impl fmt::Display for WaitForConditionErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::CheckFailed => write!(f, "check failed"),
Self::MaxChecksExceeded(details) => write!(f, "{details}"),
Self::SerializationFailed => write!(f, "serialization failed"),
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct MaxChecksExceeded {
checks: u32,
}
impl MaxChecksExceeded {
pub(crate) fn new(checks: u32) -> Self {
Self { checks }
}
pub fn checks(&self) -> u32 {
self.checks
}
}
impl fmt::Display for MaxChecksExceeded {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "max checks exceeded: {}", self.checks)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct ChildContextError {
kind: ChildContextErrorKind,
source: Option<Source>,
}
impl ChildContextError {
pub fn kind(&self) -> &ChildContextErrorKind {
&self.kind
}
pub(crate) fn new(kind: ChildContextErrorKind, source: Option<Source>) -> Self {
Self { kind, source }
}
}
impl fmt::Display for ChildContextError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write_chain(f, &self.kind, self.source())
} else {
write!(f, "{}", self.kind)
}
}
}
impl Error for ChildContextError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_deref().map(|s| s as &(dyn Error + 'static))
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum ChildContextErrorKind {
#[non_exhaustive]
ChildFailed,
#[non_exhaustive]
Internal,
#[non_exhaustive]
BatchCompletionFailed,
#[non_exhaustive]
NotCompleted,
}
impl fmt::Display for ChildContextErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ChildFailed => write!(f, "child failed"),
Self::Internal => write!(f, "internal error"),
Self::BatchCompletionFailed => write!(f, "batch completed as failed"),
Self::NotCompleted => write!(f, "branch has no result"),
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct CombinatorError {
kind: CombinatorErrorKind,
failures: Vec<Source>,
}
impl CombinatorError {
pub(crate) fn new(kind: CombinatorErrorKind, failures: Vec<Source>) -> Self {
Self { kind, failures }
}
pub fn kind(&self) -> &CombinatorErrorKind {
&self.kind
}
pub fn failures(&self) -> &[Box<dyn Error + Send + Sync + 'static>] {
&self.failures
}
}
impl fmt::Display for CombinatorError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write_chain(f, &self.kind, self.source())
} else {
write!(f, "{}", self.kind)
}
}
}
impl Error for CombinatorError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.failures
.first()
.map(|s| &**s as &(dyn Error + 'static))
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum CombinatorErrorKind {
JoinFailed(JoinFailed),
#[non_exhaustive]
AllFailed,
#[non_exhaustive]
FirstSettledFailed,
#[non_exhaustive]
EmptyInput,
#[non_exhaustive]
Internal,
}
impl fmt::Display for CombinatorErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::JoinFailed(details) => write!(f, "{details}"),
Self::AllFailed => write!(f, "all futures failed"),
Self::FirstSettledFailed => write!(f, "first settled future failed"),
Self::EmptyInput => write!(f, "combinator called with no futures"),
Self::Internal => write!(f, "internal error"),
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct JoinFailed {
failed_index: usize,
}
impl JoinFailed {
pub(crate) fn new(failed_index: usize) -> Self {
Self { failed_index }
}
pub fn failed_index(&self) -> usize {
self.failed_index
}
}
impl fmt::Display for JoinFailed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "join failed at index {}", self.failed_index)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct NonDeterministicExecutionError {
kind: NonDeterministicExecutionErrorKind,
}
impl NonDeterministicExecutionError {
pub fn kind(&self) -> &NonDeterministicExecutionErrorKind {
&self.kind
}
pub(crate) fn from_kind(kind: NonDeterministicExecutionErrorKind) -> Self {
Self { kind }
}
}
impl fmt::Display for NonDeterministicExecutionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.kind)
}
}
impl Error for NonDeterministicExecutionError {}
#[derive(Debug)]
#[non_exhaustive]
pub enum NonDeterministicExecutionErrorKind {
OperationMismatch(OperationMismatch),
UnrecognizedStatus(UnrecognizedStatus),
}
impl fmt::Display for NonDeterministicExecutionErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::OperationMismatch(details) => write!(f, "{details}"),
Self::UnrecognizedStatus(details) => write!(f, "{details}"),
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct OperationMismatch {
wire_id: String,
expected: String,
actual: String,
}
impl OperationMismatch {
pub(crate) fn new(
wire_id: impl Into<String>,
expected: impl Into<String>,
actual: impl Into<String>,
) -> Self {
Self {
wire_id: wire_id.into(),
expected: expected.into(),
actual: actual.into(),
}
}
pub fn wire_id(&self) -> &str {
&self.wire_id
}
pub fn expected(&self) -> &str {
&self.expected
}
pub fn actual(&self) -> &str {
&self.actual
}
}
impl fmt::Display for OperationMismatch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"operation at wire id {} does not match checkpoint: \
expected {}, got {}",
self.wire_id, self.expected, self.actual
)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct UnrecognizedStatus {
wire_id: String,
status: String,
}
impl UnrecognizedStatus {
pub(crate) fn new(wire_id: impl Into<String>, status: impl Into<String>) -> Self {
Self {
wire_id: wire_id.into(),
status: status.into(),
}
}
pub fn wire_id(&self) -> &str {
&self.wire_id
}
pub fn status(&self) -> &str {
&self.status
}
}
impl fmt::Display for UnrecognizedStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"operation at wire id {} replayed with unrecognized status {:?}: \
this SDK version cannot interpret the recorded outcome; \
upgrade the SDK to a version that understands this status",
self.wire_id, self.status
)
}
}
#[derive(Debug)]
pub(crate) struct ChildFnError {
source: Source,
}
impl ChildFnError {
#[must_use]
pub(crate) fn new(source: impl Into<Source>) -> Self {
Self {
source: source.into(),
}
}
pub(crate) fn into_source(self) -> Source {
self.source
}
pub(crate) fn failure_wire(&self) -> WireError {
wire_error_for(&*self.source, "Error")
}
}
impl fmt::Display for ChildFnError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write_chain(f, &"child function error", self.source())
} else {
write!(f, "child function error")
}
}
}
impl Error for ChildFnError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&*self.source as &(dyn Error + 'static))
}
}
impl From<OperationError> for ChildFnError {
fn from(err: OperationError) -> Self {
Self {
source: Box::new(err),
}
}
}
impl From<crate::BoxError> for ChildFnError {
fn from(err: crate::BoxError) -> Self {
Self { source: err }
}
}
const _: () = {
const fn assert_send_sync_static<T: Send + Sync + 'static>() {}
assert_send_sync_static::<OperationError>();
assert_send_sync_static::<OperationErrorKind>();
assert_send_sync_static::<StepError>();
assert_send_sync_static::<StepErrorKind>();
assert_send_sync_static::<WaitError>();
assert_send_sync_static::<WaitErrorKind>();
assert_send_sync_static::<UnexpectedStatus>();
assert_send_sync_static::<InvokeError>();
assert_send_sync_static::<InvokeErrorKind>();
assert_send_sync_static::<CallbackError>();
assert_send_sync_static::<CallbackErrorKind>();
assert_send_sync_static::<WaitForConditionError>();
assert_send_sync_static::<WaitForConditionErrorKind>();
assert_send_sync_static::<MaxChecksExceeded>();
assert_send_sync_static::<ChildContextError>();
assert_send_sync_static::<ChildContextErrorKind>();
assert_send_sync_static::<CombinatorError>();
assert_send_sync_static::<CombinatorErrorKind>();
assert_send_sync_static::<JoinFailed>();
assert_send_sync_static::<NonDeterministicExecutionError>();
assert_send_sync_static::<NonDeterministicExecutionErrorKind>();
assert_send_sync_static::<OperationMismatch>();
assert_send_sync_static::<WireError>();
assert_send_sync_static::<TypedError>();
assert_send_sync_static::<ReplayedFailure>();
assert_send_sync_static::<ContextualError>();
assert_send_sync_static::<ChildFnError>();
assert_send_sync_static::<crate::serdes::FileSystemSerdesError>();
};
#[cfg(test)]
pub(crate) fn recorded_step_error(wire: WireError) -> OperationError {
OperationError::from_kind(OperationErrorKind::Step(StepError::new(
StepErrorKind::ExecutionFailed,
Some(ReplayedFailure::source_from(wire.clone())),
)))
.with_wire(wire)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn checkpoint_invocation_failure_message_is_js_form() {
let err = crate::client::ExecutionClientError::new(
crate::client::ExecutionClientErrorScope::Invocation,
"throttled",
);
assert_eq!(
checkpoint_invocation_failure_message(&err),
"[Unrecoverable Invocation] Checkpoint failed: throttled"
);
}
#[derive(Debug)]
struct UserBoom {
detail: &'static str,
}
impl fmt::Display for UserBoom {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "user boom: {}", self.detail)
}
}
impl Error for UserBoom {}
fn step_error_with_user_source() -> OperationError {
OperationError::from_kind(OperationErrorKind::Step(StepError::new(
StepErrorKind::ExecutionFailed,
Some(Box::new(UserBoom { detail: "flaky" })),
)))
}
fn causal_chain(err: &dyn Error) -> Vec<String> {
let mut chain = vec![err.to_string()];
let mut current: &dyn Error = err;
while let Some(next) = current.source() {
chain.push(next.to_string());
current = next;
}
chain
}
#[test]
fn live_failure_exposes_concrete_error_type_through_source_downcast() {
let err = step_error_with_user_source();
let mut current: Option<&(dyn Error + 'static)> = err.source();
let mut found = None;
while let Some(e) = current {
if let Some(user) = e.downcast_ref::<UserBoom>() {
found = Some(user);
break;
}
current = e.source();
}
let user = found.expect("caller's concrete error must be reachable via source()");
assert_eq!(user.detail, "flaky");
}
#[test]
fn display_writes_one_frame_and_alternate_walks_chain() {
let err = step_error_with_user_source();
let plain = format!("{err}");
assert_eq!(plain, "operation error: step");
let alternate = format!("{err:#}");
assert_eq!(
alternate,
"operation error: step: execution failed: user boom: flaky"
);
}
#[test]
fn walking_source_does_not_repeat_text() {
let err = step_error_with_user_source();
let chain = causal_chain(&err);
assert_eq!(
chain,
vec![
"operation error: step".to_owned(),
"execution failed".to_owned(),
"user boom: flaky".to_owned(),
]
);
for (i, frame) in chain.iter().enumerate() {
for (j, other) in chain.iter().enumerate() {
if i != j {
assert!(
!other.contains(frame.as_str()),
"frame {i} ({frame:?}) repeats inside frame {j} ({other:?})"
);
}
}
}
}
#[test]
fn replayed_failure_carries_wire_fields() {
let wire = WireError::new(Some("NotApproved"), Some("request was denied"))
.with_error_data(Some("{\"code\":42}"));
let err = OperationError::from_kind(OperationErrorKind::Step(StepError::new(
StepErrorKind::ExecutionFailed,
Some(ReplayedFailure::source_from(wire)),
)));
let OperationErrorKind::Step(step_err) = err.kind() else {
unreachable!("constructed as a step error");
};
assert!(matches!(step_err.kind(), StepErrorKind::ExecutionFailed));
let source = Error::source(step_err).expect("replay attaches a source");
let replayed = source
.downcast_ref::<ReplayedFailure>()
.expect("replay source must be a ReplayedFailure");
assert_eq!(replayed.error_type(), Some("NotApproved"));
assert_eq!(replayed.error_message(), Some("request was denied"));
assert_eq!(replayed.wire().error_data(), Some("{\"code\":42}"));
}
#[test]
fn wire_error_for_flattens_chain_once_and_uses_fallback_type() {
let err = step_error_with_user_source();
let wire = wire_error_for(&err, "Error");
assert_eq!(
wire.error_message(),
Some("operation error: step: execution failed: user boom: flaky")
);
assert_eq!(wire.error_type(), Some("StepError"));
assert_eq!(wire.stack_trace(), [] as [String; 0]);
assert_eq!(wire.error_data(), None);
}
#[test]
fn wire_error_passes_through_recorded_frames() {
let err = ContextualError::source_from(
"ctx",
ReplayedFailure::source_from(
WireError::new(Some("T"), Some("m"))
.with_stack_trace(vec!["frame-a".into(), "frame-b".into()]),
),
);
let wire = wire_error_for(&*err, "Error");
assert_eq!(
wire.stack_trace(),
&["frame-a".to_owned(), "frame-b".to_owned()]
);
}
#[test]
fn typed_error_error_data_precedence() {
fn boom() -> UserBoom {
UserBoom { detail: "x" }
}
fn replayed(d: &str) -> Source {
ReplayedFailure::source_from(
WireError::new(Some("Inner"), Some("inner")).with_error_data(Some(d)),
)
}
fn row1() -> Source {
Box::new(TypedError::with_type("PaymentError", boom()).with_error_data("data-a"))
}
fn layered(layers: usize) -> Source {
let mut inner = row1();
for i in 0..layers {
inner = ContextualError::source_from(format!("layer {i}"), inner);
}
inner
}
let rows: Vec<(usize, Source, Option<&str>)> = vec![
(1, row1(), Some("data-a")),
(
2,
Box::new(TypedError::with_type("P", replayed("data-b")).with_error_data("data-a")),
Some("data-a"),
),
(
3,
Box::new(TypedError::with_type("P", replayed("data-b"))),
Some("data-b"),
),
(4, layered(1), Some("data-a")),
(5, Box::new(TypedError::with_type("P", boom())), None),
(6, layered(9), Some("data-a")),
(7, layered(10), Some("data-a")),
(8, layered(11), None),
];
for (row, err, expected) in &rows {
let wire = wire_error_for(&**err, "Error");
assert_eq!(wire.error_data(), *expected, "row {row}");
if *row == 1 {
assert_eq!(wire.error_type(), Some("PaymentError"));
assert!(
!wire.error_message().unwrap_or_default().contains("data-a"),
"the data never appears in the message: {:?}",
wire.error_message()
);
}
}
}
#[test]
fn step_error_constructors_build_strategy_inputs() {
let failed = StepError::execution_failed("throttled");
assert!(matches!(failed.kind(), StepErrorKind::ExecutionFailed));
assert_eq!(
failed.source().map(ToString::to_string).as_deref(),
Some("throttled")
);
let interrupted = StepError::interrupted();
assert!(matches!(interrupted.kind(), StepErrorKind::Interrupted));
assert_eq!(
interrupted.source().map(ToString::to_string).as_deref(),
Some(
"The step execution process was initiated but failed to reach completion due to an interruption."
)
);
}
#[test]
fn wire_error_for_plain_user_error_uses_fallback() {
let err = UserBoom { detail: "plain" };
let wire = wire_error_for(&err, "Error");
assert_eq!(wire.error_type(), Some("Error"));
assert_eq!(wire.error_message(), Some("user boom: plain"));
}
#[test]
fn error_data_survives_child_boundary_via_cause_chain() {
let inner_wire = WireError::new(Some("VendorError"), Some("denied"))
.with_error_data(Some("opaque-payload"));
let inner = OperationError::from_kind(OperationErrorKind::Callback(CallbackError::new(
CallbackErrorKind::ExternalFailure,
Some(ReplayedFailure::source_from(inner_wire.clone())),
)))
.with_wire(inner_wire);
let child_fn = ChildFnError::from(inner);
let wire = child_fn.failure_wire();
assert_eq!(wire.error_data(), Some("opaque-payload"));
assert_eq!(wire.error_data(), Some("opaque-payload"));
}
#[test]
fn wire_error_re_records_replayed_failure_type() {
let recorded = WireError::new(Some("MyDomainError"), Some("åŽŸå› "));
let replayed = ReplayedFailure::new(recorded.clone());
let wire = wire_error_for(&replayed, "Error");
assert_eq!(wire.error_type(), Some("MyDomainError"));
let err = OperationError::from_kind(OperationErrorKind::Step(StepError::new(
StepErrorKind::ExecutionFailed,
Some(ReplayedFailure::source_from(recorded.clone())),
)))
.with_wire(recorded);
let wire = wire_error_for(&err, "Error");
assert_eq!(wire.error_type(), Some("MyDomainError"));
assert_eq!(
err.wire().and_then(WireError::error_type),
Some("MyDomainError")
);
let bare = OperationError::from_kind(OperationErrorKind::Step(StepError::new(
StepErrorKind::ExecutionFailed,
Some(Source::from("plain failure")),
)));
let wire = wire_error_for(&bare, "Error");
assert_eq!(wire.error_type(), Some("StepError"));
}
#[test]
fn step_error_kind_accessor() {
let err = StepError::new(StepErrorKind::ExecutionFailed, Some(Source::from("fail")));
match err.kind() {
StepErrorKind::ExecutionFailed => {}
other => unreachable!("unexpected kind: {other:?}"),
}
}
#[test]
fn operation_mismatch_accessors() {
let details = OperationMismatch::new("abc123", "Step/Step", "Wait/Wait");
assert_eq!(details.wire_id(), "abc123");
assert_eq!(details.expected(), "Step/Step");
assert_eq!(details.actual(), "Wait/Wait");
let err = NonDeterministicExecutionError::from_kind(
NonDeterministicExecutionErrorKind::OperationMismatch(details),
);
assert!(Error::source(&err).is_none());
assert!(err.to_string().contains("abc123"));
}
#[test]
fn combinator_all_failed_keeps_every_loser() {
let losers: Vec<Source> = vec![
Box::new(UserBoom { detail: "a" }),
Box::new(UserBoom { detail: "b" }),
];
let err = CombinatorError::new(CombinatorErrorKind::AllFailed, losers);
assert_eq!(err.failures().len(), 2);
let first = Error::source(&err).expect("has a source");
assert!(first.downcast_ref::<UserBoom>().is_some());
let details: Vec<&str> = err
.failures()
.iter()
.filter_map(|l| l.downcast_ref::<UserBoom>().map(|u| u.detail))
.collect();
assert_eq!(details, vec!["a", "b"]);
}
#[test]
fn combinator_join_failed_keeps_loser_and_index() {
let err = CombinatorError::new(
CombinatorErrorKind::JoinFailed(JoinFailed::new(2)),
vec![Box::new(UserBoom { detail: "loser" })],
);
match err.kind() {
CombinatorErrorKind::JoinFailed(details) => assert_eq!(details.failed_index(), 2),
other => unreachable!("unexpected kind: {other:?}"),
}
let source = Error::source(&err).expect("loser preserved");
assert!(source.downcast_ref::<UserBoom>().is_some());
}
#[test]
fn child_fn_error_preserves_operation_error() {
let op = step_error_with_user_source();
let child_err = ChildFnError::from(op);
let source = Error::source(&child_err).expect("carries the error");
assert!(source.downcast_ref::<OperationError>().is_some());
assert_eq!(child_err.to_string(), "child function error");
assert!(format!("{child_err:#}").contains("user boom: flaky"));
}
#[test]
fn every_operation_family_displays_its_frame() {
let cases: Vec<(OperationError, &str)> = vec![
(
OperationError::from_kind(OperationErrorKind::Step(StepError::new(
StepErrorKind::ExecutionFailed,
None,
))),
"step",
),
(
OperationError::from_kind(OperationErrorKind::Wait(WaitError::new(
WaitErrorKind::UnexpectedStatus(UnexpectedStatus::new("Failed")),
None,
))),
"wait",
),
(
OperationError::from_kind(OperationErrorKind::Invoke(InvokeError::new(
InvokeErrorKind::FunctionFailed,
None,
))),
"invoke",
),
(
OperationError::from_kind(OperationErrorKind::Callback(CallbackError::new(
CallbackErrorKind::TimedOut,
None,
))),
"callback",
),
(
OperationError::from_kind(OperationErrorKind::WaitForCondition(
WaitForConditionError::new(
WaitForConditionErrorKind::MaxChecksExceeded(MaxChecksExceeded::new(2)),
None,
),
)),
"wait_for_condition",
),
(
OperationError::from_kind(OperationErrorKind::ChildContext(
ChildContextError::new(ChildContextErrorKind::ChildFailed, None),
)),
"child_context",
),
(
OperationError::from_kind(OperationErrorKind::Combinator(CombinatorError::new(
CombinatorErrorKind::Internal,
vec![Box::new(UserBoom { detail: "x" })],
))),
"combinator",
),
(
OperationError::from_kind(OperationErrorKind::NonDeterministicExecution(
NonDeterministicExecutionError::from_kind(
NonDeterministicExecutionErrorKind::OperationMismatch(
OperationMismatch::new("abc123", "Step/Step", "Wait/Wait"),
),
),
)),
"non_deterministic_execution",
),
];
for (err, family) in &cases {
assert_eq!(format!("{err}"), format!("operation error: {family}"));
let chain = causal_chain(err);
for (i, frame) in chain.iter().enumerate() {
for (j, other) in chain.iter().enumerate() {
if i != j {
assert!(
!other.contains(frame.as_str()),
"family {family}: frame {i} repeats in frame {j}: {chain:?}"
);
}
}
}
}
}
#[test]
fn callback_submitter_failed_displays_its_kind() {
let err = CallbackError::new(
CallbackErrorKind::SubmitterFailed,
Some(Source::from("submission failed")),
);
assert_eq!(err.to_string(), "submitter failed");
assert_eq!(format!("{err:#}"), "submitter failed: submission failed");
}
#[test]
fn callback_error_graded_split() {
let timed_out = CallbackError::new(CallbackErrorKind::TimedOut, None);
assert!(matches!(timed_out.kind(), CallbackErrorKind::TimedOut));
let heartbeat = CallbackError::new(CallbackErrorKind::HeartbeatTimedOut, None);
assert!(matches!(
heartbeat.kind(),
CallbackErrorKind::HeartbeatTimedOut
));
let wire = WireError::new(Some("UserError"), Some("denied"));
let external = CallbackError::new(
CallbackErrorKind::ExternalFailure,
Some(ReplayedFailure::source_from(wire)),
);
assert!(matches!(
external.kind(),
CallbackErrorKind::ExternalFailure
));
let source = Error::source(&external).expect("external carries wire source");
let replayed = source.downcast_ref::<ReplayedFailure>().expect("replayed");
assert_eq!(replayed.error_type(), Some("UserError"));
let internal = CallbackError::new(CallbackErrorKind::Internal, Some(Source::from("oops")));
assert!(matches!(internal.kind(), CallbackErrorKind::Internal));
}
#[test]
fn operation_context_is_reachable() {
let wire = WireError::new(Some("StepError"), Some("execution failed: boom"));
let err = step_error_with_user_source()
.with_operation("abc123", "FAILED")
.with_wire(wire);
assert_eq!(err.operation_id(), Some("abc123"));
assert_eq!(err.status(), Some("FAILED"));
assert_eq!(
err.wire().and_then(WireError::error_type),
Some("StepError")
);
}
#[test]
fn typed_error_names_the_users_type_on_the_wire() {
let err = TypedError::new(UserBoom { detail: "typed" });
assert_eq!(err.error_type(), "UserBoom");
let wire = wire_error_for(&err, "Error");
assert_eq!(wire.error_type(), Some("UserBoom"));
assert_eq!(wire.error_message(), Some("user boom: typed"));
let child =
ChildFnError::new(Box::new(TypedError::new(UserBoom { detail: "deep" })) as Source);
let wire = child.failure_wire();
assert_eq!(wire.error_type(), Some("UserBoom"));
}
#[test]
fn typed_error_keeps_concrete_error_downcastable() {
let err = TypedError::with_type("TransientError", UserBoom { detail: "x" });
let source = Error::source(&err).expect("wraps the error");
assert!(source.downcast_ref::<UserBoom>().is_some());
assert_eq!(err.to_string(), "TransientError");
assert_eq!(format!("{err:#}"), "TransientError: user boom: x");
}
#[test]
fn short_type_name_strips_module_paths() {
assert_eq!(
short_type_name("my_crate::errors::TransientError"),
"TransientError"
);
assert_eq!(short_type_name("TransientError"), "TransientError");
assert_eq!(
short_type_name("wrapper::Holder<inner::Thing, other::T>"),
"Holder<Thing, T>"
);
}
#[test]
fn contextual_error_adds_frame_without_flattening() {
let source = ContextualError::source_from("checkpoint succeed", UserBoom { detail: "io" });
assert_eq!(source.to_string(), "checkpoint succeed");
let inner = source.source().expect("keeps cause");
assert_eq!(inner.to_string(), "user boom: io");
}
fn recorded_step() -> OperationError {
recorded_step_error(WireError::new(Some("InnerType"), Some("inner")))
}
const RECORDED_STEP_CHAIN: &str = "operation error: step: execution failed: inner";
#[test]
fn recorded_step_flattens_to_its_frames() {
assert_eq!(chain_string(&recorded_step()), RECORDED_STEP_CHAIN);
}
#[test]
fn wire_message_uses_the_first_record() {
assert_eq!(wire_message(&recorded_step()), "inner");
let contextual = ContextualError::source_from(
"ctx",
ReplayedFailure::source_from(WireError::new(Some("T"), Some("m"))),
);
assert_eq!(wire_message(&*contextual), "m");
let outer_with_message =
OperationError::from_kind(OperationErrorKind::ChildContext(ChildContextError::new(
ChildContextErrorKind::ChildFailed,
Some(Box::new(recorded_step())),
)))
.with_wire(WireError::new(Some("OuterType"), Some("outer")));
assert_eq!(wire_message(&outer_with_message), "outer");
let outer_without_message =
OperationError::from_kind(OperationErrorKind::ChildContext(ChildContextError::new(
ChildContextErrorKind::ChildFailed,
Some(Box::new(recorded_step())),
)))
.with_wire(WireError::new(Some("OuterType"), None::<String>));
assert_eq!(
wire_message(&outer_without_message),
"operation error: child_context: child failed: operation error: step: execution failed: inner"
);
let replayed_without_message =
ReplayedFailure::new(WireError::new(Some("T"), None::<String>));
assert_eq!(wire_message(&replayed_without_message), "T");
let empty = recorded_step_error(WireError::new(Some("T"), Some("")));
assert_eq!(wire_message(&empty), "");
}
#[derive(Debug)]
struct Wrapper(Source);
impl fmt::Display for Wrapper {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "wrapper")
}
}
impl Error for Wrapper {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&*self.0 as &(dyn Error + 'static))
}
}
#[test]
#[expect(clippy::too_many_lines)] fn wire_message_walks_only_transparent_carriers() {
let boxed = || -> Source { Box::new(recorded_step()) };
let carriers: Vec<(&str, Box<dyn Error + 'static>)> = vec![
(
"OperationError without a record",
Box::new(OperationError::from_kind(OperationErrorKind::ChildContext(
ChildContextError::new(ChildContextErrorKind::ChildFailed, Some(boxed())),
))),
),
(
"StepError",
Box::new(StepError::new(
StepErrorKind::ExecutionFailed,
Some(boxed()),
)),
),
(
"WaitError",
Box::new(WaitError::new(
WaitErrorKind::UnexpectedStatus(UnexpectedStatus::new("FAILED")),
Some(boxed()),
)),
),
(
"InvokeError",
Box::new(InvokeError::new(
InvokeErrorKind::FunctionFailed,
Some(boxed()),
)),
),
(
"CallbackError",
Box::new(CallbackError::new(
CallbackErrorKind::SubmitterFailed,
Some(boxed()),
)),
),
(
"WaitForConditionError",
Box::new(WaitForConditionError::new(
WaitForConditionErrorKind::CheckFailed,
Some(boxed()),
)),
),
(
"ChildContextError",
Box::new(ChildContextError::new(
ChildContextErrorKind::ChildFailed,
Some(boxed()),
)),
),
(
"CombinatorError",
Box::new(CombinatorError::new(
CombinatorErrorKind::FirstSettledFailed,
vec![boxed()],
)),
),
("ChildFnError", Box::new(ChildFnError::new(boxed()))),
(
"ContextualError",
ContextualError::source_from("ctx", boxed()),
),
];
for (name, carrier) in &carriers {
assert_eq!(wire_message(&**carrier), "inner", "{name}");
}
let sourceless = StepError::new(StepErrorKind::ExecutionFailed, None);
assert_eq!(wire_message(&sourceless), "execution failed");
let typed = TypedError::with_type("OuterType", recorded_step());
assert_eq!(wire_message(&typed), "inner");
let wrapper = Wrapper(boxed());
assert_eq!(
wire_message(&wrapper),
format!("wrapper: {RECORDED_STEP_CHAIN}")
);
let client = crate::client::ExecutionClientError::with_source(
crate::client::ExecutionClientErrorScope::Invocation,
"checkpoint failed",
recorded_step(),
);
assert_eq!(
wire_message(&client),
format!("durable: client: checkpoint failed: {RECORDED_STEP_CHAIN}")
);
let serde_error = match serde_json::from_str::<u32>("x") {
Err(e) => e,
Ok(v) => unreachable!("`x` is not a u32: {v}"),
};
let serialization = StepError::new(
StepErrorKind::SerializationFailed,
Some(Box::new(serde_error)),
);
assert_eq!(
wire_message(&serialization),
"serialization failed: expected value at line 1 column 1"
);
let layered = |layers: usize| -> Source {
(0..layers).fold(boxed(), |source, _| {
ContextualError::source_from("ctx", source)
})
};
assert_eq!(wire_message(&*layered(10)), "inner");
let past_the_limit = layered(11);
assert_eq!(
wire_message(&*past_the_limit),
chain_string(&*past_the_limit)
);
assert_ne!(wire_message(&*past_the_limit), "inner");
}
#[test]
fn wire_message_counts_a_typed_error_as_one_link() {
let typed_over = |layers: usize| -> Source {
let typed: Source = Box::new(TypedError::with_type("T", recorded_step()));
(0..layers).fold(typed, |source, _| {
ContextualError::source_from("ctx", source)
})
};
assert_eq!(wire_message(&*typed_over(9)), "inner");
assert_eq!(
wire_message(&*typed_over(10)),
"ctx: ctx: ctx: ctx: ctx: ctx: ctx: ctx: ctx: ctx: \
operation error: step: execution failed: inner"
);
}
#[test]
fn wire_message_typed_record_without_message_flattens_the_chain() {
let typed = TypedError::with_type(
"Typed",
recorded_step_error(WireError::new(Some("RecordType"), None::<String>)),
);
assert_eq!(
wire_message(&typed),
"operation error: step: execution failed: RecordType"
);
let empty = TypedError::with_type(
"Typed",
recorded_step_error(WireError::new(Some("RecordType"), Some(""))),
);
assert_eq!(wire_message(&empty), "");
}
#[derive(Debug)]
struct Frame(&'static str, Option<Source>);
impl fmt::Display for Frame {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl Error for Frame {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.1.as_deref().map(|s| s as &(dyn Error + 'static))
}
}
#[derive(Debug)]
struct PaymentDeclined;
impl fmt::Display for PaymentDeclined {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "payment declined")
}
}
impl Error for PaymentDeclined {}
#[test]
fn chain_string_omits_typed_error_frames() {
let failed_step = || recorded_step_error(WireError::new(Some("StepType"), Some("boom")));
let rows: Vec<(Box<dyn Error + 'static>, &str, &str, &str)> = vec![
(
Box::new(TypedError::with_type("PaymentError", "declined")),
"PaymentError",
"declined",
"declined",
),
(
Box::new(TypedError::new(PaymentDeclined)),
"PaymentDeclined",
"payment declined",
"payment declined",
),
(
Box::new(TypedError::with_type("PaymentError", failed_step())),
"PaymentError",
"boom",
"operation error: step: execution failed: boom",
),
(
Box::new(Frame(
"charging",
Some(Box::new(TypedError::with_type("PaymentError", "declined"))),
)),
"PaymentError",
"charging: declined",
"charging: declined",
),
(
Box::new(TypedError::with_type("A", TypedError::with_type("B", "x"))),
"A",
"x",
"x",
),
(
Box::new(TypedError::with_type(
"Typed",
Frame("a", Some(Box::new(Frame("b", None)))),
)),
"Typed",
"a: b",
"a: b",
),
];
for (err, error_type, message, chain) in &rows {
let wire = wire_error_for(&**err, "Error");
assert_eq!(wire.error_type(), Some(*error_type), "{err:#}");
assert_eq!(wire.error_message(), Some(*message), "{err:#}");
assert_eq!(chain_string(&**err), *chain, "{err:#}");
}
}
#[test]
fn wire_message_preserves_non_message_fields() {
let inner_wire = || {
WireError::new(Some("InnerType"), Some("inner"))
.with_error_data(Some("inner-data"))
.with_stack_trace(vec!["inner-frame".to_owned()])
};
let child =
OperationError::from_kind(OperationErrorKind::ChildContext(ChildContextError::new(
ChildContextErrorKind::ChildFailed,
Some(Box::new(recorded_step_error(inner_wire()))),
)));
let wire = wire_error_for(&child, "Error");
assert_eq!(wire.error_type(), Some("ChildContextError"));
assert_eq!(wire.error_message(), Some("inner"));
assert_eq!(wire.error_data(), Some("inner-data"));
assert_eq!(wire.stack_trace(), ["inner-frame"]);
let contextual =
ContextualError::source_from("serialize", recorded_step_error(inner_wire()));
let wire = serialization_failure_wire(&*contextual);
assert_eq!(wire.error_type(), Some("SerializationError"));
assert_eq!(wire.error_message(), Some("inner"));
assert_eq!(wire.error_data(), Some("inner-data"));
assert_eq!(wire.stack_trace(), ["inner-frame"]);
let typed = TypedError::with_type("Typed", recorded_step_error(inner_wire()));
let wire = wire_error_for(&typed, "Error");
assert_eq!(wire.error_type(), Some("Typed"));
assert_eq!(wire.error_message(), Some("inner"));
assert_eq!(wire.error_data(), Some("inner-data"));
assert_eq!(wire.stack_trace(), ["inner-frame"]);
let typed = TypedError::with_type("Typed", recorded_step_error(inner_wire()))
.with_error_data("typed-data");
let wire = wire_error_for(&typed, "Error");
assert_eq!(wire.error_type(), Some("Typed"));
assert_eq!(wire.error_message(), Some("inner"));
assert_eq!(wire.error_data(), Some("typed-data"));
assert_eq!(wire.stack_trace(), ["inner-frame"]);
}
}