ironflow-api 2.40.7

REST API for ironflow run management and observability
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! REST API error types and responses.
//!
//! [`ApiError`] is the primary error type for all API handlers. It implements
//! [`IntoResponse`] to serialize errors to JSON
//! with proper HTTP status codes.

use axum::Json;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use ironflow_engine::error::MONTHLY_BUDGET_EXCEEDED_CODE;
use ironflow_store::error::StoreError;
use ironflow_types::ErrorEnvelope;
use serde_json::{Value, json};
use thiserror::Error;
use tracing::{error, warn};
use uuid::Uuid;

/// Error type for REST API operations.
///
/// Maps to appropriate HTTP status codes and error codes in the JSON response.
///
/// # Examples
///
/// ```
/// use ironflow_api::error::ApiError;
/// use uuid::Uuid;
///
/// let err = ApiError::RunNotFound(Uuid::nil());
/// assert_eq!(err.to_string(), "run not found");
/// ```
#[derive(Debug, Error)]
pub enum ApiError {
    /// The requested run does not exist (404).
    #[error("run not found")]
    RunNotFound(Uuid),

    /// The requested step does not exist (404).
    #[error("step not found")]
    StepNotFound(Uuid),

    /// Workflow not found (404).
    #[error("workflow not found")]
    WorkflowNotFound(String),

    /// Bad request: invalid input (400).
    #[error("{0}")]
    BadRequest(String),

    /// The request conflicts with the current state of the resource (409).
    #[error("{0}")]
    Conflict(String),

    /// Authentication required (401).
    #[error("authentication required")]
    Unauthorized,

    /// Invalid credentials (401).
    #[error("invalid credentials")]
    InvalidCredentials,

    /// Email already taken (409).
    #[error("email already exists")]
    DuplicateEmail,

    /// Username already taken (409).
    #[error("username already exists")]
    DuplicateUsername,

    /// API key not found (404).
    #[error("API key not found")]
    ApiKeyNotFound(Uuid),

    /// User not found (404).
    #[error("user not found")]
    UserNotFound(Uuid),

    /// Insufficient permissions for this action (403).
    #[error("insufficient permissions")]
    Forbidden,

    /// Secret not found (404).
    #[error("secret not found")]
    SecretNotFound(String),

    /// Insufficient scope (403).
    #[error("insufficient scope")]
    InsufficientScope,

    /// The idempotency key is already bound to a different request (409).
    ///
    /// Carries the run holding the key so the client can inspect it.
    #[error("idempotency key already used with a different request")]
    IdempotencyKeyConflict(Uuid),
    /// The global monthly cost quota is exhausted (429).
    ///
    /// Only blocks the creation of new runs; runs already in flight continue.
    #[error("{0}")]
    MonthlyBudgetExceeded(String),

    /// The requested artifact does not exist (404).
    #[error("artifact not found")]
    ArtifactNotFound(String),

    /// No artifact storage backend is configured (501).
    ///
    /// Every other endpoint keeps working: an upgraded deployment that has not
    /// opted into artifacts is degraded here only.
    #[error("artifact storage is not configured")]
    ArtifactStorageUnavailable,

    /// The uploaded payload exceeded the artifact size limit (413).
    #[error("artifact exceeds the size limit")]
    ArtifactTooLarge,

    /// Schedule not found (404).
    #[error("schedule not found")]
    ScheduleNotFound(Uuid),

    /// Approval delegation not found (404).
    #[error("approval delegation not found")]
    DelegationNotFound(Uuid),

    /// Store operation failed (500).
    #[error("database error")]
    Store(StoreError),

    /// Internal server error (500).
    #[error("internal server error")]
    Internal(String),

    /// An upstream service is unreachable or returned an error (502).
    #[error("upstream service unavailable")]
    BadGateway(String),

    /// A submitted value does not match the expected JSON schema (422).
    ///
    /// Carries one human-readable message per violation, returned to the
    /// caller under `details.errors`.
    #[error("input does not match the expected schema")]
    InvalidInput(Vec<String>),
}

impl From<StoreError> for ApiError {
    fn from(e: StoreError) -> Self {
        match e {
            StoreError::ScheduleNotFound(id) => ApiError::ScheduleNotFound(id),
            StoreError::DelegationNotFound(id) => ApiError::DelegationNotFound(id),
            other => ApiError::Store(other),
        }
    }
}

