cruxi 0.2.0

Minimal, transport-agnostic hexagonal architecture framework
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
//! Error types for the Cruxi framework.
//!
//! This module provides structured error types that support:
//! - Machine-readable error codes for API responses
//! - Error chaining via `source()` for debugging
//! - Field-level validation errors

use std::fmt;
use thiserror::Error;

/// Sentinel errors for common framework conditions.
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
pub enum CruxiError {
    /// Authorization check failed.
    #[error("cruxi: unauthorized")]
    Unauthorized,
}

/// A structured error with a machine-readable code.
///
/// `CodedError` is designed for API responses where clients need stable error
/// codes for programmatic handling. The error chain is preserved via `source`.
///
/// # Example
///
/// ```
/// use cruxi::CodedError;
///
/// let err = CodedError::new("USER_NOT_FOUND")
///     .with_title("User Not Found")
///     .with_reason("No user exists with the given ID")
///     .with_instance("req-12345");
///
/// assert_eq!(err.code(), "USER_NOT_FOUND");
/// ```
#[derive(Debug, Clone)]
pub struct CodedError {
    code: String,
    details: Box<CodedErrorDetails>,
}

#[derive(Debug, Clone)]
struct CodedErrorDetails {
    instance: Option<String>,
    class: ErrorClass,
    retryability: RetryabilityHint,
    title: Option<String>,
    user_message: Option<String>,
    diagnostic_message: Option<String>,
    source: Option<Box<CodedError>>,
}

/// Transport-agnostic error classification for adapter mapping.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorClass {
    /// Client sent semantically invalid input.
    Validation,
    /// Caller identity is missing or invalid.
    Authentication,
    /// Caller is authenticated but not allowed to perform the action.
    Authorization,
    /// Requested resource does not exist.
    NotFound,
    /// Request conflicts with current resource state.
    Conflict,
    /// Request is throttled by policy/rate limits.
    RateLimited,
    /// Operation exceeded a deadline or timeout budget.
    Timeout,
    /// Dependency or service is temporarily unavailable.
    Unavailable,
    /// Internal error with no safe external detail.
    Internal,
    /// Error class is unknown/unset.
    Unknown,
}

/// Retryability hint for policy engines and adapters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RetryabilityHint {
    /// Retry is not expected to help.
    Never,
    /// Retry is expected to be safe/useful.
    Always,
    /// Retryability is context-dependent.
    Maybe,
}

/// Whether an adapter can safely expose the user-facing error message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageExposure {
    /// Safe to expose the user-facing message from [`CodedError`].
    Safe,
    /// Do not expose detail; use transport-generic fallback wording.
    Opaque,
}

/// Transport-agnostic mapping context derived from a [`CodedError`].
///
/// Adapters can map this context to transport-native responses
/// (HTTP status, gRPC code, queue nack policy, etc.) without coupling
/// the core crate to transport types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ErrorMappingContext {
    /// Domain error class.
    pub class: ErrorClass,
    /// Retryability hint.
    pub retryability: RetryabilityHint,
    /// Whether user-facing message is safe to expose.
    pub message_exposure: MessageExposure,
}

/// Contract for adapter-facing error mapping.
///
/// Mapper implementations live at the edges and return transport-native
/// decision types.
pub trait ErrorClassMapper {
    /// Adapter-specific decision type (e.g., HTTP status + body policy).
    type Decision;

    /// Maps a transport-agnostic context into an adapter decision.
    fn map(&self, context: ErrorMappingContext) -> Self::Decision;
}

