1use axum::Json;
8use axum::http::StatusCode;
9use axum::response::{IntoResponse, Response};
10use ironflow_engine::error::MONTHLY_BUDGET_EXCEEDED_CODE;
11use ironflow_store::error::StoreError;
12use ironflow_types::ErrorEnvelope;
13use serde_json::{Value, json};
14use thiserror::Error;
15use tracing::{error, warn};
16use uuid::Uuid;
17
18#[derive(Debug, Error)]
32pub enum ApiError {
33 #[error("run not found")]
35 RunNotFound(Uuid),
36
37 #[error("step not found")]
39 StepNotFound(Uuid),
40
41 #[error("workflow not found")]
43 WorkflowNotFound(String),
44
45 #[error("{0}")]
47 BadRequest(String),
48
49 #[error("{0}")]
51 Conflict(String),
52
53 #[error("authentication required")]
55 Unauthorized,
56
57 #[error("invalid credentials")]
59 InvalidCredentials,
60
61 #[error("email already exists")]
63 DuplicateEmail,
64
65 #[error("username already exists")]
67 DuplicateUsername,
68
69 #[error("API key not found")]
71 ApiKeyNotFound(Uuid),
72
73 #[error("user not found")]
75 UserNotFound(Uuid),
76
77 #[error("insufficient permissions")]
79 Forbidden,
80
81 #[error("secret not found")]
83 SecretNotFound(String),
84
85 #[error("insufficient scope")]
87 InsufficientScope,
88
89 #[error("idempotency key already used with a different request")]
93 IdempotencyKeyConflict(Uuid),
94 #[error("{0}")]
98 MonthlyBudgetExceeded(String),
99
100 #[error("artifact not found")]
102 ArtifactNotFound(String),
103
104 #[error("artifact storage is not configured")]
109 ArtifactStorageUnavailable,
110
111 #[error("artifact exceeds the size limit")]
113 ArtifactTooLarge,
114
115 #[error("schedule not found")]
117 ScheduleNotFound(Uuid),
118
119 #[error("approval delegation not found")]
121 DelegationNotFound(Uuid),
122
123 #[error("database error")]
125 Store(StoreError),
126
127 #[error("internal server error")]
129 Internal(String),
130
131 #[error("upstream service unavailable")]
133 BadGateway(String),
134
135 #[error("input does not match the expected schema")]
140 InvalidInput(Vec<String>),
141}
142
143impl From<StoreError> for ApiError {
144 fn from(e: StoreError) -> Self {
145 match e {
146 StoreError::ScheduleNotFound(id) => ApiError::ScheduleNotFound(id),
147 StoreError::DelegationNotFound(id) => ApiError::DelegationNotFound(id),
148 other => ApiError::Store(other),
149 }
150 }
151}
152
153impl ApiError {
154 fn code(&self) -> &str {
156 match self {
157 ApiError::RunNotFound(_) => "RUN_NOT_FOUND",
158 ApiError::StepNotFound(_) => "STEP_NOT_FOUND",
159 ApiError::WorkflowNotFound(_) => "WORKFLOW_NOT_FOUND",
160 ApiError::BadRequest(_) => "BAD_REQUEST",
161 ApiError::Conflict(_) => "CONFLICT",
162 ApiError::Unauthorized => "UNAUTHORIZED",
163 ApiError::InvalidCredentials => "INVALID_CREDENTIALS",
164 ApiError::DuplicateEmail => "DUPLICATE_EMAIL",
165 ApiError::DuplicateUsername => "DUPLICATE_USERNAME",
166 ApiError::ApiKeyNotFound(_) => "API_KEY_NOT_FOUND",
167 ApiError::UserNotFound(_) => "USER_NOT_FOUND",
168 ApiError::SecretNotFound(_) => "SECRET_NOT_FOUND",
169 ApiError::Forbidden => "FORBIDDEN",
170 ApiError::InsufficientScope => "INSUFFICIENT_SCOPE",
171 ApiError::IdempotencyKeyConflict(_) => "IDEMPOTENCY_KEY_CONFLICT",
172 ApiError::MonthlyBudgetExceeded(_) => MONTHLY_BUDGET_EXCEEDED_CODE,
173 ApiError::ArtifactNotFound(_) => "ARTIFACT_NOT_FOUND",
174 ApiError::ArtifactStorageUnavailable => "ARTIFACT_STORAGE_UNAVAILABLE",
175 ApiError::ArtifactTooLarge => "ARTIFACT_TOO_LARGE",
176 ApiError::ScheduleNotFound(_) => "SCHEDULE_NOT_FOUND",
177 ApiError::DelegationNotFound(_) => "DELEGATION_NOT_FOUND",
178 ApiError::Store(StoreError::Crypto(_)) => "SECRET_STORE_UNAVAILABLE",
179 ApiError::Store(StoreError::DuplicateArtifact { .. }) => "DUPLICATE_ARTIFACT",
180 ApiError::Store(StoreError::LeaseLost { .. }) => "LEASE_LOST",
181 ApiError::Store(_) => "DATABASE_ERROR",
182 ApiError::Internal(_) => "INTERNAL_ERROR",
183 ApiError::BadGateway(_) => "BAD_GATEWAY",
184 ApiError::InvalidInput(_) => "INVALID_INPUT",
185 }
186 }
187
188 fn status(&self) -> StatusCode {
190 match self {
191 ApiError::RunNotFound(_) => StatusCode::NOT_FOUND,
192 ApiError::StepNotFound(_) => StatusCode::NOT_FOUND,
193 ApiError::WorkflowNotFound(_) => StatusCode::NOT_FOUND,
194 ApiError::SecretNotFound(_) => StatusCode::NOT_FOUND,
195 ApiError::BadRequest(_) => StatusCode::BAD_REQUEST,
196 ApiError::Conflict(_) => StatusCode::CONFLICT,
197 ApiError::Unauthorized => StatusCode::UNAUTHORIZED,
198 ApiError::InvalidCredentials => StatusCode::UNAUTHORIZED,
199 ApiError::DuplicateEmail => StatusCode::CONFLICT,
200 ApiError::DuplicateUsername => StatusCode::CONFLICT,
201 ApiError::ApiKeyNotFound(_) => StatusCode::NOT_FOUND,
202 ApiError::UserNotFound(_) => StatusCode::NOT_FOUND,
203 ApiError::Forbidden => StatusCode::FORBIDDEN,
204 ApiError::InsufficientScope => StatusCode::FORBIDDEN,
205 ApiError::IdempotencyKeyConflict(_) => StatusCode::CONFLICT,
206 ApiError::MonthlyBudgetExceeded(_) => StatusCode::TOO_MANY_REQUESTS,
207 ApiError::ArtifactNotFound(_) => StatusCode::NOT_FOUND,
208 ApiError::ArtifactStorageUnavailable => StatusCode::NOT_IMPLEMENTED,
209 ApiError::ArtifactTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
210 ApiError::ScheduleNotFound(_) => StatusCode::NOT_FOUND,
211 ApiError::DelegationNotFound(_) => StatusCode::NOT_FOUND,
212 ApiError::Store(StoreError::Crypto(_)) => StatusCode::NOT_IMPLEMENTED,
213 ApiError::Store(StoreError::DuplicateArtifact { .. }) => StatusCode::CONFLICT,
214 ApiError::Store(StoreError::LeaseLost { .. }) => StatusCode::CONFLICT,
215 ApiError::Store(_) => StatusCode::INTERNAL_SERVER_ERROR,
216 ApiError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
217 ApiError::BadGateway(_) => StatusCode::BAD_GATEWAY,
218 ApiError::InvalidInput(_) => StatusCode::UNPROCESSABLE_ENTITY,
219 }
220 }
221
222 fn details(&self) -> Option<Value> {
227 match self {
228 ApiError::IdempotencyKeyConflict(run_id) => Some(json!({ "run_id": run_id })),
229 ApiError::InvalidInput(errors) => Some(json!({ "errors": errors })),
230 _ => None,
231 }
232 }
233}
234
235impl IntoResponse for ApiError {
236 fn into_response(self) -> Response {
237 let status = self.status();
238 let code = self.code().to_string();
239 let details = self.details();
240
241 let message = match &self {
242 ApiError::Store(StoreError::Crypto(_)) => {
243 "secret store not configured (set IRONFLOW_SECRET_KEYS)".to_string()
244 }
245 ApiError::Store(e @ StoreError::LeaseLost { .. }) => e.to_string(),
248 _ => self.to_string(),
249 };
250
251 match &self {
252 ApiError::Store(e @ StoreError::LeaseLost { .. }) => {
255 warn!(error = %e, code = %code, "lease refused")
256 }
257 ApiError::Store(e) => error!(error = %e, code = %code, "store error"),
258 ApiError::Internal(detail) => {
259 error!(detail = %detail, code = %code, "internal error")
260 }
261 _ => {}
262 }
263
264 let envelope = ErrorEnvelope {
265 code,
266 message,
267 details,
268 };
269
270 (status, Json(json!({ "error": envelope }))).into_response()
271 }
272}
273
274#[cfg(test)]
275mod tests {
276 use super::*;
277
278 #[test]
279 fn run_not_found_code() {
280 let err = ApiError::RunNotFound(Uuid::nil());
281 assert_eq!(err.code(), "RUN_NOT_FOUND");
282 }
283
284 #[test]
285 fn run_not_found_status() {
286 let err = ApiError::RunNotFound(Uuid::nil());
287 assert_eq!(err.status(), StatusCode::NOT_FOUND);
288 }
289
290 #[test]
291 fn bad_request_status() {
292 let err = ApiError::BadRequest("invalid field".to_string());
293 assert_eq!(err.status(), StatusCode::BAD_REQUEST);
294 assert_eq!(err.code(), "BAD_REQUEST");
295 }
296
297 #[test]
298 fn conflict_status() {
299 let err = ApiError::Conflict("run is already waiting for a retry".to_string());
300 assert_eq!(err.status(), StatusCode::CONFLICT);
301 assert_eq!(err.code(), "CONFLICT");
302 }
303
304 #[test]
305 fn invalid_input_status_and_details() {
306 let err = ApiError::InvalidInput(vec!["\"answers\" is a required property".to_string()]);
307 assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
308 assert_eq!(err.code(), "INVALID_INPUT");
309 assert_eq!(
310 err.details(),
311 Some(json!({ "errors": ["\"answers\" is a required property"] }))
312 );
313 }
314
315 #[test]
316 fn internal_error_status() {
317 let err = ApiError::Internal("something went wrong".to_string());
318 assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
319 assert_eq!(err.code(), "INTERNAL_ERROR");
320 }
321
322 #[test]
323 fn error_to_response() {
324 let err = ApiError::BadRequest("invalid input".to_string());
325 let response = err.into_response();
326 assert_eq!(response.status(), StatusCode::BAD_REQUEST);
327 }
328
329 #[test]
330 fn unauthorized_status() {
331 let err = ApiError::Unauthorized;
332 assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
333 assert_eq!(err.code(), "UNAUTHORIZED");
334 }
335
336 #[test]
337 fn invalid_credentials_status() {
338 let err = ApiError::InvalidCredentials;
339 assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
340 assert_eq!(err.code(), "INVALID_CREDENTIALS");
341 }
342
343 #[test]
344 fn duplicate_email_status() {
345 let err = ApiError::DuplicateEmail;
346 assert_eq!(err.status(), StatusCode::CONFLICT);
347 assert_eq!(err.code(), "DUPLICATE_EMAIL");
348 }
349
350 #[test]
351 fn duplicate_username_status() {
352 let err = ApiError::DuplicateUsername;
353 assert_eq!(err.status(), StatusCode::CONFLICT);
354 assert_eq!(err.code(), "DUPLICATE_USERNAME");
355 }
356
357 #[test]
358 fn workflow_not_found_status() {
359 let err = ApiError::WorkflowNotFound("test".to_string());
360 assert_eq!(err.status(), StatusCode::NOT_FOUND);
361 assert_eq!(err.code(), "WORKFLOW_NOT_FOUND");
362 }
363
364 #[test]
365 fn step_not_found_status() {
366 let err = ApiError::StepNotFound(Uuid::nil());
367 assert_eq!(err.status(), StatusCode::NOT_FOUND);
368 assert_eq!(err.code(), "STEP_NOT_FOUND");
369 }
370
371 #[test]
372 fn user_not_found_status() {
373 let err = ApiError::UserNotFound(Uuid::nil());
374 assert_eq!(err.status(), StatusCode::NOT_FOUND);
375 assert_eq!(err.code(), "USER_NOT_FOUND");
376 }
377
378 #[test]
379 fn forbidden_status() {
380 let err = ApiError::Forbidden;
381 assert_eq!(err.status(), StatusCode::FORBIDDEN);
382 assert_eq!(err.code(), "FORBIDDEN");
383 }
384
385 #[test]
386 fn secret_not_found_status() {
387 let err = ApiError::SecretNotFound("demo/api-key".to_string());
388 assert_eq!(err.status(), StatusCode::NOT_FOUND);
389 assert_eq!(err.code(), "SECRET_NOT_FOUND");
390 }
391
392 #[test]
393 fn delegation_not_found_status_and_code() {
394 let err = ApiError::DelegationNotFound(Uuid::nil());
395 assert_eq!(err.status(), StatusCode::NOT_FOUND);
396 assert_eq!(err.code(), "DELEGATION_NOT_FOUND");
397 }
398
399 #[test]
400 fn monthly_budget_exceeded_status_and_code() {
401 let err = ApiError::MonthlyBudgetExceeded("quota exhausted".to_string());
402 assert_eq!(err.status(), StatusCode::TOO_MANY_REQUESTS);
403 assert_eq!(err.code(), "MONTHLY_BUDGET_EXCEEDED");
404 assert_eq!(err.to_string(), "quota exhausted");
405 }
406}