hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
Documentation
//! The error a task handler returns.

use std::fmt;

/// Why a task run failed, and whether Hatchet should retry it.
///
/// Every automatic conversion into `TaskError` (the blanket
/// `From<E: std::error::Error>` below) produces a **retryable** error, so a
/// bare `?` inside a handler is always a bet that retrying might help. Use
/// [`TaskError::non_retryable`] explicitly when it can't.
///
/// `anyhow::Error` does not implement `std::error::Error`, so it does not convert
/// automatically; convert it explicitly with `TaskError::new(e.to_string())` (or
/// `TaskError::new(format!("{e:#}"))` to include its context chain).
///
/// `TaskError` deliberately does not implement `std::error::Error`: that
/// would conflict with the blanket `From` conversion.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskError {
    message: String,
    retryable: bool,
}

impl TaskError {
    /// A failure Hatchet may retry, if the task has retries left.
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            retryable: true,
        }
    }

    /// A failure Hatchet must not retry.
    pub fn non_retryable(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            retryable: false,
        }
    }

    /// The message reported to the engine.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Whether Hatchet may retry the task.
    pub fn is_retryable(&self) -> bool {
        self.retryable
    }
}

impl fmt::Display for TaskError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl<E: std::error::Error> From<E> for TaskError {
    fn from(error: E) -> Self {
        Self::new(error.to_string())
    }
}

// `impl From<String> for TaskError`, `impl From<&str> for TaskError`, and
// `impl From<Box<dyn std::error::Error + Send + Sync>> for TaskError` were
// all attempted here, as requested, but each one fails to compile with
// "conflicting implementations of trait `From<...>` for type `TaskError`"
// against the blanket `impl<E: std::error::Error> From<E> for TaskError`
// above. None of `String`, `str`, or `Box<dyn std::error::Error + Send +
// Sync>` implements `std::error::Error` *today*, but Rust's coherence
// checker rejects a dedicated impl for any of them anyway: since the
// blanket impl is generic over any `E: std::error::Error` (a foreign
// trait) for the local type `TaskError`, and `String`/`str`/`Box` are all
// std types the compiler must treat as potentially gaining an
// `std::error::Error` impl in a future std version, it conservatively
// assumes future overlap and refuses to compile either impl. So none of
// the three are added; use `TaskError::new(message)` for a `String`/`&str`
// message, and `TaskError::new(error.to_string())` for a
// `Box<dyn std::error::Error + Send + Sync>`.

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

    #[test]
    fn new_errors_are_retryable() {
        let error = TaskError::new("flaky network");
        assert!(error.is_retryable());
        assert_eq!(error.message(), "flaky network");
        assert_eq!(error.to_string(), "flaky network");
    }

    #[test]
    fn non_retryable_errors_say_so() {
        let error = TaskError::non_retryable("bad input");
        assert!(!error.is_retryable());
        assert_eq!(error.message(), "bad input");
    }

    #[test]
    fn question_mark_converts_any_std_error_into_a_retryable_task_error() {
        fn parse() -> Result<i32, TaskError> {
            Ok("not a number".parse::<i32>()?)
        }
        let error = parse().unwrap_err();
        assert!(error.is_retryable());
        assert!(error.message().contains("invalid digit"), "{error}");
    }

    #[test]
    fn a_boxed_error_converts_via_new_and_is_retryable() {
        // `Box<dyn std::error::Error + Send + Sync>` does not itself implement
        // `std::error::Error` (it is unsized, and std's `Error for Box<E>`
        // impl requires `E: Sized`), and a dedicated `From` impl for it would
        // conflict with the blanket impl (see the comment above), so this is
        // the documented manual conversion instead of a `?`.
        fn boxed_failure() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
            "not a number".parse::<i32>()?;
            Ok(())
        }
        fn fails() -> Result<(), TaskError> {
            boxed_failure().map_err(|e| TaskError::new(e.to_string()))?;
            Ok(())
        }
        let error = fails().unwrap_err();
        assert!(error.is_retryable());
        assert!(error.message().contains("invalid digit"), "{error}");
    }
}