armature-framework 0.2.2

A modern, type-safe HTTP framework for Rust inspired by Angular and NestJS. Features dependency injection, decorators, middleware, authentication (JWT/OAuth2/SAML), validation, OpenAPI/Swagger, caching, job queues, and observability.
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
# Dependency Injection Guide

This guide explains how dependency injection works in Armature and how to use it effectively.

## Overview

Armature provides a complete dependency injection system inspired by Angular. Services are automatically injected into controllers based on their field types, enabling loose coupling and testability.

## Core Concepts

### 1. Injectable Services

Mark a struct with `#[injectable]` to make it available for injection:

```rust
#[injectable]
#[derive(Default, Clone)]
struct DatabaseService {
    connection_string: String,
}
```

**Requirements:**
- Must implement `Default` (for automatic instantiation)
- Must implement `Clone` (for sharing across the application)
- Must be `Send + Sync + 'static` (for thread safety)

### 2. Service Dependencies

Services can depend on other services by declaring them as fields:

```rust
#[injectable]
#[derive(Default, Clone)]
struct UserService {
    database: DatabaseService,  // Will be auto-injected
    logger: LoggerService,       // Will be auto-injected
}
```

### 3. Controllers with DI

Controllers automatically receive injected services:

```rust
#[controller("/users")]
#[derive(Default, Clone)]
struct UserController {
    user_service: UserService,  // Automatically injected!
}

impl UserController {
    // Methods can now use self.user_service
    fn get_users(&self) -> Result<Json<Vec<User>>, Error> {
        let users = self.user_service.find_all();
        Ok(Json(users))
    }
}
```

## How It Works

### Registration Order

The framework automatically handles dependency registration in the correct order:

1. **Imported modules** are registered first (depth-first)
2. **Providers** (services) are registered in declaration order
3. **Controllers** are instantiated with resolved dependencies
4. **Routes** are registered for each controller

### Dependency Resolution

When a controller is created:

1. The framework inspects the controller's fields
2. For each field, it resolves the service from the DI container
3. The controller is constructed with all dependencies injected
4. The controller instance is cached for reuse

### Container Lifecycle

- Services are **singletons** by default
- Once created, the same instance is shared across the application
- This ensures efficient resource usage (e.g., database connections)

## Usage Examples

### Example 1: Simple Service Injection

```rust
use armature_framework::prelude::*;

// Service with no dependencies
#[injectable]
#[derive(Default, Clone)]
struct ConfigService {
    api_url: String,
}

// Controller using the service
#[controller("/api")]
#[derive(Default, Clone)]
struct ApiController {
    config: ConfigService,
}

impl ApiController {
    #[get("/info")]
    async fn info(&self) -> Result<Json<String>, Error> {
        Ok(Json(self.config.api_url.clone()))
    }
}

#[module(
    providers: [ConfigService],
    controllers: [ApiController]
)]
#[derive(Default)]
struct AppModule;
```

### Example 2: Service Chain

```rust
// Level 1: Base service
#[injectable]
#[derive(Default, Clone)]
struct LoggerService;

// Level 2: Service depending on Logger
#[injectable]
#[derive(Default, Clone)]
struct DatabaseService {
    logger: LoggerService,
}

// Level 3: Service depending on Database
#[injectable]
#[derive(Default, Clone)]
struct UserService {
    database: DatabaseService,
}

// Level 4: Controller depending on UserService
#[controller("/users")]
#[derive(Default, Clone)]
struct UserController {
    user_service: UserService,
}

#[module(
    providers: [LoggerService, DatabaseService, UserService],
    controllers: [UserController]
)]
#[derive(Default)]
struct AppModule;
```

The framework ensures all dependencies are resolved in the correct order.

### Example 3: Multiple Dependencies

