cqrs-rust-lib 0.7.0

An opinionated implementation of CQRS/Event Sourcing with pluggable storage backends (InMemory, PostgreSQL, MongoDB, SurrealDB)
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
# cqrs-rust-lib

A comprehensive Command Query Responsibility Segregation (CQRS) and Event Sourcing library for Rust applications.

## Features

- CQRS and Event Sourcing core primitives
- Split `Aggregate` / `CommandHandler` traits (Single Responsibility)
- Structured domain error system with `CqrsError` and `define_domain_errors!` macro
- Multiple storage backends:
  - In-memory (testing/development)
  - MongoDB (feature: `mongodb`)
  - PostgreSQL (feature: `postgres`)
- REST routers with Axum and OpenAPI integration (feature: `utoipa`)
- Audit log router for event history
- Typed read storage and snapshot support
- Pluggable dispatchers for denormalization/projections

## Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
cqrs-rust-lib = "0.1.0"
```

### Cargo features

| Feature    | Description                                        |
|------------|----------------------------------------------------|
| `mongodb`  | MongoDB event persistence                          |
| `postgres` | PostgreSQL event persistence and read utilities     |
| `utoipa`   | REST routers and OpenAPI/Swagger integration        |
| `mcp`      | MCP server integration (experimental)               |
| `all`      | Enables `utoipa`, `mongodb`, and `postgres`         |

```toml
# PostgreSQL + REST
cqrs-rust-lib = { version = "0.1.0", features = ["postgres", "utoipa"] }

# MongoDB only
cqrs-rust-lib = { version = "0.1.0", features = ["mongodb"] }
```

## Quick Start

### 1. Define your domain

```rust
use cqrs_rust_lib::{Aggregate, CommandHandler, CqrsContext, CqrsError, Event};
use http::StatusCode;
use serde::{Deserialize, Serialize};

// Events
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum AccountEvent {
    Opened { owner: String },
    Deposited { amount: i64 },
    Withdrawn { amount: i64 },
}

impl Event for AccountEvent {
    fn event_type(&self) -> String {
        match self {
            Self::Opened { .. } => "opened".into(),
            Self::Deposited { .. } => "deposited".into(),
            Self::Withdrawn { .. } => "withdrawn".into(),
        }
    }
}

// Commands
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CreateCommand { Open { owner: String } }

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum UpdateCommand { Deposit { amount: i64 }, Withdraw { amount: i64 } }

// Aggregate
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Account {
    pub id: String,
    pub balance: i64,
}

#[async_trait::async_trait]
impl Aggregate for Account {
    const TYPE: &'static str = "account";
    type Event = AccountEvent;
    type Error = CqrsError;

    fn aggregate_id(&self) -> String { self.id.clone() }
    fn with_aggregate_id(mut self, id: String) -> Self { self.id = id; self }

    fn apply(&mut self, event: Self::Event) -> Result<(), Self::Error> {
        match event {
            AccountEvent::Opened { .. } => {}
            AccountEvent::Deposited { amount } => self.balance += amount,
            AccountEvent::Withdrawn { amount } => self.balance -= amount,
        }
        Ok(())
    }

    fn error(status: StatusCode, details: &str) -> Self::Error {
        CqrsError::from_status(status, details)
    }
}

#[async_trait::async_trait]
impl CommandHandler for Account {
    type CreateCommand = CreateCommand;
    type UpdateCommand = UpdateCommand;
    type Services = ();

    async fn handle_create(
        &self, command: Self::CreateCommand, _svc: &(), _ctx: &CqrsContext,
    ) -> Result<Vec<Self::Event>, Self::Error> {
        match command {
            CreateCommand::Open { owner } => Ok(vec![AccountEvent::Opened { owner }]),
        }
    }

