use adk_core::{AdkError, ErrorCategory, ErrorComponent, RunState};
use thiserror::Error;
use crate::kernel::KernelState;
pub type Result<T, E = KernelError> = std::result::Result<T, E>;
pub const NOT_FOUND_CODE: &str = "kernel.not_found";
pub const INVALID_STATE_CODE: &str = "kernel.invalid_state";
pub const FROZEN_CODE: &str = "kernel.frozen";
pub const LIFECYCLE_CODE: &str = "kernel.lifecycle";
pub const CONFIG_CODE: &str = "kernel.config";
pub const STORE_CODE: &str = "kernel.store";
pub const CONTROL_PLANE_CODE: &str = "kernel.control_plane";
pub const UNAUTHORIZED_CODE: &str = "kernel.unauthorized";
pub const AGENDA_NOT_FOUND_CODE: &str = "kernel.agenda_not_found";
pub const AGENDA_STATE_CODE: &str = "kernel.agenda_state";
pub const QUOTA_CODE: &str = "kernel.quota";
pub const SERVICE_CODE: &str = "kernel.service";
pub const IO_CODE: &str = "kernel.io";
pub const SERDE_CODE: &str = "kernel.serde";
pub const SPAWN_REJECTED_CODE: &str = "kernel.spawn_rejected";
pub const UNSUPPORTED_CODE: &str = "kernel.unsupported";
pub const LEDGER_INVALID_CODE: &str = "kernel.ledger.invalid_row";
pub const CROSSING_DENIED_CODE: &str = "kernel.partition.crossing_denied";
pub const MEMORY_CROSSING_CODE: &str = "kernel.partition.memory_crossing";
pub const MEMORY_DELETE_CODE: &str = "kernel.partition.memory_delete";
pub const AGENT_NOT_FOUND_CODE: &str = "kernel.agent.not_found";
pub const AGENT_INVALID_CODE: &str = "kernel.agent.invalid";
pub const AGENT_OUT_OF_DATE_CODE: &str = "kernel.agent.out_of_date";
pub const AGENT_REFUSED_CODE: &str = "kernel.agent.refused";
pub const AGENT_UNCONFIRMED_CODE: &str = "kernel.agent.unconfirmed";
pub const RESUME_NOT_HERE_CODE: &str = "kernel.resume.not_here";
pub const DECIDE_NOT_HERE_CODE: &str = "surface.decide.not_here";
pub(crate) const CODES: &[&str] = &[
NOT_FOUND_CODE,
INVALID_STATE_CODE,
FROZEN_CODE,
LIFECYCLE_CODE,
CONFIG_CODE,
STORE_CODE,
CONTROL_PLANE_CODE,
UNAUTHORIZED_CODE,
AGENDA_NOT_FOUND_CODE,
AGENDA_STATE_CODE,
QUOTA_CODE,
SERVICE_CODE,
IO_CODE,
SERDE_CODE,
SPAWN_REJECTED_CODE,
UNSUPPORTED_CODE,
LEDGER_INVALID_CODE,
CROSSING_DENIED_CODE,
MEMORY_CROSSING_CODE,
MEMORY_DELETE_CODE,
AGENT_NOT_FOUND_CODE,
AGENT_INVALID_CODE,
AGENT_OUT_OF_DATE_CODE,
AGENT_REFUSED_CODE,
AGENT_UNCONFIRMED_CODE,
RESUME_NOT_HERE_CODE,
DECIDE_NOT_HERE_CODE,
];
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum KernelError {
#[error(
"no process {pid}: list the processes with `adk-rust ps` or `GET /api/kernel/processes`"
)]
NotFound {
pid: String,
},
#[error(
"process {pid} is {state:?}, so it cannot be {action}; check its state with \
`adk-rust ps`"
)]
InvalidState {
pid: String,
state: RunState,
action: &'static str,
},
#[error("the kernel is frozen ({reason}); lift the freeze with `adk-rust unfreeze`")]
Frozen {
reason: String,
},
#[error("the kernel is {state}, so it cannot {action}; check `adk-rust ps` or the health")]
Lifecycle {
state: KernelState,
action: &'static str,
},
#[error("invalid kernel configuration: {reason}")]
Config {
reason: String,
},
#[error(
"the {backend} kernel store failed: {reason}; check the store URL and that the server is reachable"
)]
Store {
backend: &'static str,
reason: String,
},
#[error("control plane: {reason}")]
ControlPlane {
reason: String,
},
#[error("unauthorized: {reason}")]
Unauthorized {
reason: String,
},
#[error(
"no agenda item {item}: list the agenda with `adk-rust agenda` or `GET /api/kernel/agenda`"
)]
AgendaNotFound {
item: String,
},
#[error(
"agenda item {item} is {state}, so it cannot be {action}; check it with `adk-rust agenda`"
)]
AgendaState {
item: String,
state: crate::agenda::AgendaStateKind,
action: &'static str,
},
#[error(
"partition {partition} is at its quota: {reason}; wait for its processes to finish or raise the quota"
)]
Quota {
partition: String,
reason: String,
},
#[error("kernel service: {reason}")]
Service {
reason: String,
},
#[error(transparent)]
Core(#[from] AdkError),
#[error("kernel I/O failed: {0}")]
Io(#[from] std::io::Error),
#[error("kernel record encoding failed: {0}")]
Serde(#[from] serde_json::Error),
}
impl KernelError {
pub fn code(&self) -> &'static str {
match self {
Self::NotFound { .. } => NOT_FOUND_CODE,
Self::InvalidState { .. } => INVALID_STATE_CODE,
Self::Frozen { .. } => FROZEN_CODE,
Self::Lifecycle { .. } => LIFECYCLE_CODE,
Self::Config { .. } => CONFIG_CODE,
Self::Store { .. } => STORE_CODE,
Self::ControlPlane { .. } => CONTROL_PLANE_CODE,
Self::Unauthorized { .. } => UNAUTHORIZED_CODE,
Self::AgendaNotFound { .. } => AGENDA_NOT_FOUND_CODE,
Self::AgendaState { .. } => AGENDA_STATE_CODE,
Self::Quota { .. } => QUOTA_CODE,
Self::Service { .. } => SERVICE_CODE,
Self::Core(error) => error.code,
Self::Io(_) => IO_CODE,
Self::Serde(_) => SERDE_CODE,
}
}
pub fn category(&self) -> ErrorCategory {
match self {
Self::NotFound { .. } | Self::AgendaNotFound { .. } => ErrorCategory::NotFound,
Self::InvalidState { .. } | Self::Lifecycle { .. } | Self::AgendaState { .. } => {
ErrorCategory::Conflict
}
Self::Quota { .. } => ErrorCategory::ResourceExhausted,
Self::Frozen { .. }
| Self::Store { .. }
| Self::ControlPlane { .. }
| Self::Service { .. } => ErrorCategory::Unavailable,
Self::Config { .. } => ErrorCategory::InvalidInput,
Self::Unauthorized { .. } => ErrorCategory::Unauthorized,
Self::Core(error) => error.category,
Self::Io(_) | Self::Serde(_) => ErrorCategory::Internal,
}
}
}
impl From<KernelError> for AdkError {
fn from(error: KernelError) -> Self {
match error {
KernelError::Core(inner) => inner,
other => AdkError::new(
ErrorComponent::Server,
other.category(),
other.code(),
other.to_string(),
),
}
}
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use super::*;
fn sources() -> Vec<(PathBuf, String)> {
let mut pending = vec![Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
let mut files = Vec::new();
while let Some(path) = pending.pop() {
if path.is_dir() {
pending
.extend(std::fs::read_dir(&path).unwrap().map(|entry| entry.unwrap().path()));
} else if path.extension().is_some_and(|extension| extension == "rs") {
let text = std::fs::read_to_string(&path).unwrap();
files.push((path, text));
}
}
files
}
fn argument(call: &str, index: usize) -> String {
let (mut depth, mut current, mut in_string, mut escaped) = (0usize, 0, false, false);
let mut text = String::new();
for c in call.chars() {
if in_string {
in_string = c != '"' || escaped;
escaped = c == '\\' && !escaped;
} else {
match c {
'"' => in_string = true,
'(' | '[' | '{' => depth += 1,
')' | ']' | '}' if depth == 0 => break,
')' | ']' | '}' => depth -= 1,
',' if depth == 0 => {
current += 1;
continue;
}
_ => {}
}
}
if current == index {
text.push(c);
}
}
text.trim().to_string()
}
#[test]
fn every_code_the_kernel_answers_with_is_listed() {
let mut constants = Vec::new();
let mut literals = Vec::new();
for (path, text) in sources() {
for line in text.lines() {
if let Some((_, value)) = line.split_once("_CODE: &str = \"")
&& let Some((code, _)) = value.split_once('"')
&& (code.starts_with("kernel.") || code.starts_with("surface."))
{
constants.push(code.to_string());
}
}
for call in text.split("AdkError::new(").skip(1) {
let code = argument(call, 2);
if code.starts_with("\"kernel.") {
literals.push(format!("{}: {code}", path.display()));
}
}
}
assert!(constants.len() >= CODES.len(), "the scan found {constants:?}");
let unlisted: Vec<_> =
constants.iter().filter(|code| !CODES.contains(&code.as_str())).collect();
assert!(unlisted.is_empty(), "add these codes to error::CODES: {unlisted:?}");
assert!(
literals.is_empty(),
"name these codes as `*_CODE` constants in error.rs and list them in CODES: \
{literals:?}"
);
}
#[test]
fn the_argument_scan_skips_nested_calls_and_strings() {
let call = r#"ErrorComponent::Server, f(a, b), "a, (b", format!("{x}, y"))"#;
assert_eq!(argument(call, 1), "f(a, b)");
assert_eq!(argument(call, 2), r#""a, (b""#);
assert_eq!(argument(call, 3), r#"format!("{x}, y")"#);
}
}