Skip to main content

agentmux_srv/server/
api_error.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One error for an HTTP answer that is not a success: what kind of failure it is, and the words
5//! the caller reads.
6//!
7//! The kind decides the HTTP status. The words are for the agent or person who reads them and
8//! decide nothing: a refusal may keep its `FORBIDDEN:` prefix because callers know it, not because
9//! anything reads it. Code that knows why it fails says so ([`ApiError::refused`],
10//! [`ApiError::not_found`], [`ApiError::bad_request`], [`ApiError::conflict`],
11//! [`ApiError::internal`]).
12//!
13//! Most of the service layer still returns a plain `String`. Such an error becomes an `ApiError`
14//! through `From<String>`, which reads the kind from the text as the routes always did
15//! ([`ErrorKind::of_text`]). `tests/api_error_status_tests.rs` pins the status of every message
16//! in use, so giving an error its kind where it is made cannot move a status unseen.
17
18use axum::http::StatusCode;
19use axum::response::{IntoResponse, Response};
20use axum::Json;
21use serde_json::json;
22
23/// Why a request was not served.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub(crate) enum ErrorKind {
26    /// The caller may not do this: 403.
27    Refused,
28    /// What the caller named does not exist: 404.
29    NotFound,
30    /// The request cannot be served as it was written: 400.
31    BadRequest,
32    /// The request is right, and cannot be served as things stand now: 409.
33    Conflict,
34    /// The service failed: 500.
35    Internal,
36}
37
38impl ErrorKind {
39    pub(crate) fn status(self) -> StatusCode {
40        match self {
41            ErrorKind::Refused => StatusCode::FORBIDDEN,
42            ErrorKind::NotFound => StatusCode::NOT_FOUND,
43            ErrorKind::BadRequest => StatusCode::BAD_REQUEST,
44            ErrorKind::Conflict => StatusCode::CONFLICT,
45            ErrorKind::Internal => StatusCode::INTERNAL_SERVER_ERROR,
46        }
47    }
48
49    /// The kind of an error that is still a plain string, read from its text. FORBIDDEN is a
50    /// refusal. "not found" is a missing thing: a caller holding a stale or unknown id names a
51    /// missing resource, not a malformed request (SPEC_WINDOW_NAME_API_HARDENING_2026_08_08.md
52    /// ยง3.2). Argument errors are bad requests. Everything unrecognized is a fault of the service
53    /// (e.g. SQLite write failures).
54    pub(crate) fn of_text(e: &str) -> ErrorKind {
55        if e.starts_with("FORBIDDEN") {
56            ErrorKind::Refused
57        } else if e.contains("not found") {
58            ErrorKind::NotFound
59        } else if e.contains("provide ") || e.contains("not a regular file") || e.contains("too large") || e.contains("invalid") {
60            ErrorKind::BadRequest
61        } else {
62            ErrorKind::Internal
63        }
64    }
65}
66
67/// An error an HTTP route answers with: `{"error": message}` under the status of its kind.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub(crate) struct ApiError {
70    kind: ErrorKind,
71    message: String,
72}
73
74impl ApiError {
75    /// The caller may not do this. The message keeps whatever prefix its readers know.
76    pub(crate) fn refused(message: impl Into<String>) -> Self {
77        ApiError { kind: ErrorKind::Refused, message: message.into() }
78    }
79
80    /// What the caller named does not exist.
81    pub(crate) fn not_found(message: impl Into<String>) -> Self {
82        ApiError { kind: ErrorKind::NotFound, message: message.into() }
83    }
84
85    /// The request cannot be served as it was written.
86    pub(crate) fn bad_request(message: impl Into<String>) -> Self {
87        ApiError { kind: ErrorKind::BadRequest, message: message.into() }
88    }
89
90    /// Nothing in the request is wrong, and it cannot be served as things stand now: the caller
91    /// can do nothing about it by writing the request differently.
92    pub(crate) fn conflict(message: impl Into<String>) -> Self {
93        ApiError { kind: ErrorKind::Conflict, message: message.into() }
94    }
95
96    /// The service failed: the store, the file system, a state that should not exist.
97    pub(crate) fn internal(message: impl Into<String>) -> Self {
98        ApiError { kind: ErrorKind::Internal, message: message.into() }
99    }
100
101    /// This error under the name of the call that met it: `<call>: <message>`. The kind is the
102    /// same, so an error passed up keeps its status whatever is written before its words.
103    pub(crate) fn under(self, call: &str) -> Self {
104        ApiError { kind: self.kind, message: format!("{call}: {}", self.message) }
105    }
106
107    pub(crate) fn status(&self) -> StatusCode {
108        self.kind.status()
109    }
110}
111
112impl From<String> for ApiError {
113    /// An error that is still a plain string: its kind is read from its text.
114    fn from(message: String) -> Self {
115        ApiError { kind: ErrorKind::of_text(&message), message }
116    }
117}
118
119impl From<crate::server::account_episodes::SwitchError> for ApiError {
120    /// The status of each reason an account switch did not happen. This match is the one place
121    /// that decides it.
122    fn from(e: crate::server::account_episodes::SwitchError) -> Self {
123        use crate::server::account_episodes::SwitchRefusal;
124        let kind = match e.reason() {
125            SwitchRefusal::NoAgentNamed | SwitchRefusal::AgentNameShared | SwitchRefusal::AccountNameShared | SwitchRefusal::KeyNotForThisAgent => ErrorKind::BadRequest,
126            SwitchRefusal::UnknownAgent | SwitchRefusal::NoSuchAccount => ErrorKind::NotFound,
127            SwitchRefusal::NoQuota | SwitchRefusal::CantRun => ErrorKind::Conflict,
128            SwitchRefusal::Failed => ErrorKind::Internal,
129        };
130        ApiError { kind, message: e.to_string() }
131    }
132}
133
134impl std::fmt::Display for ApiError {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        f.write_str(&self.message)
137    }
138}
139
140impl IntoResponse for ApiError {
141    fn into_response(self) -> Response {
142        (self.status(), Json(json!({ "error": self.message }))).into_response()
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    async fn body(response: Response) -> serde_json::Value {
151        serde_json::from_slice(&axum::body::to_bytes(response.into_body(), 4096).await.unwrap()).unwrap()
152    }
153
154    /// The status is the kind's, whatever the words say.
155    #[tokio::test]
156    async fn the_status_is_the_kinds_and_the_body_is_the_message() {
157        let cases = [
158            (ApiError::refused("the entry was not found"), StatusCode::FORBIDDEN),
159            (ApiError::not_found("FORBIDDEN: no"), StatusCode::NOT_FOUND),
160            (ApiError::bad_request("database is locked"), StatusCode::BAD_REQUEST),
161            (ApiError::conflict("the entry was not found"), StatusCode::CONFLICT),
162            (ApiError::internal("memory.diff: version 12 not found"), StatusCode::INTERNAL_SERVER_ERROR),
163            (ApiError::not_found("calling agent uid-1 has no row").under("memory.list"), StatusCode::NOT_FOUND),
164            (ApiError::from("database is locked".to_string()), StatusCode::INTERNAL_SERVER_ERROR),
165        ];
166        for (error, status) in cases {
167            let message = error.to_string();
168            let response = error.into_response();
169            assert_eq!(response.status(), status, "{message}");
170            assert_eq!(body(response).await, json!({ "error": message }));
171        }
172    }
173}