Skip to main content

kruxiaflow_worker/
error.rs

1//! Error types for the worker SDK.
2
3use crate::types::UsageEntry;
4use rust_decimal::Decimal;
5
6/// An activity failure, reported to the server via
7/// `POST /api/v1/activities/{id}/fail`.
8///
9/// The `retryable` flag is the contract-critical part: retryable failures are
10/// re-queued by the orchestrator (up to the activity's retry limit), terminal
11/// failures are not. Construct with [`ActivityError::retryable`] or
12/// [`ActivityError::terminal`] so the distinction is always explicit.
13///
14/// A failed attempt may still have spent money: attach what it cost with
15/// [`ActivityError::with_usage`] / [`ActivityError::with_cost`] so the spend
16/// is recorded and counted against workflow budgets.
17///
18/// Any error convertible to [`anyhow::Error`] can be propagated with `?` from
19/// handlers returning `Result<_, ActivityError>` via
20/// `.map_err(ActivityError::from)?`, or directly from `anyhow::Error`; it
21/// becomes a retryable `EXECUTION_ERROR`.
22#[derive(Debug, Clone)]
23pub struct ActivityError {
24    /// Error code (for categorization, e.g. "PAYMENT_DECLINED")
25    pub code: String,
26    /// Human-readable error message
27    pub message: String,
28    /// Whether the orchestrator should retry this activity
29    pub retryable: bool,
30    /// Cost spent before the failure that is NOT covered by `usage` entries
31    pub cost_usd: Option<Decimal>,
32    /// Per-LLM-call usage made before the failure
33    pub usage: Vec<UsageEntry>,
34}
35
36impl ActivityError {
37    /// A failure the orchestrator should retry (transient conditions:
38    /// timeouts, network errors, rate limits).
39    pub fn retryable(code: impl Into<String>, message: impl Into<String>) -> Self {
40        Self {
41            code: code.into(),
42            message: message.into(),
43            retryable: true,
44            cost_usd: None,
45            usage: Vec::new(),
46        }
47    }
48
49    /// A terminal failure that will not improve on retry (bad input,
50    /// business-rule rejection).
51    pub fn terminal(code: impl Into<String>, message: impl Into<String>) -> Self {
52        Self {
53            code: code.into(),
54            message: message.into(),
55            retryable: false,
56            cost_usd: None,
57            usage: Vec::new(),
58        }
59    }
60
61    /// Attach cost spent before the failure that is not covered by usage
62    /// entries.
63    pub fn with_cost(mut self, cost_usd: Decimal) -> Self {
64        self.cost_usd = Some(cost_usd);
65        self
66    }
67
68    /// Attach per-LLM-call usage made before the failure.
69    pub fn with_usage(mut self, usage: Vec<UsageEntry>) -> Self {
70        self.usage = usage;
71        self
72    }
73}
74
75impl std::fmt::Display for ActivityError {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        write!(f, "{}: {}", self.code, self.message)
78    }
79}
80
81impl std::error::Error for ActivityError {}
82
83impl From<anyhow::Error> for ActivityError {
84    fn from(err: anyhow::Error) -> Self {
85        Self::retryable("EXECUTION_ERROR", format!("{err:#}"))
86    }
87}
88
89/// Worker configuration error.
90#[derive(Debug, thiserror::Error)]
91pub enum ConfigError {
92    #[error("Missing API URL (set KRUXIAFLOW_API_URL)")]
93    MissingApiUrl,
94
95    #[error(
96        "Partial OAuth credentials: set both KRUXIAFLOW_CLIENT_ID and KRUXIAFLOW_CLIENT_SECRET, \
97         or neither (server in dev mode)"
98    )]
99    PartialCredentials,
100
101    #[error(
102        "No worker name: set KRUXIAFLOW_WORKER, call worker(...) on the builder, \
103         or register activities that declare one"
104    )]
105    MissingWorker,
106
107    #[error(
108        "Ambiguous worker name: registered activities declare multiple workers ({0:?}); \
109         a worker polls one worker name — set it explicitly"
110    )]
111    AmbiguousWorker(Vec<String>),
112
113    #[error("Invalid value for {var}: {reason}")]
114    InvalidValue { var: String, reason: String },
115}
116
117/// Error from a worker API call.
118#[derive(Debug, thiserror::Error)]
119pub enum ClientError {
120    #[error("HTTP request failed: {0}")]
121    Http(#[from] reqwest::Error),
122
123    /// The server rejected the request as unauthenticated and no credentials
124    /// are configured. Set `KRUXIAFLOW_CLIENT_ID` / `KRUXIAFLOW_CLIENT_SECRET`,
125    /// or run the server in dev mode (`--insecure-dev`).
126    #[error(
127        "Server requires authentication but no credentials are configured \
128         (set KRUXIAFLOW_CLIENT_ID and KRUXIAFLOW_CLIENT_SECRET)"
129    )]
130    AuthRequired,
131
132    #[error("Token request failed: {status} - {body}")]
133    Auth { status: u16, body: String },
134
135    /// 409: the activity was already completed, timed out, or was reassigned
136    /// to a different worker. Idempotency semantics: log and move on, never
137    /// retry.
138    #[error("Conflict: {body}")]
139    Conflict { body: String },
140
141    #[error("API error: {status} - {body}")]
142    Api { status: u16, body: String },
143
144    /// The wake stream ended, stalled, or sent something unreadable. The
145    /// worker reconnects; meanwhile it polls on its timer.
146    #[error("Wake stream closed: {0}")]
147    WakeStream(String),
148}