es-entity 0.10.33

Event Sourcing Entity 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


## Setting up the Repositories

The repository setup is where the magic happens for nested entities.
We need to configure both the parent and child repositories with special attributes.
It is recommended to put both Repositories in the same file but only mark the parent one as `pub`.
This leverages the rust module system to enforce that the children cannot be accessed directly.

```rust
# extern crate es_entity;
# extern crate sqlx;
# extern crate serde;
# extern crate derive_builder;
# extern crate tokio;
# extern crate anyhow;
# use derive_builder::Builder;
# use es_entity::*;
# use serde::{Deserialize, Serialize};
# 
# es_entity::entity_id! {
#     SubscriptionId,
#     BillingPeriodId
# }
# 
# #[derive(EsEvent, Debug, Clone, Serialize, Deserialize)]
# #[serde(tag = "type", rename_all = "snake_case")]
# #[es_event(id = "BillingPeriodId")]
# pub enum BillingPeriodEvent {
#     Initialized {
#         id: BillingPeriodId,
#         subscription_id: SubscriptionId,
#     },
#     LineItemAdded {
#         amount: f64,
#         description: String,
#     },
#     Closed,
# }
# 
# #[derive(EsEntity, Builder)]
# #[builder(pattern = "owned", build_fn(error = "EntityHydrationError"))]
# pub struct BillingPeriod {
#     pub id: BillingPeriodId,
#     pub subscription_id: SubscriptionId,
#     pub is_current: bool,
#     pub line_items: Vec<LineItem>,
#     events: EntityEvents<BillingPeriodEvent>,
# }
# 
# #[derive(Debug, Clone)]
# pub struct LineItem {
#     pub amount: f64,
#     pub description: String,
# }
# 
# impl BillingPeriod {
#     pub fn add_line_item(&mut self, amount: f64, description: String) -> Idempotent<usize> {
#         idempotency_guard!(
#             self.events.iter_all().rev(),
#             already_applied: BillingPeriodEvent::LineItemAdded { amount: a, description: d, .. }
#                 if a == &amount && d == &description
#         );
# 
#         self.line_items.push(LineItem {
#             amount,
#             description: description.clone(),
#         });
#         
#         self.events.push(BillingPeriodEvent::LineItemAdded {
#             amount,
#             description,
#         });
# 
#         Idempotent::Executed(self.line_items.len())
#     }
# 
#     pub fn close(&mut self) -> Idempotent<()> {
#         idempotency_guard!(
#             self.events.iter_all().rev(),
#             already_applied: BillingPeriodEvent::Closed
#         );
# 
#         self.is_current = false;
#         self.events.push(BillingPeriodEvent::Closed);
#         
#         Idempotent::Executed(())
#     }
# }
# 
# impl TryFromEvents<BillingPeriodEvent> for BillingPeriod {
#     fn try_from_events(events: EntityEvents<BillingPeriodEvent>) -> Result<Self, EntityHydrationError> {
#         let mut builder = BillingPeriodBuilder::default().is_current(true);
#         let mut line_items = Vec::new();
# 
#         for event in events.iter_all() {
#             match event {
#                 BillingPeriodEvent::Initialized { id, subscription_id } => {
#                     builder = builder.id(*id).subscription_id(*subscription_id);
#                 }
#                 BillingPeriodEvent::LineItemAdded { amount, description } => {
#                     line_items.push(LineItem {
#                         amount: *amount,
#                         description: description.clone(),
#                     });
#                 }
#                 BillingPeriodEvent::Closed => {
#                     builder = builder.is_current(false)
#                 }
#             }
#         }
# 
#         builder
#             .line_items(line_items)
#             .events(events)
#             .build()
#     }
# }
# 
# #[derive(EsEvent, Debug, Clone, Serialize, Deserialize)]
# #[serde(tag = "type", rename_all = "snake_case")]
# #[es_event(id = "SubscriptionId")]
# pub enum SubscriptionEvent {
#     Initialized { id: SubscriptionId },
#     BillingPeriodStarted { period_id: BillingPeriodId },
# }
# 
# #[derive(EsEntity, Builder)]
# #[builder(pattern = "owned", build_fn(error = "EntityHydrationError"))]
# pub struct Subscription {
#     pub id: SubscriptionId,
#     current_period_id: Option<BillingPeriodId>,
#     events: EntityEvents<SubscriptionEvent>,
#     
#     // The key attribute - marks this field as containing nested entities
#     // Must be of type `Nested<T>`
#     // The #[builder(default)] will initialize it as empty as the repo loads
#     // the children after the parent as been hydrated.
#     #[es_entity(nested)]
#     #[builder(default)]
#     billing_periods: Nested<BillingPeriod>,
# }
# 
# impl Subscription {
#     pub fn start_new_billing_period(&mut self) -> Idempotent<BillingPeriodId> {
#         // Close the current billing period if there is one
#         if let Some(current_id) = self.current_period_id {
#             if let Some(current_period) = self.billing_periods.get_persisted_mut(&current_id) {
#                 current_period.close();
#             }
#         }
#         
#         // Create the new billing period
#         let new_period = NewBillingPeriod {
#             id: BillingPeriodId::new(),
#             subscription_id: self.id,
#         };
#         
#         let id = new_period.id;
#         self.billing_periods.add_new(new_period);
#         
#         // Update the current period tracking
#         self.current_period_id = Some(id);
#         self.events.push(SubscriptionEvent::BillingPeriodStarted { period_id: id });
#         
#         Idempotent::Executed(id)
#     }
#     
#     pub fn add_line_item_to_current_billing_period(&mut self, amount: f64, description: String) -> Idempotent<usize> {
#         // Use the tracked current period ID to access the billing period directly
#         if let Some(current_id) = self.current_period_id {
#             if let Some(current_period) = self.billing_periods.get_persisted_mut(&current_id) {
#                 return current_period.add_line_item(amount, description);
#             }
#         }
#         
#         Idempotent::AlreadyApplied
#     }
# }
# 
# impl TryFromEvents<SubscriptionEvent> for Subscription {
#     fn try_from_events(events: EntityEvents<SubscriptionEvent>) -> Result<Self, EntityHydrationError> {
#         let mut builder = SubscriptionBuilder::default();
#         
#         for event in events.iter_all() {
#             match event {
#                 SubscriptionEvent::Initialized { id } => {
#                     builder = builder.id(*id);
#                 }
#                 SubscriptionEvent::BillingPeriodStarted { period_id } => {
#                     builder = builder.current_billing_period(Some(*period_id));
#                 }
#             }
#         }
#         
#         builder
#             .events(events)
#             .build()
#     }
# }
# 
# #[derive(Debug, Clone, Builder)]
# pub struct NewSubscription {
#     pub id: SubscriptionId,
# }
# 
# impl IntoEvents<SubscriptionEvent> for NewSubscription {
#     fn into_events(self) -> EntityEvents<SubscriptionEvent> {
#         EntityEvents::init(
#             self.id,
#             vec![SubscriptionEvent::Initialized { id: self.id }],
#         )
#     }
# }
// private struct
struct BillingPeriods {
    pool: sqlx::PgPool,
}

#[derive(EsRepo, Debug)]
#[es_repo(entity = "Subscription")]
pub struct Subscriptions {
    pool: sqlx::PgPool,
    
    // Mark this field as containing the nested repository
    #[es_repo(nested)]
    billing_periods: BillingPeriods,
}

impl Subscriptions {
    pub fn new(pool: sqlx::PgPool) -> Self {
        Self {
            pool: pool.clone(),
            billing_periods: BillingPeriods { pool },
        }
    }
}
```