impl CodedError {
    /// Creates a new `CodedError` with the given code.
    ///
    /// The code should be a stable, machine-readable identifier like
    /// `"VALIDATION_FAILED"` or `"USER_NOT_FOUND"`.
    #[must_use]
    pub fn new(code: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            details: Box::new(CodedErrorDetails {
                instance: None,
                class: ErrorClass::Unknown,
                retryability: RetryabilityHint::Maybe,
                title: None,
                user_message: None,
                diagnostic_message: None,
                source: None,
            }),
        }
    }

    /// Sets the instance identifier for error correlation.
    ///
    /// Typically a request ID or UUID for tracing the error back to logs.
    #[must_use]
    pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
        self.details.instance = Some(instance.into());
        self
    }

    /// Sets a short, human-readable title.
    #[must_use]
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.details.title = Some(title.into());
        self
    }

    /// Sets a detailed explanation of the error.
    ///
    /// This is the safe user-facing message channel.
    #[must_use]
    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
        self.details.user_message = Some(reason.into());
        self
    }

    /// Sets a safe user-facing message for this error.
    #[must_use]
    pub fn with_user_message(mut self, message: impl Into<String>) -> Self {
        self.details.user_message = Some(message.into());
        self
    }

    /// Sets an internal diagnostic message for operators/logging.
    #[must_use]
    pub fn with_diagnostic_message(mut self, message: impl Into<String>) -> Self {
        self.details.diagnostic_message = Some(message.into());
        self
    }

    /// Sets the transport-agnostic error classification.
    #[must_use]
    pub fn with_class(mut self, class: ErrorClass) -> Self {
        self.details.class = class;
        self
    }

    /// Sets retryability hint for retry policy/mapping decisions.
    #[must_use]
    pub fn with_retryability(mut self, retryability: RetryabilityHint) -> Self {
        self.details.retryability = retryability;
        self
    }

    /// Sets the underlying cause of this error.
    #[must_use]
    pub fn with_source(mut self, source: CodedError) -> Self {
        self.details.source = Some(Box::new(source));
        self
    }

    /// Returns the error code.
    #[must_use]
    pub fn code(&self) -> &str {
        &self.code
    }

    /// Returns the instance identifier, if set.
    #[must_use]
    pub fn instance(&self) -> Option<&str> {
        self.details.instance.as_deref()
    }

    /// Returns the title, if set.
    #[must_use]
    pub fn title(&self) -> Option<&str> {
        self.details.title.as_deref()
    }

    /// Returns the safe user-facing message, if set.
    ///
    /// `reason()` is retained for compatibility and mirrors this value.
    #[must_use]
    pub fn reason(&self) -> Option<&str> {
        self.details.user_message.as_deref()
    }

    /// Returns the safe user-facing message, if set.
    #[must_use]
    pub fn user_message(&self) -> Option<&str> {
        self.details.user_message.as_deref()
    }

    /// Returns internal diagnostic detail, if set.
    #[must_use]
    pub fn diagnostic_message(&self) -> Option<&str> {
        self.details.diagnostic_message.as_deref()
    }

    /// Returns the transport-agnostic error class.
    #[must_use]
    pub fn class(&self) -> ErrorClass {
        self.details.class
    }

    /// Returns retryability hint.
    #[must_use]
    pub fn retryability(&self) -> RetryabilityHint {
        self.details.retryability
    }

    /// Returns transport-agnostic mapping context for this error.
    #[must_use]
    pub fn mapping_context(&self) -> ErrorMappingContext {
        let message_exposure = match self.class() {
            ErrorClass::Internal | ErrorClass::Unknown => MessageExposure::Opaque,
            ErrorClass::Validation
            | ErrorClass::Authentication
            | ErrorClass::Authorization
            | ErrorClass::NotFound
            | ErrorClass::Conflict
            | ErrorClass::RateLimited
            | ErrorClass::Timeout
            | ErrorClass::Unavailable => MessageExposure::Safe,
        };

        ErrorMappingContext {
            class: self.class(),
            retryability: self.retryability(),
            message_exposure,
        }
    }
}

/// Maps a [`CodedError`] to an adapter decision via an [`ErrorClassMapper`].
#[must_use]
pub fn map_coded_error<M>(error: &CodedError, mapper: &M) -> M::Decision
where
    M: ErrorClassMapper + ?Sized,
{
    mapper.map(error.mapping_context())
}

impl fmt::Display for CodedError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match (&self.details.user_message, &self.details.title) {
            (Some(reason), _) => write!(f, "{reason}"),
            (None, Some(title)) => write!(f, "{title}"),
            (None, None) => write!(f, "cruxi: coded error [{}]", self.code),
        }
    }
}

impl std::error::Error for CodedError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.details
            .source
            .as_ref()
            .map(|e| e.as_ref() as &(dyn std::error::Error + 'static))
    }
}

/// A field-level validation error.
///
/// Used by handlers for transport format validation (e.g., "field required in JSON").
///
/// # Example
///
/// ```
/// use cruxi::ValidationError;
///
/// let err = ValidationError::new("email", "required");
/// assert_eq!(err.to_string(), "cruxi: validation error: email: required");
/// ```
#[derive(Debug, Clone, Error)]
#[error("cruxi: validation error: {field}: {message}")]
pub struct ValidationError {
    field: String,
    message: String,
}

