agentmux_srv/server/
api_error.rs1use axum::http::StatusCode;
19use axum::response::{IntoResponse, Response};
20use axum::Json;
21use serde_json::json;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub(crate) enum ErrorKind {
26 Refused,
28 NotFound,
30 BadRequest,
32 Conflict,
34 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 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#[derive(Debug, Clone, PartialEq, Eq)]
69pub(crate) struct ApiError {
70 kind: ErrorKind,
71 message: String,
72}
73
74impl ApiError {
75 pub(crate) fn refused(message: impl Into<String>) -> Self {
77 ApiError { kind: ErrorKind::Refused, message: message.into() }
78 }
79
80 pub(crate) fn not_found(message: impl Into<String>) -> Self {
82 ApiError { kind: ErrorKind::NotFound, message: message.into() }
83 }
84
85 pub(crate) fn bad_request(message: impl Into<String>) -> Self {
87 ApiError { kind: ErrorKind::BadRequest, message: message.into() }
88 }
89
90 pub(crate) fn conflict(message: impl Into<String>) -> Self {
93 ApiError { kind: ErrorKind::Conflict, message: message.into() }
94 }
95
96 pub(crate) fn internal(message: impl Into<String>) -> Self {
98 ApiError { kind: ErrorKind::Internal, message: message.into() }
99 }
100
101 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 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 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 #[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}