Skip to main content

rust_supervisor/role/result/
worker.rs

1//! Worker role result and error values.
2//!
3//! Worker errors preserve the child identifier and lifecycle phase before the
4//! adapter maps them into task failures.
5
6use crate::error::types::{TaskFailure, TaskFailureKind};
7use crate::id::types::ChildId;
8use crate::policy::task_role_defaults::TaskRole;
9use crate::role::lifecycle::RoleLifecyclePhase;
10use thiserror::Error;
11
12/// Result returned by worker role lifecycle methods.
13pub type WorkerResult<T = ()> = Result<T, WorkerError>;
14
15/// Structured error returned by a worker role.
16#[derive(Debug, Clone, PartialEq, Eq, Error)]
17#[error("worker role failed during {phase:?}: {message}")]
18pub struct WorkerError {
19    /// Stable child identifier for the failed worker.
20    pub child_id: ChildId,
21    /// Lifecycle phase where the worker failed.
22    pub phase: RoleLifecyclePhase,
23    /// Human-readable diagnostic message.
24    pub message: String,
25}
26
27impl WorkerError {
28    /// Creates a worker role error.
29    ///
30    /// # Arguments
31    ///
32    /// - `child_id`: Stable child identifier for the failed worker.
33    /// - `phase`: Lifecycle phase where the worker failed.
34    /// - `message`: Diagnostic message for operators.
35    ///
36    /// # Returns
37    ///
38    /// Returns a structured [`WorkerError`] value.
39    ///
40    /// # Examples
41    ///
42    /// ```
43    /// let error = rust_supervisor::role::result::worker::WorkerError::new(
44    ///     rust_supervisor::id::types::ChildId::new("worker"),
45    ///     rust_supervisor::role::lifecycle::RoleLifecyclePhase::Work,
46    ///     "queue closed",
47    /// );
48    /// assert_eq!(error.phase.as_str(), "work");
49    /// ```
50    pub fn new(child_id: ChildId, phase: RoleLifecyclePhase, message: impl Into<String>) -> Self {
51        Self {
52            child_id,
53            phase,
54            message: message.into(),
55        }
56    }
57
58    /// Converts this worker error into a runtime task failure.
59    ///
60    /// # Arguments
61    ///
62    /// This function has no arguments.
63    ///
64    /// # Returns
65    ///
66    /// Returns a [`TaskFailure`] value consumed by the runtime policy pipeline.
67    pub fn into_task_failure(self) -> TaskFailure {
68        TaskFailure::new(
69            TaskFailureKind::Error,
70            format!("{}_{}", TaskRole::Worker.as_str(), self.phase.as_str()),
71            format!(
72                "worker role child={} phase={} failed: {}",
73                self.child_id,
74                self.phase.as_str(),
75                self.message
76            ),
77        )
78    }
79}