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
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
//! Repository trait for data validation and transactional integrity.
//!
//! Repositories are the boundary between services and providers.
//! They enforce domain rules and handle transactions.

use crate::Context;
use crate::provider::Provider;
use crate::validator::Validator;

/// Validates data and enforces transactional integrity.
///
/// Repositories are the boundary between services and providers. They:
/// - Validate domain rules (e.g., "email must be unique")
/// - Enforce transactional integrity
/// - Delegate to providers for actual I/O
///
/// # Type Parameters
///
/// - `Req`: The request type
/// - `Resp`: The response type
///
/// # Example
///
/// ```
/// use cruxi::{Context, Repository, RepositoryFn};
///
/// #[derive(Debug)]
/// struct RepoError;
///
/// impl std::fmt::Display for RepoError {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
///         write!(f, "repository failed")
///     }
/// }
///
/// impl std::error::Error for RepoError {}
///
/// let user_repo = RepositoryFn::new(|ctx: &Context, user_id: u64| -> Result<String, RepoError> {
///     // In a real implementation, this would call a Provider
///     Ok(format!("User {}", user_id))
/// });
///
/// let result = user_repo.perform(&Context::new(), 42);
/// assert!(result.is_ok());
/// ```
pub trait Repository<Req, Resp> {
    /// The error type returned by this repository.
    type Error: std::error::Error;

    /// Performs the repository operation.
    ///
    /// # Errors
    ///
    /// Returns an error when validation, provider, or transaction execution fails.
    fn perform(&self, ctx: &Context, req: Req) -> Result<Resp, Self::Error>;
}

/// Adapts a function to the [`Repository`] trait.
pub struct RepositoryFn<F, Resp, E>
where
    E: std::error::Error,
{
    f: F,
    _marker: std::marker::PhantomData<(Resp, E)>,
}

impl<F, Resp, E> RepositoryFn<F, Resp, E>
where
    E: std::error::Error,
{
    /// Creates a new repository from a function.
    pub fn new<Req>(f: F) -> Self
    where
        F: Fn(&Context, Req) -> Result<Resp, E>,
    {
        Self {
            f,
            _marker: std::marker::PhantomData,
        }
    }
}

impl<F, Req, Resp, E> Repository<Req, Resp> for RepositoryFn<F, Resp, E>
where
    F: Fn(&Context, Req) -> Result<Resp, E>,
    E: std::error::Error,
{
    type Error = E;

    fn perform(&self, ctx: &Context, req: Req) -> Result<Resp, Self::Error> {
        (self.f)(ctx, req)
    }
}

/// Error combining transaction failures with inner operation failures.
#[derive(Debug)]
pub enum TxError<TE, IE> {
    /// Transaction begin/commit/rollback failed.
    Transaction(TE),
    /// The wrapped operation failed (triggers rollback).
    Inner(IE),
}

impl<TE: std::fmt::Display, IE: std::fmt::Display> std::fmt::Display for TxError<TE, IE> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Transaction(e) => write!(f, "transaction error: {e}"),
            Self::Inner(e) => write!(f, "{e}"),
        }
    }
}

impl<TE: std::error::Error + 'static, IE: std::error::Error + 'static> std::error::Error
    for TxError<TE, IE>
{
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Transaction(e) => Some(e),
            Self::Inner(e) => Some(e),
        }
    }
}

/// Wraps operations in a unit of work.
///
/// Two use cases:
/// 1. **Service-layer**: Coordinate multiple repositories in a single transaction
/// 2. **Repo-layer**: Ensure DB writes complete before external side effects (S3, queues)
///
/// # Example
///
/// ```
/// use cruxi::{Context, Transaction, TxError};
///
/// struct DbTransaction;
///
/// #[derive(Debug)]
/// struct TxFailure;
///
/// impl std::fmt::Display for TxFailure {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
///         write!(f, "transaction failed")
///     }
/// }
///
/// impl std::error::Error for TxFailure {}
///
/// impl Transaction for DbTransaction {
///     type Error = TxFailure;
///
///     fn in_tx<F, T, E>(&self, ctx: &Context, f: F) -> Result<T, TxError<Self::Error, E>>
///     where
///         F: FnOnce(&Context) -> Result<T, E>
///     {
///         // BEGIN
///         let result = f(ctx).map_err(TxError::Inner)?;
///         // COMMIT (or rollback on error)
///         Ok(result)
///     }
/// }
/// ```
pub trait Transaction {
    /// The error type for transaction failures (begin/commit/rollback).
    type Error: std::error::Error;

