this-rs 0.0.9

Framework for building complex multi-entity REST and GraphQL APIs with many relationships
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
# this-rs Framework Architecture

## πŸ“ Overview

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     USER APPLICATION                        β”‚
β”‚                                                             β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                β”‚
β”‚  β”‚   User   β”‚  β”‚ Company  β”‚  β”‚   Car    β”‚  ... Entities  β”‚
β”‚  β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜                β”‚
β”‚       β”‚             β”‚              β”‚                        β”‚
β”‚       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                       β”‚
β”‚                     β”‚                                       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                      β”‚
                      β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   THIS-RS FRAMEWORK                         β”‚
β”‚                                                             β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
β”‚  β”‚              CORE MODULE (Generic)                 β”‚    β”‚
β”‚  β”‚                                                    β”‚    β”‚
β”‚  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”‚    β”‚
β”‚  β”‚  β”‚  Entity  β”‚  β”‚  Link    β”‚  β”‚  Field   β”‚      β”‚    β”‚
β”‚  β”‚  β”‚  Traits  β”‚  β”‚  System  β”‚  β”‚  System  β”‚      β”‚    β”‚
β”‚  β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β”‚    β”‚
β”‚  β”‚                                                    β”‚    β”‚
β”‚  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”‚    β”‚
β”‚  β”‚  β”‚ Service  β”‚  β”‚Pluralize β”‚  β”‚  Module  β”‚      β”‚    β”‚
β”‚  β”‚  β”‚  Traits  β”‚  β”‚  System  β”‚  β”‚  System  β”‚      β”‚    β”‚
β”‚  β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β”‚    β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β”‚                           β”‚                                 β”‚
β”‚       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”           β”‚
β”‚       β–Ό                   β–Ό                   β–Ό           β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”‚
β”‚  β”‚ LINKS   β”‚      β”‚   CONFIG    β”‚      β”‚ENTITIES β”‚      β”‚
β”‚  β”‚ MODULE  │◄──────   MODULE    │─────►│ MODULE  β”‚      β”‚
β”‚  β”‚         β”‚      β”‚             β”‚      β”‚         β”‚      β”‚
β”‚  β”‚ Service β”‚      β”‚ YAML Loader β”‚      β”‚ Macros  β”‚      β”‚
β”‚  β”‚Registry β”‚      β”‚   Parser    β”‚      β”‚         β”‚      β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β”‚
β”‚                                                             β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                      β”‚
                      β–Ό
            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
            β”‚   STORAGE LAYER  β”‚
            β”‚                  β”‚
            β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
            β”‚  β”‚  In-Memory β”‚  β”‚
            β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
            β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
            β”‚  β”‚  DynamoDB  β”‚  β”‚
            β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

## πŸ—οΈ Detailed Modules

### 1. Core Module (Generic)

The heart of the framework, completely agnostic of concrete entity types.

```
src/core/
β”œβ”€β”€ entity.rs       ← Fundamental traits
β”‚   β”œβ”€β”€ Entity      : Base trait (id, type, timestamps, status)
β”‚   β”œβ”€β”€ Data        : Inherits Entity, adds name + indexed fields
β”‚   └── Link        : Inherits Entity, adds source_id + target_id
β”‚
β”œβ”€β”€ link.rs         ← Polymorphic link system
β”‚   β”œβ”€β”€ LinkEntity     : Concrete link implementation
β”‚   └── LinkDefinition : Link type configuration
β”‚
β”œβ”€β”€ field.rs        ← Types and validation
β”‚   β”œβ”€β”€ FieldValue     : Polymorphic value (String, Int, UUID, etc.)
β”‚   └── FieldFormat    : Validators (Email, URL, Phone, Custom)
β”‚
β”œβ”€β”€ service.rs      ← Service traits
β”‚   β”œβ”€β”€ DataService<T> : CRUD for entities
β”‚   └── LinkService    : CRUD for links
β”‚
β”œβ”€β”€ module.rs       ← Module system
β”‚   β”œβ”€β”€ Module         : Groups entities + config
β”‚   β”œβ”€β”€ EntityFetcher  : Fetch entities for link enrichment
β”‚   └── EntityCreator  : Create entities dynamically
β”‚
β”œβ”€β”€ pluralize.rs    ← Pluralization
β”‚   └── Pluralizer     : company β†’ companies
β”‚
β”œβ”€β”€ auth.rs         ← Authorization
β”‚   β”œβ”€β”€ AuthProvider   : Auth policy provider
β”‚   └── AuthContext    : User auth context
β”‚
└── extractors.rs   ← HTTP extractors (Axum)
    β”œβ”€β”€ LinkExtractor      : Extract link info from URL
    └── DirectLinkExtractor: Extract specific link from URL
```

**Key Principle**: No reference to concrete types (User, Car, etc.) in core.