impl ApiError {
    /// Return the error code for JSON serialization.
    fn code(&self) -> &str {
        match self {
            ApiError::RunNotFound(_) => "RUN_NOT_FOUND",
            ApiError::StepNotFound(_) => "STEP_NOT_FOUND",
            ApiError::WorkflowNotFound(_) => "WORKFLOW_NOT_FOUND",
            ApiError::BadRequest(_) => "BAD_REQUEST",
            ApiError::Conflict(_) => "CONFLICT",
            ApiError::Unauthorized => "UNAUTHORIZED",
            ApiError::InvalidCredentials => "INVALID_CREDENTIALS",
            ApiError::DuplicateEmail => "DUPLICATE_EMAIL",
            ApiError::DuplicateUsername => "DUPLICATE_USERNAME",
            ApiError::ApiKeyNotFound(_) => "API_KEY_NOT_FOUND",
            ApiError::UserNotFound(_) => "USER_NOT_FOUND",
            ApiError::SecretNotFound(_) => "SECRET_NOT_FOUND",
            ApiError::Forbidden => "FORBIDDEN",
            ApiError::InsufficientScope => "INSUFFICIENT_SCOPE",
            ApiError::IdempotencyKeyConflict(_) => "IDEMPOTENCY_KEY_CONFLICT",
            ApiError::MonthlyBudgetExceeded(_) => MONTHLY_BUDGET_EXCEEDED_CODE,
            ApiError::ArtifactNotFound(_) => "ARTIFACT_NOT_FOUND",
            ApiError::ArtifactStorageUnavailable => "ARTIFACT_STORAGE_UNAVAILABLE",
            ApiError::ArtifactTooLarge => "ARTIFACT_TOO_LARGE",
            ApiError::ScheduleNotFound(_) => "SCHEDULE_NOT_FOUND",
            ApiError::DelegationNotFound(_) => "DELEGATION_NOT_FOUND",
            ApiError::Store(StoreError::Crypto(_)) => "SECRET_STORE_UNAVAILABLE",
            ApiError::Store(StoreError::DuplicateArtifact { .. }) => "DUPLICATE_ARTIFACT",
            ApiError::Store(StoreError::LeaseLost { .. }) => "LEASE_LOST",
            ApiError::Store(_) => "DATABASE_ERROR",
            ApiError::Internal(_) => "INTERNAL_ERROR",
            ApiError::BadGateway(_) => "BAD_GATEWAY",
            ApiError::InvalidInput(_) => "INVALID_INPUT",
        }
    }

    /// Return the HTTP status code for this error.
    fn status(&self) -> StatusCode {
        match self {
            ApiError::RunNotFound(_) => StatusCode::NOT_FOUND,
            ApiError::StepNotFound(_) => StatusCode::NOT_FOUND,
            ApiError::WorkflowNotFound(_) => StatusCode::NOT_FOUND,
            ApiError::SecretNotFound(_) => StatusCode::NOT_FOUND,
            ApiError::BadRequest(_) => StatusCode::BAD_REQUEST,
            ApiError::Conflict(_) => StatusCode::CONFLICT,
            ApiError::Unauthorized => StatusCode::UNAUTHORIZED,
            ApiError::InvalidCredentials => StatusCode::UNAUTHORIZED,
            ApiError::DuplicateEmail => StatusCode::CONFLICT,
            ApiError::DuplicateUsername => StatusCode::CONFLICT,
            ApiError::ApiKeyNotFound(_) => StatusCode::NOT_FOUND,
            ApiError::UserNotFound(_) => StatusCode::NOT_FOUND,
            ApiError::Forbidden => StatusCode::FORBIDDEN,
            ApiError::InsufficientScope => StatusCode::FORBIDDEN,
            ApiError::IdempotencyKeyConflict(_) => StatusCode::CONFLICT,
            ApiError::MonthlyBudgetExceeded(_) => StatusCode::TOO_MANY_REQUESTS,
            ApiError::ArtifactNotFound(_) => StatusCode::NOT_FOUND,
            ApiError::ArtifactStorageUnavailable => StatusCode::NOT_IMPLEMENTED,
            ApiError::ArtifactTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
            ApiError::ScheduleNotFound(_) => StatusCode::NOT_FOUND,
            ApiError::DelegationNotFound(_) => StatusCode::NOT_FOUND,
            ApiError::Store(StoreError::Crypto(_)) => StatusCode::NOT_IMPLEMENTED,
            ApiError::Store(StoreError::DuplicateArtifact { .. }) => StatusCode::CONFLICT,
            ApiError::Store(StoreError::LeaseLost { .. }) => StatusCode::CONFLICT,
            ApiError::Store(_) => StatusCode::INTERNAL_SERVER_ERROR,
            ApiError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
            ApiError::BadGateway(_) => StatusCode::BAD_GATEWAY,
            ApiError::InvalidInput(_) => StatusCode::UNPROCESSABLE_ENTITY,
        }
    }

    /// Structured context attached to the JSON error body, if any.
    ///
    /// Never carries internal detail: only identifiers the caller is already
    /// entitled to see.
    fn details(&self) -> Option<Value> {
        match self {
            ApiError::IdempotencyKeyConflict(run_id) => Some(json!({ "run_id": run_id })),
            ApiError::InvalidInput(errors) => Some(json!({ "errors": errors })),
            _ => None,
        }
    }
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let status = self.status();
        let code = self.code().to_string();
        let details = self.details();

        let message = match &self {
            ApiError::Store(StoreError::Crypto(_)) => {
                "secret store not configured (set IRONFLOW_SECRET_KEYS)".to_string()
            }
            // Carries the caller-facing detail in its own Display impl,
            // unlike the generic "database error" of ApiError::Store.
            ApiError::Store(e @ StoreError::LeaseLost { .. }) => e.to_string(),
            _ => self.to_string(),
        };