    /// Executes the given function within a transaction.
    ///
    /// - On success: commits and returns the result
    /// - On `Err(inner)`: rolls back and returns `TxError::Inner(inner)`
    /// - On commit/rollback failure: returns `TxError::Transaction(err)`
    ///
    /// # Errors
    ///
    /// Returns `TxError::Inner` when `f` fails, or `TxError::Transaction`
    /// when transaction management fails.
    fn in_tx<F, T, E>(&self, ctx: &Context, f: F) -> Result<T, TxError<Self::Error, E>>
    where
        F: FnOnce(&Context) -> Result<T, E>;
}

/// Error type for [`ValidatingRepository`].
#[derive(Debug)]
pub enum ValidatingRepositoryError<VE, PE, TE> {
    /// Validation failed.
    Validation(VE),
    /// Provider error.
    Provider(PE),
    /// Transaction error.
    Transaction(TE),
}

impl<VE, PE, TE> std::fmt::Display for ValidatingRepositoryError<VE, PE, TE>
where
    VE: std::fmt::Display,
    PE: std::fmt::Display,
    TE: std::fmt::Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Validation(e) => write!(f, "validation error: {e}"),
            Self::Provider(e) => write!(f, "provider error: {e}"),
            Self::Transaction(e) => write!(f, "transaction error: {e}"),
        }
    }
}

impl<VE, PE, TE> std::error::Error for ValidatingRepositoryError<VE, PE, TE>
where
    VE: std::error::Error + 'static,
    PE: std::error::Error + 'static,
    TE: std::error::Error + 'static,
{
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Validation(e) => Some(e),
            Self::Provider(e) => Some(e),
            Self::Transaction(e) => Some(e),
        }
    }
}

/// A no-op transaction that just executes the function directly.
pub struct NoTransaction;

impl Transaction for NoTransaction {
    type Error = std::convert::Infallible;

    fn in_tx<F, T, E>(&self, ctx: &Context, f: F) -> Result<T, TxError<Self::Error, E>>
    where
        F: FnOnce(&Context) -> Result<T, E>,
    {
        f(ctx).map_err(TxError::Inner)
    }
}