```rust
#[injectable]
#[derive(Default, Clone)]
struct AuthService;

#[injectable]
#[derive(Default, Clone)]
struct CacheService;

#[injectable]
#[derive(Default, Clone)]
struct EmailService;

#[injectable]
#[derive(Default, Clone)]
struct UserService {
    auth: AuthService,
    cache: CacheService,
    email: EmailService,
}

#[controller("/users")]
#[derive(Default, Clone)]
struct UserController {
    user_service: UserService,
    auth_service: AuthService,  // Can inject same service multiple times
}
```

## Module System

### Provider Declaration

Providers must be declared in the module:

```rust
#[module(
    providers: [ServiceA, ServiceB, ServiceC],
    controllers: [ControllerX, ControllerY]
)]
```

**Order matters for providers:**
- List services with no dependencies first
- Then list services that depend on earlier services
- The framework registers them in declaration order

### Module Imports

Modules can import other modules to access their services:

```rust
#[module(
    providers: [SharedService],
    exports: [SharedService]  // Make available to importers
)]
#[derive(Default)]
struct SharedModule;

#[module(
    providers: [UserService],
    controllers: [UserController],
    imports: [SharedModule]  // Import shared services
)]
#[derive(Default)]
struct UserModule;
```

## Registering Built-in Services

Armature provides many built-in services that you can register in the DI container. Here are examples of how to register commonly used services.

### Health Check Service

```rust
use armature_core::{
    Container, Provider, HealthService, HealthServiceBuilder,
    MemoryHealthIndicator, DiskHealthIndicator, UptimeHealthIndicator,
};

// Method 1: Register a pre-built HealthService using the builder
fn register_health_service(container: &Container) {
    let health_service = HealthServiceBuilder::new()
        .with_defaults()  // Adds memory, disk, and uptime indicators
        .with_info(|info| {
            info.name("my-api")
                .version("1.0.0")
                .description("My REST API")
        })
        .build();

    container.register(health_service);
}

// Method 2: Register with custom indicators only
fn register_custom_health_service(container: &Container) {
    let health_service = HealthServiceBuilder::new()
        .with_indicator(MemoryHealthIndicator::new(0.9))  // 90% threshold
        .with_indicator(UptimeHealthIndicator::default())
        .build();

    container.register(health_service);
}

// Using the health service in a controller
#[controller("/health")]
#[derive(Default, Clone)]
struct HealthController {
    health_service: HealthService,
}

impl HealthController {
    #[get("/")]
    async fn check(&self) -> Result<HttpResponse, Error> {
        let response = self.health_service.check().await;
        Ok(HttpResponse::new(response.status.http_status_code())
            .with_json(&response)?)
    }

    #[get("/live")]
    async fn liveness(&self) -> Result<HttpResponse, Error> {
        let response = self.health_service.liveness().await;
        Ok(HttpResponse::new(response.status.http_status_code())
            .with_json(&response)?)
    }

    #[get("/ready")]
    async fn readiness(&self) -> Result<HttpResponse, Error> {
        let response = self.health_service.readiness().await;
        Ok(HttpResponse::new(response.status.http_status_code())
            .with_json(&response)?)
    }
}
```

### Registering Services in Modules

```rust
use armature_core::{
    Module, Container, ProviderRegistration, ControllerRegistration,
    HealthService, HealthServiceBuilder,
};
use std::any::TypeId;

struct AppModule;

impl Module for AppModule {
    fn providers(&self) -> Vec<ProviderRegistration> {
        vec![
            // Register HealthService with custom configuration
            ProviderRegistration {
                type_id: TypeId::of::<HealthService>(),
                type_name: "HealthService",
                register_fn: |container| {
                    let health_service = HealthServiceBuilder::new()
                        .with_defaults()
                        .with_info(|info| info.name("my-app").version("1.0.0"))
                        .build();
                    container.register(health_service);
                },
            },
            // Register other services...
        ]
    }

    fn controllers(&self) -> Vec<ControllerRegistration> {
        vec![]  // Your controllers
    }

    fn imports(&self) -> Vec<Box<dyn Module>> {
        vec![]
    }

    fn exports(&self) -> Vec<TypeId> {
        vec![TypeId::of::<HealthService>()]  // Export for child modules
    }
}
```