## 🎯 Entity Hierarchy

The framework provides a 3-level entity hierarchy:

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              Entity (Base)              β”‚
β”‚  - id: Uuid (auto-generated)            β”‚
β”‚  - type: String (auto-set)              β”‚
β”‚  - created_at: DateTime<Utc>            β”‚
β”‚  - updated_at: DateTime<Utc>            β”‚
β”‚  - deleted_at: Option<DateTime<Utc>>    β”‚
β”‚  - status: String                       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                  β”‚
         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”
         β”‚                 β”‚
         β–Ό                 β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Data Entity    β”‚  β”‚  Link Entity    β”‚
β”‚  (Inherits)     β”‚  β”‚  (Inherits)     β”‚
β”‚                 β”‚  β”‚                 β”‚
β”‚  + name: String β”‚  β”‚  + source_id    β”‚
β”‚  + custom fieldsβ”‚  β”‚  + target_id    β”‚
β”‚                 β”‚  β”‚  + link_type    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

### Entity (Base Trait)

All entities inherit these fields:
```rust
pub trait Entity {
    fn id(&self) -> Uuid;
    fn entity_type(&self) -> &str;
    fn created_at(&self) -> DateTime<Utc>;
    fn updated_at(&self) -> DateTime<Utc>;
    fn deleted_at(&self) -> Option<DateTime<Utc>>;
    fn status(&self) -> &str;
    
    // Utility methods
    fn is_deleted(&self) -> bool;
    fn is_active(&self) -> bool;
}
```

### Data (Inherits Entity)

Data entities represent domain objects:
```rust
pub trait Data: Entity {
    fn name(&self) -> &str;
    fn indexed_fields(&self) -> Vec<&str>;
    fn field_value(&self, field_name: &str) -> Option<FieldValue>;
}
```

### Link (Inherits Entity)

Link entities represent relationships:
```rust
pub trait Link: Entity {
    fn source_id(&self) -> Uuid;
    fn target_id(&self) -> Uuid;
    fn link_type(&self) -> &str;
}
```

## πŸ”§ Macro System

The framework provides powerful macros to eliminate boilerplate:

### `impl_data_entity!`

Generates a complete Data entity:

```rust
impl_data_entity!(Order, "order", ["name", "number"], {
    number: String,
    amount: f64,
    customer_name: Option<String>,
    notes: Option<String>,
});
```

**Generates**:
```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Order {
    // Base Entity fields (auto-injected)
    pub id: Uuid,
    pub entity_type: String,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub deleted_at: Option<DateTime<Utc>>,
    pub status: String,
    
    // Data field (auto-injected)
    pub name: String,
    
    // Custom fields
    pub number: String,
    pub amount: f64,
    pub customer_name: Option<String>,
    pub notes: Option<String>,
}

impl Entity for Order { /* auto-implemented */ }
impl Data for Order { /* auto-implemented */ }

impl Order {
    pub fn new(...) -> Self { /* auto-generated constructor */ }
    pub fn soft_delete(&mut self) { /* soft delete support */ }
    pub fn touch(&mut self) { /* update timestamp */ }
    pub fn set_status(&mut self, status: String) { /* status update */ }
    pub fn restore(&mut self) { /* restore from soft delete */ }
}
```

### `impl_link_entity!`

Generates a custom Link entity:

```rust
impl_link_entity!(CustomLink, "custom_link", {
    metadata_field: String,
});
```

### Field Injection Macros

- `entity_fields!()` - Inject base Entity fields
- `data_fields!()` - Inject Entity + name fields
- `link_fields!()` - Inject Entity + link fields

## πŸ”— Links Module (Agnostic)

Manages relationships between entities without knowing their types.

```
src/links/
β”œβ”€β”€ handlers.rs     ← HTTP handlers (Axum)
β”‚   β”œβ”€β”€ list_links          : GET /{entity}/{id}/{route_name}
β”‚   β”œβ”€β”€ get_link            : GET /links/{link_id}
β”‚   β”œβ”€β”€ get_link_by_route   : GET /{source}/{sid}/{route}/{tid}
β”‚   β”œβ”€β”€ create_link         : POST /{source}/{sid}/{route}/{tid}
β”‚   β”œβ”€β”€ create_linked_entity: POST /{source}/{sid}/{route}
β”‚   β”œβ”€β”€ update_link         : PUT /{source}/{sid}/{route}/{tid}
β”‚   └── delete_link         : DELETE /{source}/{sid}/{route}/{tid}
β”‚
β”œβ”€β”€ registry.rs     ← Route resolution
β”‚   └── LinkRouteRegistry : URL β†’ LinkDefinition
β”‚
└── service.rs      ← Link service implementation
    └── (moved to storage/)
```

### Generated Routes