/// A repository that validates input and wraps provider calls in a transaction collaborator.
///
/// This is the primary composite repository in the framework. It:
/// 1. Validates the request using domain rules
/// 2. Wraps the provider call in the configured transaction collaborator
/// 3. Delegates to the provider for actual I/O
///
/// Use [`crate::PassValidator`] and [`NoTransaction`] when validation and transaction
/// behavior are intentionally no-ops.
///
/// # Example
///
/// ```
/// use cruxi::{Context, NoTransaction, ProviderFn, Repository, ValidatingRepository, ValidatorFn};
///
/// #[derive(Clone)]
/// struct CreateUserReq { email: String }
/// struct User { id: u64, email: String }
///
/// #[derive(Debug)]
/// enum DomainError {
///     InvalidEmail,
/// }
///
/// impl std::fmt::Display for DomainError {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
///         match self {
///             Self::InvalidEmail => write!(f, "invalid email"),
///         }
///     }
/// }
///
/// impl std::error::Error for DomainError {}
///
/// let validator = ValidatorFn::new(|_ctx: &Context, req: &CreateUserReq| -> Result<(), DomainError> {
///     // Domain validation: email format, uniqueness, etc.
///     if !req.email.contains('@') {
///         Err(DomainError::InvalidEmail)
///     } else {
///         Ok(())
///     }
/// });
///
/// let provider = ProviderFn::new(|_ctx: &Context, req: CreateUserReq| -> Result<User, DomainError> {
///     // Actual database insert would go here
///     Ok(User { id: 1, email: req.email })
/// });
///
/// let repo = ValidatingRepository::new(validator, provider, NoTransaction);
///
/// let ctx = Context::new();
/// let result = repo.perform(&ctx, CreateUserReq { email: "test@example.com".into() });
/// assert!(result.is_ok());
/// ```
///
/// Missing collaborators are compile-time errors:
///
/// ```compile_fail
/// use cruxi::{Context, NoTransaction, ValidatorFn, ValidatingRepository};
///
/// let validator = ValidatorFn::new(|_ctx: &Context, _req: &u64| -> Result<(), std::convert::Infallible> {
///     Ok(())
/// });
///
/// // `None` does not implement `Provider`, so this does not compile.
/// let _repository = ValidatingRepository::new(validator, None, NoTransaction);
/// ```
///
/// ```compile_fail
/// use cruxi::{Context, NoTransaction, ProviderFn, ValidatingRepository};
///
/// let provider = ProviderFn::new(|_ctx: &Context, req: u64| -> Result<u64, std::convert::Infallible> {
///     Ok(req)
/// });
///
/// // `None` does not implement `Validator`, so this does not compile.
/// let _repository = ValidatingRepository::new(None, provider, NoTransaction);
/// ```
///
/// ```compile_fail
/// use cruxi::{Context, PassValidator, ProviderFn, ValidatingRepository};
///
/// let provider = ProviderFn::new(|_ctx: &Context, req: u64| -> Result<u64, std::convert::Infallible> {
///     Ok(req)
/// });
///
/// // `None` does not implement `Transaction`, so this does not compile.
/// let _repository = ValidatingRepository::new(PassValidator, provider, None);
/// ```
pub struct ValidatingRepository<V, P, T, Req, Resp>
where
    V: Validator<Req>,
    P: Provider<Req, Resp>,
    T: Transaction,
{
    /// The validator for domain rules.
    pub validator: V,
    /// The provider for I/O operations.
    pub provider: P,
    /// The transaction wrapper.
    pub transaction: T,
    _marker: std::marker::PhantomData<(Req, Resp)>,
}

impl<V, P, T, Req, Resp> ValidatingRepository<V, P, T, Req, Resp>
where
    V: Validator<Req>,
    P: Provider<Req, Resp>,
    T: Transaction,
{
    /// Creates a new validating repository.
    pub fn new(validator: V, provider: P, transaction: T) -> Self {
        Self {
            validator,
            provider,
            transaction,
            _marker: std::marker::PhantomData,
        }
    }
}

impl<V, P, T, Req, Resp> Repository<Req, Resp> for ValidatingRepository<V, P, T, Req, Resp>
where
    V: Validator<Req>,
    V::Error: 'static,
    P: Provider<Req, Resp>,
    P::Error: 'static,
    T: Transaction,
    T::Error: 'static,
{
    type Error = ValidatingRepositoryError<V::Error, P::Error, T::Error>;

    fn perform(&self, ctx: &Context, req: Req) -> Result<Resp, Self::Error> {
        self.validator
            .validate(ctx, &req)
            .map_err(ValidatingRepositoryError::Validation)?;

        self.transaction
            .in_tx(ctx, |ctx| self.provider.execute(ctx, req))
            .map_err(|e| match e {
                TxError::Transaction(te) => ValidatingRepositoryError::Transaction(te),
                TxError::Inner(pe) => ValidatingRepositoryError::Provider(pe),
            })
    }
}

// Async variants

#[cfg(feature = "async")]
use async_trait::async_trait;

/// Async version of [`Repository`] for use with async runtimes.
#[cfg(feature = "async")]
#[async_trait]
pub trait AsyncRepository<Req, Resp>: Send + Sync
where
    Req: Send,
    Resp: Send,
{
    /// The error type returned by this repository.
    type Error: std::error::Error + Send;

    /// Performs the repository operation asynchronously.
    ///
    /// # Errors
    ///
    /// Returns an error when validation, provider, or transaction execution fails.
    async fn perform(&self, ctx: &Context, req: Req) -> Result<Resp, Self::Error>;
}

