Skip to main content

adk_kernel/
error.rs

1//! The kernel's error type (spec 3.2 §7.1).
2//!
3//! Every fallible kernel API returns [`KernelError`]. It converts into
4//! [`adk_core::AdkError`] at the boundary with an `ErrorComponent::Server` component and a
5//! `kernel.*` code, so a control-plane route answers with the status and problem JSON the
6//! rest of `adk-server` uses.
7
8use adk_core::{AdkError, ErrorCategory, ErrorComponent, RunState};
9use thiserror::Error;
10
11use crate::kernel::KernelState;
12
13/// Result of a fallible kernel operation (spec 3.2 §7.1).
14pub type Result<T, E = KernelError> = std::result::Result<T, E>;
15
16/// Error code of [`KernelError::NotFound`].
17pub const NOT_FOUND_CODE: &str = "kernel.not_found";
18/// Error code of [`KernelError::InvalidState`].
19pub const INVALID_STATE_CODE: &str = "kernel.invalid_state";
20/// Error code of [`KernelError::Frozen`].
21pub const FROZEN_CODE: &str = "kernel.frozen";
22/// Error code of [`KernelError::Lifecycle`].
23pub const LIFECYCLE_CODE: &str = "kernel.lifecycle";
24/// Error code of [`KernelError::Config`].
25pub const CONFIG_CODE: &str = "kernel.config";
26/// Error code of [`KernelError::Store`].
27pub const STORE_CODE: &str = "kernel.store";
28/// Error code of [`KernelError::ControlPlane`].
29pub const CONTROL_PLANE_CODE: &str = "kernel.control_plane";
30/// Error code of [`KernelError::Unauthorized`].
31pub const UNAUTHORIZED_CODE: &str = "kernel.unauthorized";
32/// Error code of [`KernelError::AgendaNotFound`].
33pub const AGENDA_NOT_FOUND_CODE: &str = "kernel.agenda_not_found";
34/// Error code of [`KernelError::AgendaState`].
35pub const AGENDA_STATE_CODE: &str = "kernel.agenda_state";
36/// Error code of [`KernelError::Quota`].
37pub const QUOTA_CODE: &str = "kernel.quota";
38/// Error code of [`KernelError::Service`].
39pub const SERVICE_CODE: &str = "kernel.service";
40/// Error code of [`KernelError::Io`].
41pub const IO_CODE: &str = "kernel.io";
42/// Error code of [`KernelError::Serde`].
43pub const SERDE_CODE: &str = "kernel.serde";
44/// Error code of a spawn the run store refuses because another run holds its concurrency
45/// key and the run does not queue behind it.
46pub const SPAWN_REJECTED_CODE: &str = "kernel.spawn_rejected";
47/// Error code of a call a store does not support, such as attachments on a device store
48/// that keeps none.
49pub const UNSUPPORTED_CODE: &str = "kernel.unsupported";
50/// Error code of a ledger row the ledger refuses (spec 3.2 §9.2 K-I19).
51///
52/// # Example
53///
54/// ```rust
55/// assert_eq!(adk_kernel::error::LEDGER_INVALID_CODE, "kernel.ledger.invalid_row");
56/// ```
57pub const LEDGER_INVALID_CODE: &str = "kernel.ledger.invalid_row";
58/// Error code of a crossing between partitions that no rule permits (spec 3.2 K-I15).
59pub const CROSSING_DENIED_CODE: &str = "kernel.partition.crossing_denied";
60/// Error code of a partition's memory call that names another partition's scope
61/// (spec 3.2 K-I15).
62pub const MEMORY_CROSSING_CODE: &str = "kernel.partition.memory_crossing";
63/// Error code of a delete by query on a partition's memory, which would reach every
64/// partition's scope.
65pub const MEMORY_DELETE_CODE: &str = "kernel.partition.memory_delete";
66/// Error code of an agent id the kernel does not keep (spec 3.3 §5.7).
67pub const AGENT_NOT_FOUND_CODE: &str = "kernel.agent.not_found";
68/// Error code of an agent definition that breaks a rule of spec 3.3 §5.7: its name, id,
69/// instructions, folder or uses.
70pub const AGENT_INVALID_CODE: &str = "kernel.agent.invalid";
71/// Error code of an agent change made against an older version (spec 3.3 §5.7).
72pub const AGENT_OUT_OF_DATE_CODE: &str = "kernel.agent.out_of_date";
73/// Error code of an agent change the agent table refuses: a caller who is not a person, a
74/// device, high risk without presence, more than an area or a suggesting agent allows
75/// (spec 3.3 §5.7, S-I11, S-I12).
76pub const AGENT_REFUSED_CODE: &str = "kernel.agent.refused";
77/// Error code of an agent change applied with a digest that is not its preview's (spec 3.3
78/// §5.7).
79pub const AGENT_UNCONFIRMED_CODE: &str = "kernel.agent.unconfirmed";
80/// Error code of `POST /kernel/unfreeze` refused over HTTP: resuming happens only in the web
81/// home or on a paired local terminal (spec 3.3 S-I10).
82///
83/// # Example
84///
85/// ```rust
86/// assert_eq!(adk_kernel::error::RESUME_NOT_HERE_CODE, "kernel.resume.not_here");
87/// ```
88pub const RESUME_NOT_HERE_CODE: &str = "kernel.resume.not_here";
89/// Error code of a decision on `POST /approvals/{id}/decide` that the caller's surface may not
90/// give (spec 3.3 §7.2): it is answered in the home or on the kernel's own terminal.
91///
92/// # Example
93///
94/// ```rust
95/// assert_eq!(adk_kernel::error::DECIDE_NOT_HERE_CODE, "surface.decide.not_here");
96/// ```
97pub const DECIDE_NOT_HERE_CODE: &str = "surface.decide.not_here";
98
99/// Every code the kernel answers a control-plane call with: the codes a
100/// [`ControlClient`](crate::control::ControlClient) keeps, and reports any other code as
101/// [`CONTROL_PLANE_CODE`]. A test checks it against every `*_CODE` constant in the crate.
102pub(crate) const CODES: &[&str] = &[
103    NOT_FOUND_CODE,
104    INVALID_STATE_CODE,
105    FROZEN_CODE,
106    LIFECYCLE_CODE,
107    CONFIG_CODE,
108    STORE_CODE,
109    CONTROL_PLANE_CODE,
110    UNAUTHORIZED_CODE,
111    AGENDA_NOT_FOUND_CODE,
112    AGENDA_STATE_CODE,
113    QUOTA_CODE,
114    SERVICE_CODE,
115    IO_CODE,
116    SERDE_CODE,
117    SPAWN_REJECTED_CODE,
118    UNSUPPORTED_CODE,
119    LEDGER_INVALID_CODE,
120    CROSSING_DENIED_CODE,
121    MEMORY_CROSSING_CODE,
122    MEMORY_DELETE_CODE,
123    AGENT_NOT_FOUND_CODE,
124    AGENT_INVALID_CODE,
125    AGENT_OUT_OF_DATE_CODE,
126    AGENT_REFUSED_CODE,
127    AGENT_UNCONFIRMED_CODE,
128    RESUME_NOT_HERE_CODE,
129    DECIDE_NOT_HERE_CODE,
130];
131
132/// What went wrong in the kernel (spec 3.2 §7.1).
133///
134/// Messages name the remedy: the command or setting that fixes the condition.
135///
136/// # Example
137///
138/// ```rust
139/// use adk_core::AdkError;
140/// use adk_kernel::KernelError;
141///
142/// let error = KernelError::NotFound { pid: "run-7".into() };
143/// assert!(error.to_string().contains("adk-rust ps"));
144/// let error: AdkError = error.into();
145/// assert_eq!(error.code, adk_kernel::error::NOT_FOUND_CODE);
146/// assert!(error.is_not_found());
147/// ```
148#[derive(Debug, Error)]
149#[non_exhaustive]
150pub enum KernelError {
151    /// No process has this id.
152    #[error(
153        "no process {pid}: list the processes with `adk-rust ps` or `GET /api/kernel/processes`"
154    )]
155    NotFound {
156        /// The process id (the run id).
157        pid: String,
158    },
159
160    /// The process is in a state the action does not apply to.
161    #[error(
162        "process {pid} is {state:?}, so it cannot be {action}; check its state with \
163         `adk-rust ps`"
164    )]
165    InvalidState {
166        /// The process id (the run id).
167        pid: String,
168        /// The run's state.
169        state: RunState,
170        /// The action refused, such as `suspended`.
171        action: &'static str,
172    },
173
174    /// The kernel is frozen, so nothing starts.
175    #[error("the kernel is frozen ({reason}); lift the freeze with `adk-rust unfreeze`")]
176    Frozen {
177        /// The freeze reason.
178        reason: String,
179    },
180
181    /// The kernel's lifecycle state does not allow the call, such as `pause` before `start`.
182    #[error("the kernel is {state}, so it cannot {action}; check `adk-rust ps` or the health")]
183    Lifecycle {
184        /// The kernel's state.
185        state: KernelState,
186        /// The refused call, such as `pause`.
187        action: &'static str,
188    },
189
190    /// The kernel configuration is invalid.
191    #[error("invalid kernel configuration: {reason}")]
192    Config {
193        /// What is wrong and how to fix it.
194        reason: String,
195    },
196
197    /// A kernel store backend failed.
198    #[error(
199        "the {backend} kernel store failed: {reason}; check the store URL and that the server is reachable"
200    )]
201    Store {
202        /// The backend, such as `sqlite`, `postgres` or `redis`.
203        backend: &'static str,
204        /// The backend's error.
205        reason: String,
206    },
207
208    /// The control plane could not start, serve or connect.
209    #[error("control plane: {reason}")]
210    ControlPlane {
211        /// What failed and how to fix it.
212        reason: String,
213    },
214
215    /// A control-plane caller carries no authenticated subject (spec 3.2 §9.2 K-I16).
216    #[error("unauthorized: {reason}")]
217    Unauthorized {
218        /// Why the caller was refused.
219        reason: String,
220    },
221
222    /// No agenda item has this id (spec 3.2 §7.5).
223    #[error(
224        "no agenda item {item}: list the agenda with `adk-rust agenda` or `GET /api/kernel/agenda`"
225    )]
226    AgendaNotFound {
227        /// The item id.
228        item: String,
229    },
230
231    /// The agenda item is in a state the action does not apply to (spec 3.2 §7.5).
232    #[error(
233        "agenda item {item} is {state}, so it cannot be {action}; check it with `adk-rust agenda`"
234    )]
235    AgendaState {
236        /// The item id.
237        item: String,
238        /// The item's state.
239        state: crate::agenda::AgendaStateKind,
240        /// The action refused, such as `approved`.
241        action: &'static str,
242    },
243
244    /// A partition quota refuses the process (spec 3.2 §7.9).
245    #[error(
246        "partition {partition} is at its quota: {reason}; wait for its processes to finish or raise the quota"
247    )]
248    Quota {
249        /// The partition.
250        partition: String,
251        /// Which quota and its value.
252        reason: String,
253    },
254
255    /// Installing, removing or running the kernel as a service failed (spec 3.2 §7.12).
256    #[error("kernel service: {reason}")]
257    Service {
258        /// What failed and how to fix it.
259        reason: String,
260    },
261
262    /// An error from an `adk-core` or `adk-server` API the kernel composes.
263    #[error(transparent)]
264    Core(#[from] AdkError),
265
266    /// A file or socket operation failed.
267    #[error("kernel I/O failed: {0}")]
268    Io(#[from] std::io::Error),
269
270    /// A record could not be encoded or decoded.
271    #[error("kernel record encoding failed: {0}")]
272    Serde(#[from] serde_json::Error),
273}
274
275impl KernelError {
276    /// The error's code: a `kernel.*` code, or the wrapped error's code for
277    /// [`Core`](Self::Core).
278    ///
279    /// # Example
280    ///
281    /// ```rust
282    /// use adk_kernel::KernelError;
283    ///
284    /// let error = KernelError::Frozen { reason: "incident 12".into() };
285    /// assert_eq!(error.code(), adk_kernel::error::FROZEN_CODE);
286    /// ```
287    pub fn code(&self) -> &'static str {
288        match self {
289            Self::NotFound { .. } => NOT_FOUND_CODE,
290            Self::InvalidState { .. } => INVALID_STATE_CODE,
291            Self::Frozen { .. } => FROZEN_CODE,
292            Self::Lifecycle { .. } => LIFECYCLE_CODE,
293            Self::Config { .. } => CONFIG_CODE,
294            Self::Store { .. } => STORE_CODE,
295            Self::ControlPlane { .. } => CONTROL_PLANE_CODE,
296            Self::Unauthorized { .. } => UNAUTHORIZED_CODE,
297            Self::AgendaNotFound { .. } => AGENDA_NOT_FOUND_CODE,
298            Self::AgendaState { .. } => AGENDA_STATE_CODE,
299            Self::Quota { .. } => QUOTA_CODE,
300            Self::Service { .. } => SERVICE_CODE,
301            Self::Core(error) => error.code,
302            Self::Io(_) => IO_CODE,
303            Self::Serde(_) => SERDE_CODE,
304        }
305    }
306
307    /// The error's category, which sets the HTTP status a control-plane route answers.
308    pub fn category(&self) -> ErrorCategory {
309        match self {
310            Self::NotFound { .. } | Self::AgendaNotFound { .. } => ErrorCategory::NotFound,
311            Self::InvalidState { .. } | Self::Lifecycle { .. } | Self::AgendaState { .. } => {
312                ErrorCategory::Conflict
313            }
314            Self::Quota { .. } => ErrorCategory::ResourceExhausted,
315            Self::Frozen { .. }
316            | Self::Store { .. }
317            | Self::ControlPlane { .. }
318            | Self::Service { .. } => ErrorCategory::Unavailable,
319            Self::Config { .. } => ErrorCategory::InvalidInput,
320            Self::Unauthorized { .. } => ErrorCategory::Unauthorized,
321            Self::Core(error) => error.category,
322            Self::Io(_) | Self::Serde(_) => ErrorCategory::Internal,
323        }
324    }
325}
326
327impl From<KernelError> for AdkError {
328    fn from(error: KernelError) -> Self {
329        match error {
330            KernelError::Core(inner) => inner,
331            other => AdkError::new(
332                ErrorComponent::Server,
333                other.category(),
334                other.code(),
335                other.to_string(),
336            ),
337        }
338    }
339}
340
341#[cfg(test)]
342mod tests {
343    use std::path::{Path, PathBuf};
344
345    use super::*;
346
347    /// Every `.rs` file under the crate's `src`.
348    fn sources() -> Vec<(PathBuf, String)> {
349        let mut pending = vec![Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
350        let mut files = Vec::new();
351        while let Some(path) = pending.pop() {
352            if path.is_dir() {
353                pending
354                    .extend(std::fs::read_dir(&path).unwrap().map(|entry| entry.unwrap().path()));
355            } else if path.extension().is_some_and(|extension| extension == "rs") {
356                let text = std::fs::read_to_string(&path).unwrap();
357                files.push((path, text));
358            }
359        }
360        files
361    }
362
363    /// The `index`th top-level argument of the call whose text follows its opening
364    /// parenthesis, trimmed.
365    fn argument(call: &str, index: usize) -> String {
366        let (mut depth, mut current, mut in_string, mut escaped) = (0usize, 0, false, false);
367        let mut text = String::new();
368        for c in call.chars() {
369            if in_string {
370                in_string = c != '"' || escaped;
371                escaped = c == '\\' && !escaped;
372            } else {
373                match c {
374                    '"' => in_string = true,
375                    '(' | '[' | '{' => depth += 1,
376                    ')' | ']' | '}' if depth == 0 => break,
377                    ')' | ']' | '}' => depth -= 1,
378                    ',' if depth == 0 => {
379                        current += 1;
380                        continue;
381                    }
382                    _ => {}
383                }
384            }
385            if current == index {
386                text.push(c);
387            }
388        }
389        text.trim().to_string()
390    }
391
392    // A code the client does not list reaches its callers as `kernel.control_plane`, so
393    // every code the crate can answer with is a `*_CODE` constant listed in `CODES`.
394    #[test]
395    fn every_code_the_kernel_answers_with_is_listed() {
396        let mut constants = Vec::new();
397        let mut literals = Vec::new();
398        for (path, text) in sources() {
399            for line in text.lines() {
400                if let Some((_, value)) = line.split_once("_CODE: &str = \"")
401                    && let Some((code, _)) = value.split_once('"')
402                    && (code.starts_with("kernel.") || code.starts_with("surface."))
403                {
404                    constants.push(code.to_string());
405                }
406            }
407            for call in text.split("AdkError::new(").skip(1) {
408                let code = argument(call, 2);
409                if code.starts_with("\"kernel.") {
410                    literals.push(format!("{}: {code}", path.display()));
411                }
412            }
413        }
414        assert!(constants.len() >= CODES.len(), "the scan found {constants:?}");
415        let unlisted: Vec<_> =
416            constants.iter().filter(|code| !CODES.contains(&code.as_str())).collect();
417        assert!(unlisted.is_empty(), "add these codes to error::CODES: {unlisted:?}");
418        assert!(
419            literals.is_empty(),
420            "name these codes as `*_CODE` constants in error.rs and list them in CODES: \
421             {literals:?}"
422        );
423    }
424
425    #[test]
426    fn the_argument_scan_skips_nested_calls_and_strings() {
427        let call = r#"ErrorComponent::Server, f(a, b), "a, (b", format!("{x}, y"))"#;
428        assert_eq!(argument(call, 1), "f(a, b)");
429        assert_eq!(argument(call, 2), r#""a, (b""#);
430        assert_eq!(argument(call, 3), r#"format!("{x}, y")"#);
431    }
432}