impl ValidationError {
    /// Creates a new validation error for the given field.
    #[must_use]
    pub fn new(field: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            field: field.into(),
            message: message.into(),
        }
    }

    /// Returns the field name that failed validation.
    #[must_use]
    pub fn field(&self) -> &str {
        &self.field
    }

    /// Returns the validation failure message.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }
}

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

    #[test]
    fn coded_error_display_with_reason() {
        let err = CodedError::new("TEST")
            .with_reason("detailed reason")
            .with_title("Title");
        assert_eq!(err.to_string(), "detailed reason");
    }

    #[test]
    fn coded_error_display_with_title_only() {
        let err = CodedError::new("TEST").with_title("Title Only");
        assert_eq!(err.to_string(), "Title Only");
    }

    #[test]
    fn coded_error_display_fallback() {
        let err = CodedError::new("TEST_CODE");
        assert_eq!(err.to_string(), "cruxi: coded error [TEST_CODE]");
    }

    #[test]
    fn coded_error_chain() {
        let inner = CodedError::new("INNER").with_reason("inner cause");
        let outer = CodedError::new("OUTER")
            .with_reason("outer reason")
            .with_source(inner);

        assert!(outer.source().is_some());
    }

    #[test]
    fn coded_error_defaults_class_and_retryability() {
        let err = CodedError::new("TEST");
        assert_eq!(err.class(), ErrorClass::Unknown);
        assert_eq!(err.retryability(), RetryabilityHint::Maybe);
    }

    #[test]
    fn coded_error_supports_class_and_retryability_overrides() {
        let err = CodedError::new("TEST")
            .with_class(ErrorClass::Validation)
            .with_retryability(RetryabilityHint::Never);
        assert_eq!(err.class(), ErrorClass::Validation);
        assert_eq!(err.retryability(), RetryabilityHint::Never);
    }

    #[test]
    fn coded_error_supports_user_and_diagnostic_channels() {
        let err = CodedError::new("TEST")
            .with_user_message("safe for caller")
            .with_diagnostic_message("db pool timed out");
        assert_eq!(err.user_message(), Some("safe for caller"));
        assert_eq!(err.reason(), Some("safe for caller"));
        assert_eq!(err.diagnostic_message(), Some("db pool timed out"));
    }

    #[test]
    fn mapping_context_marks_internal_as_opaque() {
        let err = CodedError::new("TEST")
            .with_class(ErrorClass::Internal)
            .with_retryability(RetryabilityHint::Never);
        assert_eq!(
            err.mapping_context(),
            ErrorMappingContext {
                class: ErrorClass::Internal,
                retryability: RetryabilityHint::Never,
                message_exposure: MessageExposure::Opaque,
            }
        );
    }

    #[test]
    fn mapping_context_marks_validation_as_safe() {
        let err = CodedError::new("TEST")
            .with_class(ErrorClass::Validation)
            .with_retryability(RetryabilityHint::Never);
        assert_eq!(
            err.mapping_context(),
            ErrorMappingContext {
                class: ErrorClass::Validation,
                retryability: RetryabilityHint::Never,
                message_exposure: MessageExposure::Safe,
            }
        );
    }

    #[test]
    fn map_coded_error_uses_mapper_contract() {
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        enum Decision {
            Client,
            Server,
        }

        struct DemoMapper;

        impl ErrorClassMapper for DemoMapper {
            type Decision = Decision;

            fn map(&self, context: ErrorMappingContext) -> Self::Decision {
                match context.class {
                    ErrorClass::Validation
                    | ErrorClass::Authentication
                    | ErrorClass::Authorization
                    | ErrorClass::NotFound
                    | ErrorClass::Conflict
                    | ErrorClass::RateLimited => Decision::Client,
                    ErrorClass::Timeout
                    | ErrorClass::Unavailable
                    | ErrorClass::Internal
                    | ErrorClass::Unknown => Decision::Server,
                }
            }
        }

        let mapper = DemoMapper;
        let validation = CodedError::new("VALIDATION").with_class(ErrorClass::Validation);
        let internal = CodedError::new("INTERNAL").with_class(ErrorClass::Internal);

        assert_eq!(map_coded_error(&validation, &mapper), Decision::Client);
        assert_eq!(map_coded_error(&internal, &mapper), Decision::Server);
    }

    #[test]
    fn validation_error_display() {
        let err = ValidationError::new("email", "required");
        assert_eq!(err.to_string(), "cruxi: validation error: email: required");
    }
}