    async fn handle_update(
        &self, command: Self::UpdateCommand, _svc: &(), _ctx: &CqrsContext,
    ) -> Result<Vec<Self::Event>, Self::Error> {
        match command {
            UpdateCommand::Deposit { amount } => Ok(vec![AccountEvent::Deposited { amount }]),
            UpdateCommand::Withdraw { amount } => Ok(vec![AccountEvent::Withdrawn { amount }]),
        }
    }
}
```

### 2. Create the engine and execute commands

```rust
use cqrs_rust_lib::es::{inmemory::InMemoryPersist, EventStoreImpl};
use cqrs_rust_lib::{CqrsCommandEngine, CqrsContext};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let store = EventStoreImpl::new(InMemoryPersist::<Account>::new());
    let engine = CqrsCommandEngine::new(store, vec![], (), Box::new(|_e| {}));

    let ctx = CqrsContext::default();
    let id = engine.execute_create(CreateCommand::Open { owner: "Alice".into() }, &ctx).await?;
    engine.execute_update(&id, UpdateCommand::Deposit { amount: 100 }, &ctx).await?;
    Ok(())
}
```

## Domain Error Codes

Define structured, domain-specific error codes with the `define_domain_errors!` macro:

```rust
use cqrs_rust_lib::{define_domain_errors, CqrsError, CqrsErrorCode};
use http::StatusCode;

define_domain_errors! {
    domain: "account",
    prefix: 10,
    errors: {
        InsufficientFunds => (1, StatusCode::BAD_REQUEST, "INSUFFICIENT_FUNDS"),
        InvalidAmount     => (2, StatusCode::BAD_REQUEST, "INVALID_AMOUNT"),
        AccountClosed     => (3, StatusCode::GONE, "ACCOUNT_CLOSED"),
    }
}

impl From<ErrorCode> for CqrsError {
    fn from(e: ErrorCode) -> Self {
        e.error(e.to_string())
    }
}
```

Use in command handlers:

```rust
if self.balance < amount {
    return Err(ErrorCode::InsufficientFunds.error(
        format!("Cannot withdraw {}, balance is {}", amount, self.balance)
    ));
}
```

API response:

```json
{
  "domain": "account",
  "code": "ACCOUNT_INSUFFICIENT_FUNDS",
  "internalCode": 10001,
  "status": 400,
  "message": "Cannot withdraw 500, balance is 200"
}
```

See `docs/migration_guide/domain_errors.md` for the full migration guide.

## Custom Aggregate ID Generation

By default, aggregate IDs are generated as UUID v4. For patterns like **Association as Aggregate** — where the ID must be deterministic and derived from the command — you can provide a custom `AggregateIdGenerator`.

### Example: UserRight (association between User and Right)

```rust
use cqrs_rust_lib::{
    Aggregate, CommandHandler, AggregateIdGenerator, CqrsContext,
    CqrsError, Event, CqrsCommandEngine,
    es::{inmemory::InMemoryPersist, EventStoreImpl},
};
use serde::{Deserialize, Serialize};
use http::StatusCode;

// --- Events ---

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum UserRightEvent {
    Granted { user_id: String, right_id: String },
    Revoked,
}

impl Event for UserRightEvent {
    fn event_type(&self) -> String {
        match self {
            Self::Granted { .. } => "granted".into(),
            Self::Revoked => "revoked".into(),
        }
    }
}