### Using Dynamic Modules for Service Registration

```rust
use armature_core::{DynamicModule, HealthService, HealthServiceBuilder, provider_registration};

// Create a reusable health module
fn create_health_module(app_name: &str, app_version: &str) -> DynamicModule {
    let name = app_name.to_string();
    let version = app_version.to_string();

    DynamicModule::new("HealthModule")
        .with_provider(ProviderRegistration {
            type_id: std::any::TypeId::of::<HealthService>(),
            type_name: "HealthService",
            register_fn: move |container| {
                let health_service = HealthServiceBuilder::new()
                    .with_defaults()
                    .build();
                container.register(health_service);
            },
        })
        .export::<HealthService>()
}

// Use it in your application
let health_module = create_health_module("my-api", "1.0.0");
```

### Database and Cache Services

```rust
use armature_core::{Container, Provider};

// Example: Custom database service wrapper
#[derive(Clone)]
struct DatabaseService {
    connection_string: String,
    // pool: Arc<Pool>  // Your actual connection pool
}

impl Provider for DatabaseService {}

impl DatabaseService {
    pub fn new(connection_string: &str) -> Self {
        Self {
            connection_string: connection_string.to_string(),
        }
    }
}

// Register in container
fn setup_database(container: &Container, connection_string: &str) {
    let db_service = DatabaseService::new(connection_string);
    container.register(db_service);
}

// Example: Cache service with configuration
#[derive(Clone)]
struct CacheService {
    ttl_seconds: u64,
}

impl Provider for CacheService {}

impl CacheService {
    pub fn new(ttl_seconds: u64) -> Self {
        Self { ttl_seconds }
    }
}

fn setup_cache(container: &Container) {
    container.register(CacheService::new(300));  // 5 minute TTL
}
```

## Advanced Patterns

### Constructor Injection

The generated `new_with_di` method is automatically called:

```rust
// Generated automatically by #[controller]
impl UserController {
    pub fn new_with_di(container: &Container) -> Result<Self, Error> {
        Ok(Self {
            user_service: (*container.resolve::<UserService>()?).clone(),
        })
    }
}
```

### Manual DI (for advanced use cases)

You can manually work with the container:

```rust
let container = Container::new();

// Register a service
container.register(MyService::default());

// Register with factory function
container.register_factory(|| {
    MyComplexService::new_with_config("some-config")
});

// Resolve a service
let service = container.resolve::<MyService>()?;

// Check if service exists
if container.has::<MyService>() {
    println!("MyService is registered");
}
```

### Registering Services from Configuration

```rust
use armature_core::{Container, Provider};
use std::env;

#[derive(Clone)]
struct AppConfig {
    database_url: String,
    redis_url: String,
    log_level: String,
}

impl Provider for AppConfig {}

impl AppConfig {
    pub fn from_env() -> Self {
        Self {
            database_url: env::var("DATABASE_URL")
                .unwrap_or_else(|_| "postgres://localhost/app".to_string()),
            redis_url: env::var("REDIS_URL")
                .unwrap_or_else(|_| "redis://localhost:6379".to_string()),
            log_level: env::var("LOG_LEVEL")
                .unwrap_or_else(|_| "info".to_string()),
        }
    }
}

fn setup_app(container: &Container) {
    // Load configuration from environment
    let config = AppConfig::from_env();
    container.register(config.clone());

    // Use config to set up other services
    let db_service = DatabaseService::new(&config.database_url);
    container.register(db_service);
}
```

### Testing with DI

DI makes testing easier by allowing mock injection:

```rust
#[cfg(test)]
mod tests {
    #[injectable]
    #[derive(Default, Clone)]
    struct MockDatabaseService {
        // Mock implementation
    }

    #[test]
    fn test_controller() {
        let container = Container::new();
        container.register(MockDatabaseService::default());

        let controller = UserController::new_with_di(&container).unwrap();
        // Test controller with mock dependencies
    }
}
```

