arqen 0.3.0

Backend infrastructure for agent-ready applications
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[cfg(feature = "http-server")]
use axum::http::StatusCode;
#[cfg(feature = "http-server")]
use axum::response::{IntoResponse, Response};

/// Stable error codes for API responses.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode {
    NotFound,
    Validation,
    Authentication,
    Authorization,
    Conflict,
    RateLimited,
    Internal,
    External,
    Unavailable,
}

impl ErrorCode {
    /// Map error code to HTTP status code.
    pub fn status_code(&self) -> StatusCode {
        match self {
            ErrorCode::NotFound => StatusCode::NOT_FOUND,
            ErrorCode::Validation => StatusCode::BAD_REQUEST,
            ErrorCode::Authentication => StatusCode::UNAUTHORIZED,
            ErrorCode::Authorization => StatusCode::FORBIDDEN,
            ErrorCode::Conflict => StatusCode::CONFLICT,
            ErrorCode::RateLimited => StatusCode::TOO_MANY_REQUESTS,
            ErrorCode::Internal => StatusCode::INTERNAL_SERVER_ERROR,
            ErrorCode::External => StatusCode::BAD_GATEWAY,
            ErrorCode::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
        }
    }
}

impl std::fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ErrorCode::NotFound => write!(f, "not_found"),
            ErrorCode::Validation => write!(f, "validation"),
            ErrorCode::Authentication => write!(f, "authentication"),
            ErrorCode::Authorization => write!(f, "authorization"),
            ErrorCode::Conflict => write!(f, "conflict"),
            ErrorCode::RateLimited => write!(f, "rate_limited"),
            ErrorCode::Internal => write!(f, "internal"),
            ErrorCode::External => write!(f, "external"),
            ErrorCode::Unavailable => write!(f, "unavailable"),
        }
    }
}

/// Correlation ID for request tracing.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CorrelationId(pub String);

impl CorrelationId {
    /// Generate a new correlation ID.
    pub fn new() -> Self {
        Self(Uuid::new_v4().to_string())
    }
}

impl Default for CorrelationId {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Display for CorrelationId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Error context for propagating request context through the call stack.
#[derive(Debug, Clone)]
pub struct ErrorContext {
    pub correlation_id: CorrelationId,
    pub path: String,
    pub method: String,
}

impl ErrorContext {
    pub fn new(correlation_id: CorrelationId, path: impl Into<String>, method: impl Into<String>) -> Self {
        Self {
            correlation_id,
            path: path.into(),
            method: method.into(),
        }
    }
}

/// Error response body.
#[derive(Debug, Serialize, Deserialize)]
pub struct ErrorBody {
    pub code: ErrorCode,
    pub message: String,
    pub correlation_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<serde_json::Value>,
}

/// Consistent error response format.
#[derive(Debug, Serialize, Deserialize)]
pub struct ErrorResponse {
    pub error: ErrorBody,
}

impl ErrorResponse {
    /// Create a new error response.
    pub fn new(
        code: ErrorCode,
        message: impl Into<String>,
        correlation_id: impl Into<String>,
    ) -> Self {
        Self {
            error: ErrorBody {
                code,
                message: message.into(),
                correlation_id: correlation_id.into(),
                details: None,
            },
        }
    }

    /// Create a new error response with details.
    pub fn with_details(
        code: ErrorCode,
        message: impl Into<String>,
        correlation_id: impl Into<String>,
        details: serde_json::Value,
    ) -> Self {
        Self {
            error: ErrorBody {
                code,
                message: message.into(),
                correlation_id: correlation_id.into(),
                details: Some(details),
            },
        }
    }

    /// Create a redacted error response for internal errors.
    pub fn redacted(correlation_id: impl Into<String>) -> Self {
        Self::new(
            ErrorCode::Internal,
            "An internal error occurred",
            correlation_id,
        )
    }
}

/// Categorization of errors for HTTP response mapping and debugging.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum ErrorKind {
    #[error("not found")]
    NotFound,
    #[error("validation error")]
    Validation,
    #[error("authentication error")]
    Authentication,
    #[error("authorization error")]
    Authorization,
    #[error("conflict")]
    Conflict,
    #[error("rate limited")]
    RateLimited,
    #[error("internal error")]
    Internal,
    #[error("external error")]
    External,
    #[error("unavailable")]
    Unavailable,
}