The important configuration here:
1. The child repository (`BillingPeriods`) marks the foreign key column with `parent`.
2. The parent repository (`Subscriptions`) includes the child repository as a field marked with `#[es_repo(nested)]`

## Using Nested Entities

Now we can use our aggregate with full type safety and automatic loading of nested entities:

```rust
# extern crate es_entity;
# extern crate sqlx;
# extern crate serde;
# extern crate derive_builder;
# extern crate tokio;
# extern crate anyhow;
# use derive_builder::Builder;
# use es_entity::*;
# use serde::{Deserialize, Serialize};
# es_entity::entity_id! {
#     SubscriptionId,
#     BillingPeriodId
# }
# #[derive(EsEvent, Debug, Clone, Serialize, Deserialize)]
# #[serde(tag = "type", rename_all = "snake_case")]
# #[es_event(id = "BillingPeriodId")]
# pub enum BillingPeriodEvent {
#     Initialized {
#         id: BillingPeriodId,
#         subscription_id: SubscriptionId,
#     },
#     LineItemAdded {
#         amount: f64,
#         description: String,
#     },
#     Closed,
# }
# #[derive(EsEntity, Builder)]
# #[builder(pattern = "owned", build_fn(error = "EntityHydrationError"))]
# pub struct BillingPeriod {
#     pub id: BillingPeriodId,
#     pub subscription_id: SubscriptionId,
#     pub is_current: bool,
#     pub line_items: Vec<LineItem>,
#     events: EntityEvents<BillingPeriodEvent>,
# }
# #[derive(Debug, Clone)]
# pub struct LineItem {
#     pub amount: f64,
#     pub description: String,
# }
# impl BillingPeriod {
#     pub fn add_line_item(&mut self, amount: f64, description: String) -> Idempotent<usize> {
#         if !self.is_current {
#             unreachable!()
#         }
#         idempotency_guard!(
#             self.events.iter_all().rev(),
#             already_applied: BillingPeriodEvent::LineItemAdded { amount: a, description: d, .. }
#                 if a == &amount && d == &description
#         );
#         self.line_items.push(LineItem {
#             amount,
#             description: description.clone(),
#         });
#         self.events.push(BillingPeriodEvent::LineItemAdded {
#             amount,
#             description,
#         });
#         Idempotent::Executed(self.line_items.len())
#     }
#     pub fn close(&mut self) -> Idempotent<()> {
#         idempotency_guard!(
#             self.events.iter_all().rev(),
#             already_applied: BillingPeriodEvent::Closed
#         );
#         self.is_current = false;
#         self.events.push(BillingPeriodEvent::Closed);
#         Idempotent::Executed(())
#     }
# }
# impl TryFromEvents<BillingPeriodEvent> for BillingPeriod {
#     fn try_from_events(events: EntityEvents<BillingPeriodEvent>) -> Result<Self, EntityHydrationError> {
#         let mut builder = BillingPeriodBuilder::default();
#         let mut line_items = Vec::new();
#         let mut is_current = true;
#         for event in events.iter_all() {
#             match event {
#                 BillingPeriodEvent::Initialized { id, subscription_id } => {
#                     builder = builder.id(*id).subscription_id(*subscription_id);
#                 }
#                 BillingPeriodEvent::LineItemAdded { amount, description } => {
#                     line_items.push(LineItem {
#                         amount: *amount,
#                         description: description.clone(),
#                     });
#                 }
#                 BillingPeriodEvent::Closed => {
#                     is_current = false;
#                 }
#             }
#         }
#         builder
#             .is_current(is_current)
#             .line_items(line_items)
#             .events(events)
#             .build()
#     }
# }
# #[derive(Debug, Clone, Builder)]
# pub struct NewBillingPeriod {
#     pub id: BillingPeriodId,
#     pub subscription_id: SubscriptionId,
# }
# impl IntoEvents<BillingPeriodEvent> for NewBillingPeriod {
#     fn into_events(self) -> EntityEvents<BillingPeriodEvent> {
#         EntityEvents::init(
#             self.id,
#             vec![BillingPeriodEvent::Initialized {
#                 id: self.id,
#                 subscription_id: self.subscription_id,
#             }],
#         )
#     }
# }
# #[derive(EsEvent, Debug, Clone, Serialize, Deserialize)]
# #[serde(tag = "type", rename_all = "snake_case")]
# #[es_event(id = "SubscriptionId")]
# pub enum SubscriptionEvent {
#     Initialized { id: SubscriptionId },
#     BillingPeriodStarted { period_id: BillingPeriodId },
# }
# #[derive(EsEntity, Builder)]
# #[builder(pattern = "owned", build_fn(error = "EntityHydrationError"))]
# pub struct Subscription {
#     pub id: SubscriptionId,
#     current_period_id: Option<BillingPeriodId>,
#     events: EntityEvents<SubscriptionEvent>,
#     #[es_entity(nested)]
#     #[builder(default)]
#     billing_periods: Nested<BillingPeriod>,
# }
# impl Subscription {
#     pub fn start_new_billing_period(&mut self) -> Idempotent<BillingPeriodId> {
#         if let Some(current_id) = self.current_period_id {
#             if let Some(current_period) = self.billing_periods.get_persisted_mut(&current_id) {
#                 current_period.close();
#             }
#         }
#         let new_period = NewBillingPeriod {
#             id: BillingPeriodId::new(),
#             subscription_id: self.id,
#         };
#         let id = new_period.id;
#         self.billing_periods.add_new(new_period);
#         self.current_period_id = Some(id);
#         self.events.push(SubscriptionEvent::BillingPeriodStarted { period_id: id });
#         Idempotent::Executed(id)
#     }
#     pub fn add_line_item_to_current_billing_period(&mut self, amount: f64, description: String) -> Idempotent<usize> {
#         if let Some(current_id) = self.current_period_id {
#             if let Some(current_period) = self.billing_periods.get_persisted_mut(&current_id) {
#                 return current_period.add_line_item(amount, description);
#             }
#         }
#         Idempotent::AlreadyApplied
#     }
#     pub fn current_billing_period(&self) -> Option<&BillingPeriod> {
#         self.current_period_id
#             .and_then(|id| self.billing_periods.entities().get(&id))
#     }
#     pub fn all_billing_periods(&self) -> impl Iterator<Item = &BillingPeriod> {
#         self.billing_periods.entities().values()
#     }
# }
# impl TryFromEvents<SubscriptionEvent> for Subscription {
#     fn try_from_events(events: EntityEvents<SubscriptionEvent>) -> Result<Self, EntityHydrationError> {
#         let mut builder = SubscriptionBuilder::default();
#         let mut current_period_id = None;
#         for event in events.iter_all() {
#             match event {
#                 SubscriptionEvent::Initialized { id } => {
#                     builder = builder.id(*id);
#                 }
#                 SubscriptionEvent::BillingPeriodStarted { period_id } => {
#                     current_period_id = Some(*period_id);
#                 }
#             }
#         }
#         builder
#             .current_period_id(current_period_id)
#             .events(events)
#             .build()
#     }
# }
# #[derive(Debug, Clone, Builder)]
# pub struct NewSubscription {
#     pub id: SubscriptionId,
# }
# impl IntoEvents<SubscriptionEvent> for NewSubscription {
#     fn into_events(self) -> EntityEvents<SubscriptionEvent> {
#         EntityEvents::init(
#             self.id,
#             vec![SubscriptionEvent::Initialized { id: self.id }],
#         )
#     }
# }
# #[derive(EsRepo, Debug)]
# #[es_repo(
#     entity = "BillingPeriod",
#     columns(
#         subscription_id(ty = "SubscriptionId", update(persist = false), list_for, parent)
#     )
# )]
# pub struct BillingPeriods {
#     pool: sqlx::PgPool,
# }
# #[derive(EsRepo, Debug)]
# #[es_repo(entity = "Subscription")]
# pub struct Subscriptions {
#     pool: sqlx::PgPool,
#     #[es_repo(nested)]
#     billing_periods: BillingPeriods,
# }
# impl Subscriptions {
#     pub fn new(pool: sqlx::PgPool) -> Self {
#         Self {
#             pool: pool.clone(),
#             billing_periods: BillingPeriods { pool },
#         }
#     }
# }
#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = sqlx::PgPool::connect(&database_url).await?;
    let subscriptions = Subscriptions::new(pool);
    
    // Create a new subscription
    let subscription_id = SubscriptionId::new();
    let new_subscription = NewSubscription { id: subscription_id };
    let mut subscription = subscriptions.create(new_subscription).await?;
    
    // Start a billing period
    subscription.start_new_billing_period();
    
    // Add some line items to the current period
    subscription.add_line_item_to_current_billing_period(
        100.0,
        "Monthly subscription fee".to_string()
    );
    subscription.add_line_item_to_current_billing_period(
        25.0,
        "Additional service charge".to_string()
    );
    
    // Persist all changes (both parent and nested entities)
    subscriptions.update(&mut subscription).await?;
    
    // Load the subscription - nested entities are automatically loaded
    let loaded = subscriptions.find_by_id(subscription_id).await?;
    
    // Access the current billing period
    if let Some(current_period) = loaded.current_billing_period() {
        println!("Current period has {} line items", current_period.line_items.len());
        for item in &current_period.line_items {
            println!("  - {}: ${}", item.description, item.amount);
        }
    }
    
    Ok(())
}
```