        match &self {
            // A lost lease is a client-side condition, not a server fault:
            // it must not page anyone.
            ApiError::Store(e @ StoreError::LeaseLost { .. }) => {
                warn!(error = %e, code = %code, "lease refused")
            }
            ApiError::Store(e) => error!(error = %e, code = %code, "store error"),
            ApiError::Internal(detail) => {
                error!(detail = %detail, code = %code, "internal error")
            }
            _ => {}
        }

        let envelope = ErrorEnvelope {
            code,
            message,
            details,
        };

        (status, Json(json!({ "error": envelope }))).into_response()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn run_not_found_code() {
        let err = ApiError::RunNotFound(Uuid::nil());
        assert_eq!(err.code(), "RUN_NOT_FOUND");
    }

    #[test]
    fn run_not_found_status() {
        let err = ApiError::RunNotFound(Uuid::nil());
        assert_eq!(err.status(), StatusCode::NOT_FOUND);
    }

    #[test]
    fn bad_request_status() {
        let err = ApiError::BadRequest("invalid field".to_string());
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
        assert_eq!(err.code(), "BAD_REQUEST");
    }

    #[test]
    fn conflict_status() {
        let err = ApiError::Conflict("run is already waiting for a retry".to_string());
        assert_eq!(err.status(), StatusCode::CONFLICT);
        assert_eq!(err.code(), "CONFLICT");
    }

    #[test]
    fn invalid_input_status_and_details() {
        let err = ApiError::InvalidInput(vec!["\"answers\" is a required property".to_string()]);
        assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
        assert_eq!(err.code(), "INVALID_INPUT");
        assert_eq!(
            err.details(),
            Some(json!({ "errors": ["\"answers\" is a required property"] }))
        );
    }

    #[test]
    fn internal_error_status() {
        let err = ApiError::Internal("something went wrong".to_string());
        assert_eq!(err.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(err.code(), "INTERNAL_ERROR");
    }

    #[test]
    fn error_to_response() {
        let err = ApiError::BadRequest("invalid input".to_string());
        let response = err.into_response();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn unauthorized_status() {
        let err = ApiError::Unauthorized;
        assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(err.code(), "UNAUTHORIZED");
    }

    #[test]
    fn invalid_credentials_status() {
        let err = ApiError::InvalidCredentials;
        assert_eq!(err.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(err.code(), "INVALID_CREDENTIALS");
    }

    #[test]
    fn duplicate_email_status() {
        let err = ApiError::DuplicateEmail;
        assert_eq!(err.status(), StatusCode::CONFLICT);
        assert_eq!(err.code(), "DUPLICATE_EMAIL");
    }

    #[test]
    fn duplicate_username_status() {
        let err = ApiError::DuplicateUsername;
        assert_eq!(err.status(), StatusCode::CONFLICT);
        assert_eq!(err.code(), "DUPLICATE_USERNAME");
    }

    #[test]
    fn workflow_not_found_status() {
        let err = ApiError::WorkflowNotFound("test".to_string());
        assert_eq!(err.status(), StatusCode::NOT_FOUND);
        assert_eq!(err.code(), "WORKFLOW_NOT_FOUND");
    }

    #[test]
    fn step_not_found_status() {
        let err = ApiError::StepNotFound(Uuid::nil());
        assert_eq!(err.status(), StatusCode::NOT_FOUND);
        assert_eq!(err.code(), "STEP_NOT_FOUND");
    }

    #[test]
    fn user_not_found_status() {
        let err = ApiError::UserNotFound(Uuid::nil());
        assert_eq!(err.status(), StatusCode::NOT_FOUND);
        assert_eq!(err.code(), "USER_NOT_FOUND");
    }

    #[test]
    fn forbidden_status() {
        let err = ApiError::Forbidden;
        assert_eq!(err.status(), StatusCode::FORBIDDEN);
        assert_eq!(err.code(), "FORBIDDEN");
    }

    #[test]
    fn secret_not_found_status() {
        let err = ApiError::SecretNotFound("demo/api-key".to_string());
        assert_eq!(err.status(), StatusCode::NOT_FOUND);
        assert_eq!(err.code(), "SECRET_NOT_FOUND");
    }

    #[test]
    fn delegation_not_found_status_and_code() {
        let err = ApiError::DelegationNotFound(Uuid::nil());
        assert_eq!(err.status(), StatusCode::NOT_FOUND);
        assert_eq!(err.code(), "DELEGATION_NOT_FOUND");
    }

    #[test]
    fn monthly_budget_exceeded_status_and_code() {
        let err = ApiError::MonthlyBudgetExceeded("quota exhausted".to_string());
        assert_eq!(err.status(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(err.code(), "MONTHLY_BUDGET_EXCEEDED");
        assert_eq!(err.to_string(), "quota exhausted");
    }
}