impl ErrorKind {
    /// Convert to stable ErrorCode.
    pub fn to_code(&self) -> ErrorCode {
        match self {
            ErrorKind::NotFound => ErrorCode::NotFound,
            ErrorKind::Validation => ErrorCode::Validation,
            ErrorKind::Authentication => ErrorCode::Authentication,
            ErrorKind::Authorization => ErrorCode::Authorization,
            ErrorKind::Conflict => ErrorCode::Conflict,
            ErrorKind::RateLimited => ErrorCode::RateLimited,
            ErrorKind::Internal => ErrorCode::Internal,
            ErrorKind::External => ErrorCode::External,
            ErrorKind::Unavailable => ErrorCode::Unavailable,
        }
    }
}

/// Application error type that maps to HTTP status codes.
#[derive(Debug, thiserror::Error)]
#[error("{kind}: {message}")]
pub struct AppError {
    pub kind: ErrorKind,
    pub message: String,
    #[source]
    pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
}

impl AppError {
    pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
            source: None,
        }
    }

    pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
        self.source = Some(Box::new(source));
        self
    }

    /// Convert to ErrorResponse with correlation ID.
    pub fn to_response(&self, correlation_id: &CorrelationId) -> ErrorResponse {
        ErrorResponse::new(self.kind.to_code(), &self.message, correlation_id.0.clone())
    }

    /// Convert to redacted ErrorResponse for internal errors.
    pub fn to_redacted_response(&self, correlation_id: &CorrelationId) -> ErrorResponse {
        if self.kind == ErrorKind::Internal {
            ErrorResponse::redacted(correlation_id.0.clone())
        } else {
            self.to_response(correlation_id)
        }
    }

    /// Check if error is internal (should be redacted).
    pub fn is_internal(&self) -> bool {
        self.kind == ErrorKind::Internal
    }
}

#[cfg(feature = "http-server")]
impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        // Generate correlation ID if not provided via extension
        let correlation_id = CorrelationId::new();
        let status = self.kind.to_code().status_code();

        let response = self.to_redacted_response(&correlation_id);
        let body = axum::Json(response);

        (status, body).into_response()
    }
}

impl From<std::sync::PoisonError<std::sync::MutexGuard<'_, ()>>> for AppError {
    fn from(e: std::sync::PoisonError<std::sync::MutexGuard<'_, ()>>) -> Self {
        AppError::new(ErrorKind::Internal, format!("mutex poisoned: {e}"))
    }
}

impl From<serde_json::Error> for AppError {
    fn from(e: serde_json::Error) -> Self {
        AppError::new(ErrorKind::Validation, format!("invalid JSON: {e}"))
    }
}