## Best Practices

### 1. Keep Services Stateless

Services should be stateless or have immutable state:

```rust
// Good: Stateless
#[injectable]
#[derive(Default, Clone)]
struct UserService {
    db: DatabaseService,  // Shared connection pool
}

// Avoid: Mutable state
#[injectable]
#[derive(Default, Clone)]
struct CounterService {
    count: i32,  // This won't work as expected with Clone
}
```

### 2. Use Descriptive Names

```rust
// Good
#[injectable]
struct UserAuthenticationService;

// Avoid
#[injectable]
struct Service1;
```

### 3. Minimize Dependencies

Keep the dependency graph shallow:

```rust
// Good: 2-3 dependencies max
#[injectable]
struct UserService {
    database: DatabaseService,
    cache: CacheService,
}

// Avoid: Too many dependencies (consider refactoring)
#[injectable]
struct GodService {
    dep1: Service1,
    dep2: Service2,
    // ... 10 more dependencies
}
```

### 4. Interface Segregation

Create focused services with single responsibilities:

```rust
// Good: Focused services
#[injectable]
struct UserRepository;  // Data access

#[injectable]
struct UserValidator;  // Validation logic

#[injectable]
struct UserNotifier;   // Notifications

// Avoid: God object
#[injectable]
struct UserEverything;  // Does everything
```

## Troubleshooting

### "Provider not found" Error

**Cause:** Service not registered in module or wrong type.

**Solution:** Ensure the service is in the `providers` array:

```rust
#[module(
    providers: [MyService],  // Must be listed here!
    controllers: [MyController]
)]
```

### Circular Dependencies

**Cause:** Service A depends on B, B depends on A.

**Solution:** Refactor to break the cycle:

```rust
// Bad: Circular dependency
struct ServiceA { b: ServiceB }
struct ServiceB { a: ServiceA }  // Circular!

// Good: Extract shared dependency
struct ServiceA { shared: SharedService }
struct ServiceB { shared: SharedService }
struct SharedService { /* shared logic */ }
```

### Clone Not Implemented

**Cause:** Service doesn't implement `Clone`.

**Solution:** Add `#[derive(Clone)]` or implement it manually:

```rust
#[injectable]
#[derive(Default, Clone)]  // Add Clone here
struct MyService;
```

## Performance Considerations

### Singleton Pattern

- Services are created once and reused
- No performance overhead after initial creation
- Thread-safe through `Arc` internally

### Clone Overhead

- `Clone` on services is usually cheap (clones Arc pointers)
- For expensive resources, use Arc/Rc internally:

```rust
#[injectable]
#[derive(Default, Clone)]
struct DatabaseService {
    pool: Arc<ConnectionPool>,  // Cheap to clone
}
```

## Future Enhancements

Planned features for the DI system:

- [ ] `@Scope` decorator for request-scoped services
- [ ] `@Factory` for custom instantiation logic
- [ ] `@Lazy` for lazy-loaded services
- [ ] Interface-based injection with traits
- [ ] Conditional providers
- [ ] Provider configuration

## Comparison with Other Frameworks

### vs Spring (Java)
- Similar `@Injectable` / `@Service` concepts
- Similar `@Controller` pattern
- No XML configuration needed

### vs Angular (TypeScript)
- Nearly identical decorator syntax
- Same module system
- Constructor injection works similarly

### vs Actix-web (Rust)
- More explicit DI (vs implicit Data extractors)
- Compile-time safety
- Better testability

## Summary

Armature's DI system provides:

✅ **Automatic injection** based on field types
✅ **Type-safe** resolution at compile time
✅ **Modular** organization with imports/exports
✅ **Testable** through dependency injection
✅ **Performant** with singleton pattern
✅ **Familiar** syntax for Angular/Spring developers

The DI system is the foundation of Armature, enabling clean, maintainable, and testable code.