## Benefits of the Nested Approach

This approach provides several key benefits:

1. **Type Safety**: The aggregate boundary is enforced at compile time
2. **Atomic Updates**: All changes to the aggregate are persisted together
3. **Automatic Loading**: When you load the parent, all nested entities are loaded automatically
4. **Encapsulation**: All access to nested entities goes through the aggregate root
5. **Consistency**: The parent entity can enforce invariants across all its children

## Performance Considerations

While nesting provides strong consistency guarantees, there are some performance implications to consider:

1. **Loading**: All nested entities are loaded when the parent is loaded. For aggregates with many children, this could impact performance.
2. **Updates**: All nested entities are checked for changes during updates, even if only one was modified.
3. **Memory**: The entire aggregate is held in memory, which could be significant for large aggregates.

For these reasons, it's important to keep aggregates small and focused on a specific consistency boundary.

## When to Use Nesting

Use the nested approach when:
- You have a true invariant that spans multiple entities
- The child entities have no meaning without the parent
- You need to enforce consistency rules across the relationship
- The number of child entities is reasonably bounded

Avoid nesting when:
- The relationship is merely associative
- Child entities can exist independently
- You expect unbounded growth in the number of children
- Performance requirements dictate more granular loading/updating

Remember, as discussed in the aggregates chapter, there are often alternative designs that can avoid the need for nesting while still maintaining consistency.