From YAML configuration:
```yaml
links:
  - link_type: owner
    source_type: user
    target_type: car
    forward_route_name: cars-owned
    reverse_route_name: owner
```

**Auto-generated routes**:
```
GET    /users/{id}/cars-owned              β†’ List cars owned by user
POST   /users/{id}/cars-owned              β†’ Create new car + link
GET    /users/{id}/cars-owned/{car_id}     β†’ Get specific link
POST   /users/{id}/cars-owned/{car_id}     β†’ Link existing car
PUT    /users/{id}/cars-owned/{car_id}     β†’ Update link metadata
DELETE /users/{id}/cars-owned/{car_id}     β†’ Delete link

GET    /cars/{id}/owner                    β†’ Get owner of car (reverse)
```

## 🎨 Module System

Modules group related entities and provide services:

```rust
pub trait Module: Send + Sync {
    fn name(&self) -> &str;
    fn entity_types(&self) -> Vec<&str>;
    fn links_config(&self) -> Result<LinksConfig>;
    fn register_entities(&self, registry: &mut EntityRegistry);
    fn get_entity_fetcher(&self, entity_type: &str) -> Option<Arc<dyn EntityFetcher>>;
    fn get_entity_creator(&self, entity_type: &str) -> Option<Arc<dyn EntityCreator>>;
}
```

### EntityFetcher

Dynamically fetches entities for link enrichment:

```rust
#[async_trait]
pub trait EntityFetcher: Send + Sync {
    async fn fetch_as_json(&self, entity_id: &Uuid) -> Result<serde_json::Value>;
}
```

**Implementation example**:
```rust
#[async_trait]
impl EntityFetcher for OrderStore {
    async fn fetch_as_json(&self, entity_id: &Uuid) -> Result<serde_json::Value> {
        let order = self.get(entity_id)
            .ok_or_else(|| anyhow::anyhow!("Order not found"))?;
        Ok(serde_json::to_value(order)?)
    }
}
```

### EntityCreator

Dynamically creates entities with automatic linking:

```rust
#[async_trait]
pub trait EntityCreator: Send + Sync {
    async fn create_from_json(&self, entity_data: serde_json::Value) -> Result<serde_json::Value>;
}
```

**Implementation example**:
```rust
#[async_trait]
impl EntityCreator for OrderStore {
    async fn create_from_json(&self, entity_data: serde_json::Value) -> Result<serde_json::Value> {
        let order = Order::new(
            entity_data["number"].as_str().unwrap_or("").to_string(),
            entity_data["status"].as_str().unwrap_or("active").to_string(),
            // ... other fields
        );
        self.add(order.clone());
        Ok(serde_json::to_value(order)?)
    }
}
```

## πŸ”„ Data Flow

### Creating a Link Between Existing Entities

```
1. HTTP Request
   POST /users/{user_id}/cars-owned/{car_id}
   Body: { "metadata": { "purchase_date": "2024-01-15" } }

2. Axum Handler (create_link)
   ↓ DirectLinkExtractor parses URL
   ↓ Extracts: source_id, target_id, link_type

3. LinkService.create()
   ↓ Creates LinkEntity
   ↓ link_type: "owner"
   ↓ source_id: user_id (UUID)
   ↓ target_id: car_id (UUID)

4. Storage Layer
   ↓ Insert LinkEntity

5. Response
   ← LinkEntity { id, link_type, source_id, target_id, ... }
```

### Creating New Entity + Link Automatically

```
1. HTTP Request
   POST /users/{user_id}/cars-owned
   Body: {
     "entity": { "name": "Tesla Model 3", "brand": "Tesla", ... },
     "metadata": { "purchase_date": "2024-01-15" }
   }

2. Axum Handler (create_linked_entity)
   ↓ LinkExtractor parses URL
   ↓ Extracts: source_id, entity_type, route_name

3. Get EntityCreator from Module
   ↓ module.get_entity_creator("car")

4. EntityCreator.create_from_json()
   ↓ Creates new Car entity
   ↓ Stores in database
   ↓ Returns created entity with ID

5. LinkService.create()
   ↓ Creates link: user_id β†’ car_id

6. Response
   ← {
       "entity": { /* created car */ },
       "link": { /* created link */ }
     }
```

### Querying Links (Auto-Enriched)

```
1. HTTP Request
   GET /users/{user_id}/cars-owned

2. LinkRouteRegistry.resolve_route()
   ↓ "user" + "cars-owned"
   ↓ β†’ LinkDefinition { link_type: "owner", ... }
   ↓ β†’ Direction: Forward

3. LinkService.find_by_source()
   ↓ source_id: user_id
   ↓ source_type: "user"
   ↓ link_type: Some("owner")
   ↓ target_type: Some("car")

4. Enrich Links (enrich_links_with_entities)
   ↓ For each link:
   ↓   - Get EntityFetcher for "car"
   ↓   - Fetch full car entity by target_id
   ↓   - Embed in link response

5. Response
   ← {
       "links": [
         {
           "id": "link-123",
           "source_id": "user-uuid",
           "target_id": "car-uuid",
           "target": { /* FULL car entity */ },
           "metadata": { /* link metadata */ }
         }
       ]
     }
```