#[cfg(feature = "http-client")]
impl From<reqwest::Error> for AppError {
    fn from(e: reqwest::Error) -> Self {
        AppError::new(ErrorKind::External, format!("HTTP client error: {e}"))
    }
}

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

    #[test]
    fn test_error_code_display() {
        assert_eq!(format!("{}", ErrorCode::NotFound), "not_found");
        assert_eq!(format!("{}", ErrorCode::Validation), "validation");
        assert_eq!(format!("{}", ErrorCode::Internal), "internal");
    }

    #[test]
    fn test_error_code_status_codes() {
        assert_eq!(ErrorCode::NotFound.status_code(), StatusCode::NOT_FOUND);
        assert_eq!(ErrorCode::Validation.status_code(), StatusCode::BAD_REQUEST);
        assert_eq!(ErrorCode::Authentication.status_code(), StatusCode::UNAUTHORIZED);
        assert_eq!(ErrorCode::Authorization.status_code(), StatusCode::FORBIDDEN);
        assert_eq!(ErrorCode::Conflict.status_code(), StatusCode::CONFLICT);
        assert_eq!(ErrorCode::RateLimited.status_code(), StatusCode::TOO_MANY_REQUESTS);
        assert_eq!(ErrorCode::Internal.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(ErrorCode::External.status_code(), StatusCode::BAD_GATEWAY);
        assert_eq!(ErrorCode::Unavailable.status_code(), StatusCode::SERVICE_UNAVAILABLE);
    }

    #[test]
    fn test_correlation_id_new() {
        let id = CorrelationId::new();
        assert!(!id.0.is_empty());
    }

    #[test]
    fn test_correlation_id_default() {
        let id = CorrelationId::default();
        assert!(!id.0.is_empty());
    }

    #[test]
    fn test_error_response_new() {
        let response = ErrorResponse::new(ErrorCode::NotFound, "not found", "req-123");
        assert_eq!(response.error.code, ErrorCode::NotFound);
        assert_eq!(response.error.message, "not found");
        assert_eq!(response.error.correlation_id, "req-123");
        assert!(response.error.details.is_none());
    }

    #[test]
    fn test_error_response_with_details() {
        let details = serde_json::json!({"field": "email"});
        let response = ErrorResponse::with_details(
            ErrorCode::Validation,
            "invalid email",
            "req-123",
            details.clone(),
        );
        assert_eq!(response.error.details, Some(details));
    }

    #[test]
    fn test_error_response_redacted() {
        let response = ErrorResponse::redacted("req-123");
        assert_eq!(response.error.code, ErrorCode::Internal);
        assert_eq!(response.error.message, "An internal error occurred");
    }

    #[test]
    fn test_error_kind_to_code() {
        assert_eq!(ErrorKind::NotFound.to_code(), ErrorCode::NotFound);
        assert_eq!(ErrorKind::Validation.to_code(), ErrorCode::Validation);
        assert_eq!(ErrorKind::Internal.to_code(), ErrorCode::Internal);
    }

    #[test]
    fn test_app_error_new() {
        let err = AppError::new(ErrorKind::NotFound, "user not found");
        assert_eq!(err.kind, ErrorKind::NotFound);
        assert_eq!(err.message, "user not found");
        assert!(err.source.is_none());
    }

    #[test]
    fn test_app_error_display() {
        let err = AppError::new(ErrorKind::Validation, "invalid email");
        assert_eq!(format!("{err}"), "validation error: invalid email");
    }

    #[test]
    fn test_app_error_with_source() {
        let source = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
        let err = AppError::new(ErrorKind::Internal, "io failure").with_source(source);
        assert!(err.source.is_some());
    }

    #[test]
    fn test_app_error_from_serde_json() {
        let json_err = serde_json::from_str::<serde_json::Value>("not json").unwrap_err();
        let app_err: AppError = json_err.into();
        assert_eq!(app_err.kind, ErrorKind::Validation);
    }

    #[test]
    fn test_app_error_to_response() {
        let err = AppError::new(ErrorKind::NotFound, "not found");
        let correlation_id = CorrelationId::new();
        let response = err.to_response(&correlation_id);
        assert_eq!(response.error.code, ErrorCode::NotFound);
        assert_eq!(response.error.message, "not found");
        assert_eq!(response.error.correlation_id, correlation_id.0);
    }

    #[test]
    fn test_app_error_to_redacted_response_internal() {
        let err = AppError::new(ErrorKind::Internal, "database connection failed");
        let correlation_id = CorrelationId::new();
        let response = err.to_redacted_response(&correlation_id);
        assert_eq!(response.error.code, ErrorCode::Internal);
        assert_eq!(response.error.message, "An internal error occurred");
    }

    #[test]
    fn test_app_error_to_redacted_response_non_internal() {
        let err = AppError::new(ErrorKind::NotFound, "user not found");
        let correlation_id = CorrelationId::new();
        let response = err.to_redacted_response(&correlation_id);
        assert_eq!(response.error.code, ErrorCode::NotFound);
        assert_eq!(response.error.message, "user not found");
    }

    #[test]
    fn test_app_error_is_internal() {
        let err = AppError::new(ErrorKind::Internal, "internal error");
        assert!(err.is_internal());

        let err = AppError::new(ErrorKind::NotFound, "not found");
        assert!(!err.is_internal());
    }

    #[test]
    fn test_error_response_json_format() {
        let response = ErrorResponse::new(ErrorCode::NotFound, "not found", "req-123");
        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("not_found"));
        assert!(json.contains("not found"));
        assert!(json.contains("req-123"));
    }

    #[test]
    fn test_error_response_json_no_details_when_none() {
        let response = ErrorResponse::new(ErrorCode::NotFound, "not found", "req-123");
        let json = serde_json::to_string(&response).unwrap();
        assert!(!json.contains("details"));
    }

    #[test]
    fn test_error_response_json_with_details() {
        let response = ErrorResponse::with_details(
            ErrorCode::Validation,
            "invalid",
            "req-123",
            serde_json::json!({"field": "email"}),
        );
        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("details"));
        assert!(json.contains("email"));
    }
}