arqen 0.13.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
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,
    Timeout,
    Dependency,
    Internal,
    External,
    Unavailable,
    NotImpl,
}

impl ErrorCode {
    /// Convert to HTTP status code.
    ///
    /// Requires the `http-server` feature.
    #[cfg(feature = "http-server")]
    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::Timeout => StatusCode::GATEWAY_TIMEOUT,
            ErrorCode::Dependency => StatusCode::BAD_GATEWAY,
            ErrorCode::Internal => StatusCode::INTERNAL_SERVER_ERROR,
            ErrorCode::External => StatusCode::BAD_GATEWAY,
            ErrorCode::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
            ErrorCode::NotImpl => StatusCode::NOT_IMPLEMENTED,
        }
    }
}

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::Timeout => write!(f, "timeout"),
            ErrorCode::Dependency => write!(f, "dependency"),
            ErrorCode::Internal => write!(f, "internal"),
            ErrorCode::External => write!(f, "external"),
            ErrorCode::Unavailable => write!(f, "unavailable"),
            ErrorCode::NotImpl => write!(f, "not_impl"),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CorrelationId(pub String);

impl CorrelationId {
    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)
    }
}

// Correlation ID for the request currently being handled. Scoped by
// `correlation_id_middleware` around each request so that error responses —
// which do not receive the request itself — can propagate the request-scoped ID.
#[cfg(feature = "http-server")]
tokio::task_local! {
    pub static REQUEST_CORRELATION_ID: CorrelationId;
}

#[cfg(feature = "http-server")]
impl CorrelationId {
    /// Return the correlation ID of the current request.
    ///
    /// Falls back to a freshly generated ID when no correlation middleware is
    /// installed (i.e. outside a request scope).
    pub fn current() -> Self {
        REQUEST_CORRELATION_ID
            .try_with(|id| id.clone())
            .unwrap_or_else(|_| Self::new())
    }
}

#[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(),
        }
    }
}

#[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>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ErrorResponse {
    pub error: ErrorBody,
}

impl ErrorResponse {
    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,
            },
        }
    }

    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),
            },
        }
    }

    pub fn redacted(correlation_id: impl Into<String>) -> Self {
        Self::new(
            ErrorCode::Internal,
            "An internal error occurred",
            correlation_id,
        )
    }
}

#[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("timeout")]
    Timeout,
    #[error("dependency error")]
    Dependency,
    #[error("internal error")]
    Internal,
    #[error("external error")]
    External,
    #[error("unavailable")]
    Unavailable,
    #[error("not implemented")]
    NotImpl,
}

impl ErrorKind {
    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::Timeout => ErrorCode::Timeout,
            ErrorKind::Dependency => ErrorCode::Dependency,
            ErrorKind::Internal => ErrorCode::Internal,
            ErrorKind::External => ErrorCode::External,
            ErrorKind::Unavailable => ErrorCode::Unavailable,
            ErrorKind::NotImpl => ErrorCode::NotImpl,
        }
    }

    /// Check if this error kind should be redacted in responses.
    pub fn should_redact(&self) -> bool {
        matches!(self, ErrorKind::Internal)
    }
}

#[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
    }

    pub fn to_response(&self, correlation_id: &CorrelationId) -> ErrorResponse {
        ErrorResponse::new(self.kind.to_code(), &self.message, correlation_id.0.clone())
    }

    pub fn to_redacted_response(&self, correlation_id: &CorrelationId) -> ErrorResponse {
        if self.kind.should_redact() {
            ErrorResponse::redacted(correlation_id.0.clone())
        } else {
            self.to_response(correlation_id)
        }
    }

    pub fn is_internal(&self) -> bool {
        self.kind == ErrorKind::Internal
    }
}

#[cfg(feature = "http-server")]
impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let correlation_id = CorrelationId::current();
        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}"))
    }
}

impl From<std::io::Error> for AppError {
    fn from(e: std::io::Error) -> Self {
        match e.kind() {
            std::io::ErrorKind::NotFound => {
                AppError::new(ErrorKind::NotFound, format!("file not found: {e}"))
            }
            std::io::ErrorKind::PermissionDenied => {
                AppError::new(ErrorKind::Authorization, format!("permission denied: {e}"))
            }
            _ => AppError::new(ErrorKind::Internal, format!("IO error: {e}")),
        }
    }
}

impl From<std::net::AddrParseError> for AppError {
    fn from(e: std::net::AddrParseError) -> Self {
        AppError::new(ErrorKind::Validation, format!("invalid address: {e}"))
    }
}

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

impl From<std::env::VarError> for AppError {
    fn from(e: std::env::VarError) -> Self {
        AppError::new(
            ErrorKind::Internal,
            format!("environment variable error: {e}"),
        )
    }
}

#[cfg(feature = "http-client")]
impl From<reqwest::Error> for AppError {
    fn from(e: reqwest::Error) -> Self {
        if e.is_timeout() {
            AppError::new(ErrorKind::Timeout, format!("request timed out: {e}"))
        } else if e.is_connect() {
            AppError::new(ErrorKind::Dependency, format!("connection failed: {e}"))
        } else {
            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::Timeout), "timeout");
        assert_eq!(format!("{}", ErrorCode::Dependency), "dependency");
        assert_eq!(format!("{}", ErrorCode::Internal), "internal");
    }

    #[cfg(feature = "http-server")]
    #[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::Timeout.status_code(),
            StatusCode::GATEWAY_TIMEOUT
        );
        assert_eq!(ErrorCode::Dependency.status_code(), StatusCode::BAD_GATEWAY);
        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::Timeout.to_code(), ErrorCode::Timeout);
        assert_eq!(ErrorKind::Dependency.to_code(), ErrorCode::Dependency);
        assert_eq!(ErrorKind::Internal.to_code(), ErrorCode::Internal);
    }

    #[test]
    fn test_error_kind_should_redact() {
        assert!(ErrorKind::Internal.should_redact());
        assert!(!ErrorKind::NotFound.should_redact());
        assert!(!ErrorKind::Validation.should_redact());
        assert!(!ErrorKind::Timeout.should_redact());
        assert!(!ErrorKind::Dependency.should_redact());
    }

    #[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_from_io_error() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "missing");
        let app_err: AppError = io_err.into();
        assert_eq!(app_err.kind, ErrorKind::NotFound);
    }

    #[test]
    fn test_app_error_from_io_permission() {
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
        let app_err: AppError = io_err.into();
        assert_eq!(app_err.kind, ErrorKind::Authorization);
    }

    #[test]
    fn test_app_error_from_addr_parse() {
        let addr_err = "not-an-address"
            .parse::<std::net::SocketAddr>()
            .unwrap_err();
        let app_err: AppError = addr_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"));
    }

    #[cfg(feature = "http-server")]
    #[test]
    fn test_timeout_error_mapping() {
        let err = AppError::new(ErrorKind::Timeout, "request timed out");
        let correlation_id = CorrelationId::new();
        let response = err.to_response(&correlation_id);
        assert_eq!(response.error.code, ErrorCode::Timeout);
        assert_eq!(
            response.error.code.status_code(),
            StatusCode::GATEWAY_TIMEOUT
        );
    }

    #[cfg(feature = "http-server")]
    #[test]
    fn test_dependency_error_mapping() {
        let err = AppError::new(ErrorKind::Dependency, "thingd unavailable");
        let correlation_id = CorrelationId::new();
        let response = err.to_response(&correlation_id);
        assert_eq!(response.error.code, ErrorCode::Dependency);
        assert_eq!(response.error.code.status_code(), StatusCode::BAD_GATEWAY);
    }
}