**Key**: No N+1 queries! Entities are fetched efficiently.

## πŸ“¦ Config Module

Loads and parses YAML configuration:

```
src/config/
└── mod.rs
    β”œβ”€β”€ LinksConfig    : Complete configuration
    └── EntityConfig   : Entity configuration
```

**YAML structure**:
```yaml
entities:
  - singular: order
    plural: orders
  - singular: invoice
    plural: invoices

links:
  - link_type: has_invoice
    source_type: order
    target_type: invoice
    forward_route_name: invoices
    reverse_route_name: order
    description: "Order has invoices"
    auth:
      create:
        policy: AllowOwner
        roles: ["admin", "user"]
```

## πŸ—„οΈ Storage Layer

```
src/storage/
β”œβ”€β”€ in_memory.rs    ← In-memory implementation
β”‚   └── InMemoryLinkService
β”‚
└── dynamodb.rs     ← DynamoDB implementation
    β”œβ”€β”€ DynamoDbDataService<T>
    └── DynamoDbLinkService
```

Both implement the same traits:
- `DataService<T>` for entity CRUD
- `LinkService` for link CRUD

## πŸ›οΈ Server Architecture

### ServerBuilder

Fluent API for building HTTP servers:

```rust
let app = ServerBuilder::new()
    .with_link_service(InMemoryLinkService::new())
    .register_module(billing_module)?
    .register_module(catalog_module)?
    .build()?;
```

**What it does**:
1. Collects all modules
2. Merges YAML configurations
3. Registers all entity descriptors
4. Builds entity CRUD routes
5. Builds generic link routes
6. Collects EntityFetchers
7. Collects EntityCreators
8. Creates AppState
9. Returns complete Axum Router

### EntityRegistry

Collects and builds entity routes:

```rust
pub struct EntityRegistry {
    descriptors: Vec<Box<dyn EntityDescriptor>>,
}

impl EntityRegistry {
    pub fn register(&mut self, descriptor: Box<dyn EntityDescriptor>);
    pub fn build_routes(&self) -> Router;
}
```

## 🎭 Key Design Patterns

### 1. Type Erasure

Core framework never knows concrete types:
```rust
// βœ… Framework uses trait objects
Arc<dyn EntityFetcher>
Arc<dyn EntityCreator>
Arc<dyn DataService<T>>

// ❌ Framework never does this
Arc<OrderStore>
Arc<UserService>
```

### 2. Dynamic Dispatch

Entities are fetched/created dynamically at runtime:
```rust
let fetcher = module.get_entity_fetcher("order")?;
let entity = fetcher.fetch_as_json(&order_id).await?;
```

### 3. Macro-Driven Code Generation

Eliminate boilerplate with compile-time generation:
```rust
// Input: 4 lines
impl_data_entity!(Order, "order", ["name"], {
    amount: f64,
});

// Output: 100+ lines of generated code
```

### 4. Configuration-Driven Behavior

Routes and validation defined in YAML:
```yaml
links:
  - link_type: owner
    source_type: user
    target_type: car
    forward_route_name: cars-owned
```

### 5. Dependency Injection

Modules provide services through trait methods:
```rust
impl Module for BillingModule {
    fn get_entity_fetcher(&self, entity_type: &str) -> Option<Arc<dyn EntityFetcher>> {
        match entity_type {
            "order" => Some(Arc::new(self.store.orders.clone())),
            _ => None,
        }
    }
}
```

## πŸš€ Benefits

### For Framework Users

βœ… **Zero Boilerplate**: Define entities in 4 lines  
βœ… **Auto-Generated Routes**: No manual routing code  
βœ… **Type Safety**: Full Rust compile-time checks  
βœ… **Consistent Patterns**: Same structure everywhere  
βœ… **Link Enrichment**: No N+1 query problems  

### For Framework Developers

βœ… **Extensibility**: Easy to add new storage backends  
βœ… **Testability**: Trait-based design allows mocking  
βœ… **Modularity**: Clear separation of concerns  
βœ… **Maintainability**: Generic core never changes  

## πŸ“š Next Steps

- [Server Builder Implementation]SERVER_BUILDER_IMPLEMENTATION.md
- [Routing Explanation]ROUTING_EXPLANATION.md
- [Link Authorization]LINK_AUTH_IMPLEMENTATION.md
- [Getting Started Guide]../guides/GETTING_STARTED.md

---

**The architecture is designed for maximum productivity with zero compromise on type safety.** πŸš€πŸ¦€βœ¨