1use adk_core::{AdkError, ErrorCategory, ErrorComponent, RunState};
9use thiserror::Error;
10
11use crate::kernel::KernelState;
12
13pub type Result<T, E = KernelError> = std::result::Result<T, E>;
15
16pub const NOT_FOUND_CODE: &str = "kernel.not_found";
18pub const INVALID_STATE_CODE: &str = "kernel.invalid_state";
20pub const FROZEN_CODE: &str = "kernel.frozen";
22pub const LIFECYCLE_CODE: &str = "kernel.lifecycle";
24pub const CONFIG_CODE: &str = "kernel.config";
26pub const STORE_CODE: &str = "kernel.store";
28pub const CONTROL_PLANE_CODE: &str = "kernel.control_plane";
30pub const UNAUTHORIZED_CODE: &str = "kernel.unauthorized";
32pub const AGENDA_NOT_FOUND_CODE: &str = "kernel.agenda_not_found";
34pub const AGENDA_STATE_CODE: &str = "kernel.agenda_state";
36pub const QUOTA_CODE: &str = "kernel.quota";
38pub const SERVICE_CODE: &str = "kernel.service";
40pub const IO_CODE: &str = "kernel.io";
42pub const SERDE_CODE: &str = "kernel.serde";
44pub const SPAWN_REJECTED_CODE: &str = "kernel.spawn_rejected";
47pub const UNSUPPORTED_CODE: &str = "kernel.unsupported";
50pub const LEDGER_INVALID_CODE: &str = "kernel.ledger.invalid_row";
58pub const CROSSING_DENIED_CODE: &str = "kernel.partition.crossing_denied";
60pub const MEMORY_CROSSING_CODE: &str = "kernel.partition.memory_crossing";
63pub const MEMORY_DELETE_CODE: &str = "kernel.partition.memory_delete";
66pub const AGENT_NOT_FOUND_CODE: &str = "kernel.agent.not_found";
68pub const AGENT_INVALID_CODE: &str = "kernel.agent.invalid";
71pub const AGENT_OUT_OF_DATE_CODE: &str = "kernel.agent.out_of_date";
73pub const AGENT_REFUSED_CODE: &str = "kernel.agent.refused";
77pub const AGENT_UNCONFIRMED_CODE: &str = "kernel.agent.unconfirmed";
80pub const RESUME_NOT_HERE_CODE: &str = "kernel.resume.not_here";
89pub const DECIDE_NOT_HERE_CODE: &str = "surface.decide.not_here";
98
99pub(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#[derive(Debug, Error)]
149#[non_exhaustive]
150pub enum KernelError {
151 #[error(
153 "no process {pid}: list the processes with `adk-rust ps` or `GET /api/kernel/processes`"
154 )]
155 NotFound {
156 pid: String,
158 },
159
160 #[error(
162 "process {pid} is {state:?}, so it cannot be {action}; check its state with \
163 `adk-rust ps`"
164 )]
165 InvalidState {
166 pid: String,
168 state: RunState,
170 action: &'static str,
172 },
173
174 #[error("the kernel is frozen ({reason}); lift the freeze with `adk-rust unfreeze`")]
176 Frozen {
177 reason: String,
179 },
180
181 #[error("the kernel is {state}, so it cannot {action}; check `adk-rust ps` or the health")]
183 Lifecycle {
184 state: KernelState,
186 action: &'static str,
188 },
189
190 #[error("invalid kernel configuration: {reason}")]
192 Config {
193 reason: String,
195 },
196
197 #[error(
199 "the {backend} kernel store failed: {reason}; check the store URL and that the server is reachable"
200 )]
201 Store {
202 backend: &'static str,
204 reason: String,
206 },
207
208 #[error("control plane: {reason}")]
210 ControlPlane {
211 reason: String,
213 },
214
215 #[error("unauthorized: {reason}")]
217 Unauthorized {
218 reason: String,
220 },
221
222 #[error(
224 "no agenda item {item}: list the agenda with `adk-rust agenda` or `GET /api/kernel/agenda`"
225 )]
226 AgendaNotFound {
227 item: String,
229 },
230
231 #[error(
233 "agenda item {item} is {state}, so it cannot be {action}; check it with `adk-rust agenda`"
234 )]
235 AgendaState {
236 item: String,
238 state: crate::agenda::AgendaStateKind,
240 action: &'static str,
242 },
243
244 #[error(
246 "partition {partition} is at its quota: {reason}; wait for its processes to finish or raise the quota"
247 )]
248 Quota {
249 partition: String,
251 reason: String,
253 },
254
255 #[error("kernel service: {reason}")]
257 Service {
258 reason: String,
260 },
261
262 #[error(transparent)]
264 Core(#[from] AdkError),
265
266 #[error("kernel I/O failed: {0}")]
268 Io(#[from] std::io::Error),
269
270 #[error("kernel record encoding failed: {0}")]
272 Serde(#[from] serde_json::Error),
273}
274
275impl KernelError {
276 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 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 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 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 #[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}