/// Blanket implementation allowing sync repositories to be used as async.
#[cfg(feature = "async")]
#[async_trait]
impl<R, Req, Resp> AsyncRepository<Req, Resp> for R
where
    R: Repository<Req, Resp> + Send + Sync,
    R::Error: Send,
    Req: Send + 'static,
    Resp: Send,
{
    type Error = R::Error;

    async fn perform(&self, ctx: &Context, req: Req) -> Result<Resp, Self::Error> {
        Repository::perform(self, ctx, req)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{CodedError, ProviderFn, ValidatorFn};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};

    struct TestTransaction {
        entered: Arc<AtomicBool>,
    }

    impl Transaction for TestTransaction {
        type Error = CodedError;

        fn in_tx<F, T, E>(&self, ctx: &Context, f: F) -> Result<T, TxError<Self::Error, E>>
        where
            F: FnOnce(&Context) -> Result<T, E>,
        {
            self.entered.store(true, Ordering::SeqCst);
            f(ctx).map_err(TxError::Inner)
        }
    }

    struct FailingTransaction;

    impl Transaction for FailingTransaction {
        type Error = CodedError;

        fn in_tx<F, T, E>(&self, _ctx: &Context, _f: F) -> Result<T, TxError<Self::Error, E>>
        where
            F: FnOnce(&Context) -> Result<T, E>,
        {
            Err(TxError::Transaction(CodedError::new("TX_FAILED")))
        }
    }

    #[test]
    fn repository_fn_basic() {
        let repo = RepositoryFn::new(|_ctx: &Context, req: i32| -> Result<i32, CodedError> {
            Ok(req * 2)
        });

        let result = Repository::perform(&repo, &Context::new(), 21);
        assert_eq!(result.ok(), Some(42));
    }

    #[test]
    fn validating_repository_with_valid_request() {
        let validator = ValidatorFn::new(|_ctx: &Context, req: &i32| -> Result<(), CodedError> {
            if *req > 0 {
                Ok(())
            } else {
                Err(CodedError::new("INVALID"))
            }
        });

        let provider =
            ProviderFn::new(|_ctx: &Context, req: i32| -> Result<i32, CodedError> { Ok(req * 2) });

        let repo = ValidatingRepository::new(validator, provider, NoTransaction);
        let result = Repository::perform(&repo, &Context::new(), 21);
        assert_eq!(result.ok(), Some(42));
    }

    #[test]
    fn validating_repository_with_invalid_request() {
        let validator = ValidatorFn::new(|_ctx: &Context, req: &i32| -> Result<(), CodedError> {
            if *req > 0 {
                Ok(())
            } else {
                Err(CodedError::new("INVALID"))
            }
        });

        let provider =
            ProviderFn::new(|_ctx: &Context, req: i32| -> Result<i32, CodedError> { Ok(req * 2) });

        let repo = ValidatingRepository::new(validator, provider, NoTransaction);
        let result = Repository::perform(&repo, &Context::new(), -1);
        assert!(result.is_err());
    }

    #[test]
    fn validating_repository_with_transaction() {
        // Track whether transaction was entered
        let tx_entered = Arc::new(AtomicBool::new(false));
        let tx_entered_clone = tx_entered.clone();

        let provider =
            ProviderFn::new(|_ctx: &Context, req: i32| -> Result<i32, CodedError> { Ok(req * 2) });

        let tx = TestTransaction {
            entered: tx_entered_clone,
        };
        let repo = ValidatingRepository::new(crate::PassValidator, provider, tx);

        let result = Repository::perform(&repo, &Context::new(), 21);
        assert_eq!(result.ok(), Some(42));
        assert!(
            tx_entered.load(Ordering::SeqCst),
            "Transaction should have been entered"
        );
    }

    #[test]
    fn transaction_error_propagates() {
        let provider =
            ProviderFn::new(|_ctx: &Context, req: i32| -> Result<i32, CodedError> { Ok(req * 2) });

        let repo = ValidatingRepository::new(crate::PassValidator, provider, FailingTransaction);

        let result = Repository::perform(&repo, &Context::new(), 21);
        match result {
            Err(ValidatingRepositoryError::Transaction(ref e)) => {
                assert_eq!(e.code(), "TX_FAILED");
            }
            Err(ValidatingRepositoryError::Validation(e)) => {
                panic!("Expected transaction error, got validation error: {e}");
            }
            Err(ValidatingRepositoryError::Provider(e)) => {
                panic!("Expected transaction error, got provider error: {e}");
            }
            Ok(value) => {
                panic!("Expected transaction error, got success value: {value}");
            }
        }
    }
}