// --- Commands ---

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GrantRight {
    pub user_id: String,
    pub right_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum UserRightUpdateCommand {
    Revoke,
}

// --- Aggregate ---

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UserRight {
    pub id: String,
    pub user_id: String,
    pub right_id: String,
    pub active: bool,
}

#[async_trait::async_trait]
impl Aggregate for UserRight {
    const TYPE: &'static str = "user_right";
    type Event = UserRightEvent;
    type Error = CqrsError;

    fn aggregate_id(&self) -> String { self.id.clone() }
    fn with_aggregate_id(mut self, id: String) -> Self { self.id = id; self }

    fn apply(&mut self, event: Self::Event) -> Result<(), Self::Error> {
        match event {
            UserRightEvent::Granted { user_id, right_id } => {
                self.user_id = user_id;
                self.right_id = right_id;
                self.active = true;
            }
            UserRightEvent::Revoked => { self.active = false; }
        }
        Ok(())
    }

    fn error(status: StatusCode, details: &str) -> Self::Error {
        CqrsError::from_status(status, details)
    }
}

#[async_trait::async_trait]
impl CommandHandler for UserRight {
    type CreateCommand = GrantRight;
    type UpdateCommand = UserRightUpdateCommand;
    type Services = ();

    async fn handle_create(
        &self, cmd: Self::CreateCommand, _svc: &(), _ctx: &CqrsContext,
    ) -> Result<Vec<Self::Event>, Self::Error> {
        Ok(vec![UserRightEvent::Granted {
            user_id: cmd.user_id,
            right_id: cmd.right_id,
        }])
    }

    async fn handle_update(
        &self, cmd: Self::UpdateCommand, _svc: &(), _ctx: &CqrsContext,
    ) -> Result<Vec<Self::Event>, Self::Error> {
        match cmd {
            UserRightUpdateCommand::Revoke => Ok(vec![UserRightEvent::Revoked]),
        }
    }
}
```

### Custom ID generator

The aggregate ID is derived from the association components, making it deterministic and idempotent:

```rust
struct UserRightIdGenerator;

impl AggregateIdGenerator<UserRight> for UserRightIdGenerator {
    fn next_id(&self, cmd: &GrantRight, _ctx: &CqrsContext) -> String {
        format!("{}_{}", cmd.user_id, cmd.right_id)
    }
}
```

### Wiring the engine

```rust
let store = EventStoreImpl::new(InMemoryPersist::<UserRight>::new());
let engine = CqrsCommandEngine::new(store, vec![], (), Box::new(|_e| {}))
    .with_id_generator(Box::new(UserRightIdGenerator));

let ctx = CqrsContext::default();

// The aggregate ID will be "user_42_right_7" (deterministic)
let id = engine.execute_create(
    GrantRight { user_id: "user_42".into(), right_id: "right_7".into() },
    &ctx,
).await?;
assert_eq!(id, "user_42_right_7");

// Later, revoke using the same deterministic ID
engine.execute_update(&id, UserRightUpdateCommand::Revoke, &ctx).await?;
```

Without `with_id_generator`, the engine falls back to UUID v4 generation (default behavior, no breaking change).

## Storage Backends

### PostgreSQL (feature: `postgres`)

```rust
use cqrs_rust_lib::es::{postgres::PostgresPersist, EventStoreImpl};
use std::sync::Arc;
use tokio_postgres::NoTls;

let (client, conn) = tokio_postgres::connect("postgres://user:pass@localhost/db", NoTls).await?;
tokio::spawn(async move { let _ = conn.await; });
let client = Arc::new(client);

let store = EventStoreImpl::new(PostgresPersist::<Account>::new(client.clone()));
let engine = CqrsCommandEngine::new(store, vec![], (), Box::new(|_e| {}));
```

### MongoDB (feature: `mongodb`)

Same pattern with `es::mongodb::MongoDBPersist`.

## REST Routers (feature: `utoipa`)

Axum routers with auto-generated OpenAPI schemas:

- **Write router**: `rest::CQRSWriteRouter::routes(Arc<CqrsCommandEngine<A>>)`
- **Read router**: `rest::CQRSReadRouter::routes(repository, Aggregate::TYPE)`
- **Audit log router**: `rest::CQRSAuditLogRouter::routes(event_store, tag)`

See `example/todolist/src/api.rs` for complete wiring with Swagger UI.

## Architecture

```
Aggregate (state + events)     CommandHandler (commands -> events)
         \                       /
          CqrsCommandEngine ----+---- EventStore (persist)
                |                         |
           Dispatchers              Storage backends
          (projections)          (InMemory/PG/Mongo)
```

### Key Types

| Type | Description |
|------|-------------|
| `Aggregate` | Domain state, event application, identity |
| `CommandHandler` | Command processing, business validation |
| `CqrsCommandEngine` | Orchestrates command execution |
| `EventStore` / `EventStoreImpl` | Event persistence abstraction |
| `CqrsError` | Unified structured error type |
| `CqrsErrorCode` | Trait for domain-specific error codes |
| `CqrsContext` | Carries user, request ID, correlation |
| `Dispatcher` | React to persisted events (projections) |
| `View` / `ViewElements` | Read model projections |

## Examples

| Example | Storage | Features |
|---------|---------|----------|
| `example/bank` | MongoDB | Domain errors, commands, queries, views |
| `example/todolist` | PostgreSQL | REST API, Swagger UI, snapshots, integration tests |

### Run todolist

```bash
cargo run -p todolist -- start --pg-uri="postgres://user:pass@localhost:5432/db" --http-port=8081
```

### Run tests

```bash
cargo test             # lib tests
cargo test -p todolist # integration tests
```

## Migration Guides

- [Aggregate / CommandHandler Split]docs/migration_guide/split_aggregate.md
- [Domain Error Codes]docs/migration_guide/domain_errors.md

## License

This project is licensed under the terms found in the [LICENSE](LICENSE) file.

## Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.