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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
# Server Integration Guide

Integration strategies for using Armature with external web servers like NGINX and Ferron.

## Table of Contents

- [Current Architecture]#current-architecture
- [Integration Patterns]#integration-patterns
- [NGINX Integration]#nginx-integration
- [Ferron Integration]#ferron-integration
- [Pluggable Server Backend]#pluggable-server-backend
- [Comparison]#comparison
- [Recommendations]#recommendations

---

## Current Architecture

Armature currently uses **Hyper** as its embedded HTTP server:

```rust
// armature-core/src/application.rs
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Request, Response, body::Incoming as IncomingBody};
```

**Benefits:**
- ✅ Zero-copy request handling
- ✅ Native async/await support
- ✅ Built-in HTTP/2 and HTTP/3 support
- ✅ No external dependencies
- ✅ Direct integration with Tokio

**Limitations:**
- ❌ No built-in load balancing
- ❌ No advanced routing/caching
- ❌ Limited static file optimization
- ❌ No zero-downtime reloads

---

## Integration Patterns

There are **three main approaches** to integrate external servers:

### 1. Reverse Proxy Pattern (Recommended)

```
┌─────────┐      ┌───────────┐      ┌───────────┐
│ Client  │─────▶│  NGINX/   │─────▶│ Armature  │
│         │      │  Ferron   │      │  (Hyper)  │
└─────────┘      └───────────┘      └───────────┘
                  Reverse Proxy      App Server
```

**Use Cases:**
- Load balancing across multiple Armature instances
- SSL/TLS termination
- Static asset serving
- Response caching
- Rate limiting
- DDoS protection

### 2. CGI/FastCGI/Module Pattern

```
┌─────────┐      ┌───────────────────────────┐
│ Client  │─────▶│  NGINX with Armature      │
│         │      │  as embedded module/CGI   │
└─────────┘      └───────────────────────────┘
```

**Use Cases:**
- Tight integration with web server
- Shared memory/cache
- Single process deployment

### 3. Pluggable Backend Pattern

```
┌───────────┐      ┌──────────────┐
│ Armature  │─────▶│   Backend    │
│   Core    │      │   Trait      │
└───────────┘      └──────────────┘
       ┌──────────────────┼──────────────────┐
       │                  │                  │
   ┌───▼───┐         ┌────▼────┐      ┌─────▼─────┐
   │ Hyper │         │  NGINX  │      │  Ferron   │
   └───────┘         └─────────┘      └───────────┘
```

**Use Cases:**
- Framework flexibility
- Testing different servers
- Custom server implementations

---

## NGINX Integration

### Approach 1: Reverse Proxy (Recommended)

#### Setup

**1. Armature Configuration:**

```rust
// main.rs
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = Application::create::<AppModule>().await;

    // Listen on localhost only (NGINX will forward)
    app.listen(3000).await?;
    Ok(())
}
```

**2. NGINX Configuration:**

```nginx
# /etc/nginx/sites-available/armature

upstream armature_backend {
    # Multiple instances for load balancing
    server 127.0.0.1:3000 max_fails=3 fail_timeout=30s;
    server 127.0.0.1:3001 max_fails=3 fail_timeout=30s;
    server 127.0.0.1:3002 max_fails=3 fail_timeout=30s;

    # Load balancing method
    least_conn;

    # Keep-alive connections
    keepalive 32;
}

server {
    listen 80;
    listen [::]:80;
    server_name example.com;

    # Redirect HTTP to HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com;

    # SSL Configuration
    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    # Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # Static files (serve directly from NGINX)
    location /static/ {
        alias /var/www/armature/static/;
        expires 1y;
        add_header Cache-Control "public, immutable";

        # Gzip compression
        gzip on;
        gzip_types text/css application/javascript image/svg+xml;
        gzip_min_length 1000;
    }

    # API routes (proxy to Armature)
    location / {
        proxy_pass http://armature_backend;

        # Headers
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # Timeouts
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

        # WebSocket support
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        # Buffering
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
    }

    # Rate limiting
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        proxy_pass http://armature_backend;
        # ... same proxy settings as above
    }

    # Health check endpoint
    location /health {
        access_log off;
        proxy_pass http://armature_backend/health;
    }
}

# Rate limiting zones
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
```

#### Systemd Service Files

**Armature Service:**

```ini
# /etc/systemd/system/armature@.service
[Unit]
Description=Armature Web Application (instance %i)
After=network.target

[Service]
Type=simple
User=armature
Group=armature
WorkingDirectory=/opt/armature
Environment="PORT=300%i"
Environment="RUST_LOG=info"
ExecStart=/opt/armature/target/release/armature-app
Restart=always
RestartSec=5

# Security
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/armature/logs

[Install]
WantedBy=multi-user.target
```

**Start multiple instances:**

```bash
# Enable and start 3 instances
sudo systemctl enable armature@0 armature@1 armature@2
sudo systemctl start armature@0 armature@1 armature@2

# Reload NGINX
sudo systemctl reload nginx
```

#### Benefits

✅ **Production-Ready**: NGINX handles SSL, compression, caching
✅ **Load Balancing**: Distribute load across multiple instances
✅ **Zero-Downtime Deploys**: Reload NGINX config without dropping connections
✅ **Static Assets**: NGINX serves static files efficiently
✅ **Security**: Rate limiting, DDoS protection, WAF integration
✅ **Monitoring**: NGINX logs, status page, metrics

### Approach 2: NGINX Dynamic Module

**Creating an Armature NGINX module** (advanced):

```c
// ngx_http_armature_module.c
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>

// FFI to Rust
extern ngx_int_t armature_handle_request(
    ngx_http_request_t *r,
    u_char *method,
    u_char *uri,
    u_char *body,
    size_t body_len
);

static ngx_int_t ngx_http_armature_handler(ngx_http_request_t *r) {
    // Call into Armature Rust code
    return armature_handle_request(
        r,
        r->method_name.data,
        r->uri.data,
        r->request_body->bufs->buf->pos,
        r->request_body->bufs->buf->last - r->request_body->bufs->buf->pos
    );
}

// Module definition
static ngx_command_t ngx_http_armature_commands[] = {
    {
        ngx_string("armature"),
        NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS,
        ngx_http_armature_handler,
        0,
        0,
        NULL
    },
    ngx_null_command
};

// ... module boilerplate
```

**Rust FFI side:**

```rust
// lib.rs
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_uchar};

#[no_mangle]
pub extern "C" fn armature_handle_request(
    r: *mut NgxHttpRequest,
    method: *const c_uchar,
    uri: *const c_uchar,
    body: *const c_uchar,
    body_len: usize,
) -> c_int {
    // Convert C strings to Rust
    let method = unsafe { CStr::from_ptr(method as *const c_char) }
        .to_str()
        .unwrap();

    // Route through Armature
    // ... implementation

    0 // NGX_OK
}
```

**Build configuration:**

```bash
# Configure NGINX with Armature module
./configure --add-dynamic-module=/path/to/armature-nginx-module

# Compile NGINX
make
make install
```

**NGINX config:**

```nginx
load_module modules/ngx_http_armature_module.so;

server {
    location / {
        armature;
    }
}
```

---

## Ferron Integration

[Ferron](https://ferron.sh/) is a modern web server written in Rust, making it potentially easier to integrate with Armature.

### Approach 1: Reverse Proxy

**Ferron Configuration:**

```toml
# ferron.toml
[server]
host = "0.0.0.0"
port = 80

[[proxies]]
name = "armature-backend"
path = "/"
backend = "http://127.0.0.1:3000"

# Load balancing
[[proxies.backends]]
url = "http://127.0.0.1:3000"
weight = 1

[[proxies.backends]]
url = "http://127.0.0.1:3001"
weight = 1

[[proxies.backends]]
url = "http://127.0.0.1:3002"
weight = 1

# Static files
[[static]]
path = "/static"
directory = "/var/www/static"
cache_control = "public, max-age=31536000"

# TLS
[tls]
enabled = true
cert = "/etc/ssl/certs/example.com.crt"
key = "/etc/ssl/private/example.com.key"
```

**Start Ferron:**

```bash
ferron --config ferron.toml
```

### Approach 2: Ferron as Library

Since Ferron is written in Rust, we could potentially embed it:

```rust
// Cargo.toml
[dependencies]
ferron-core = "0.1" # hypothetical

// main.rs
use ferron_core::Server as FerronServer;
use armature_framework::prelude::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = Application::create::<AppModule>().await;

    // Wrap Armature with Ferron
    let ferron = FerronServer::new()
        .with_handler(app)
        .with_static("/static", "/var/www/static")
        .with_rate_limiting()
        .build();

    ferron.listen("0.0.0.0:3000").await?;
    Ok(())
}
```

### Approach 3: Git Submodule Integration

**Add Ferron as git submodule:**

```bash
# Add Ferron source as submodule
git submodule add https://github.com/ferron-project/ferron.git external/ferron
git submodule update --init --recursive

# Add to Cargo workspace
```

**Cargo.toml:**

```toml
[workspace]
members = [
    "armature-core",
    "armature-macro",
    "armature",
    "external/ferron", # If Ferron exposes a library crate
]

[dependencies]
ferron = { path = "external/ferron" }
```

---

## Pluggable Server Backend

We could make Armature's HTTP server **pluggable** with a trait-based approach:

### Server Trait Design

```rust
// armature-core/src/server.rs

use async_trait::async_trait;
use crate::{HttpRequest, HttpResponse, Error};
use std::net::SocketAddr;

/// Trait for HTTP server backends
#[async_trait]
pub trait HttpServer: Send + Sync + 'static {
    /// Start the HTTP server
    async fn listen(&self, addr: SocketAddr) -> Result<(), Error>;

    /// Start the HTTPS server
    async fn listen_tls(
        &self,
        addr: SocketAddr,
        cert: &[u8],
        key: &[u8],
    ) -> Result<(), Error>;

    /// Graceful shutdown
    async fn shutdown(&self) -> Result<(), Error>;

    /// Get server name
    fn name(&self) -> &str;
}

/// Request handler callback
pub type RequestHandler = Arc<
    dyn Fn(HttpRequest) -> Pin<Box<dyn Future<Output = Result<HttpResponse, Error>> + Send>>
        + Send
        + Sync,
>;
```

### Hyper Backend (Default)

```rust
// armature-server-hyper/src/lib.rs

pub struct HyperServer {
    router: Arc<Router>,
    lifecycle: Arc<LifecycleManager>,
}

#[async_trait]
impl HttpServer for HyperServer {
    async fn listen(&self, addr: SocketAddr) -> Result<(), Error> {
        // Current implementation
        let listener = TcpListener::bind(addr).await?;
        // ... existing code
        Ok(())
    }

    fn name(&self) -> &str {
        "Hyper"
    }
}
```

### NGINX Backend (via Unix Socket)

```rust
// armature-server-nginx/src/lib.rs

pub struct NginxServer {
    router: Arc<Router>,
    socket_path: PathBuf,
}

#[async_trait]
impl HttpServer for NginxServer {
    async fn listen(&self, _addr: SocketAddr) -> Result<(), Error> {
        // Listen on Unix socket
        let listener = UnixListener::bind(&self.socket_path)?;

        loop {
            let (stream, _) = listener.accept().await?;
            let router = self.router.clone();

            tokio::spawn(async move {
                // Handle FastCGI/SCGI protocol
                handle_nginx_connection(stream, router).await;
            });
        }
    }

    fn name(&self) -> &str {
        "NGINX-FastCGI"
    }
}
```

### Ferron Backend

```rust
// armature-server-ferron/src/lib.rs

pub struct FerronServer {
    router: Arc<Router>,
    config: FerronConfig,
}

#[async_trait]
impl HttpServer for FerronServer {
    async fn listen(&self, addr: SocketAddr) -> Result<(), Error> {
        // Use Ferron's server implementation
        ferron_core::serve(addr, |req| {
            let router = self.router.clone();
            async move {
                let armature_req = convert_request(req);
                let armature_resp = router.route(armature_req).await?;
                Ok(convert_response(armature_resp))
            }
        })
        .await
    }

    fn name(&self) -> &str {
        "Ferron"
    }
}
```

### Application with Pluggable Server

```rust
// armature-core/src/application.rs

impl Application {
    /// Create application with custom server backend
    pub async fn with_server<S: HttpServer>(
        self,
        server: S,
    ) -> Result<(), Error> {
        println!("🚀 Using {} server backend", server.name());
        server.listen(SocketAddr::from(([0, 0, 0, 0], 3000))).await
    }
}

// Usage
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = Application::create::<AppModule>().await;

    // Choose backend
    #[cfg(feature = "nginx")]
    let server = NginxServer::new(app.router.clone());

    #[cfg(feature = "ferron")]
    let server = FerronServer::new(app.router.clone());

    #[cfg(not(any(feature = "nginx", feature = "ferron")))]
    let server = HyperServer::new(app.router.clone(), app.lifecycle.clone());

    app.with_server(server).await?;
    Ok(())
}
```

---

## Comparison

| Feature | Hyper (Current) | NGINX Reverse Proxy | Ferron Reverse Proxy | Pluggable Backend |
|---------|-----------------|---------------------|---------------------|-------------------|
| **Setup Complexity** | ⭐⭐⭐⭐⭐ Simple | ⭐⭐⭐ Moderate | ⭐⭐⭐⭐ Easy | ⭐⭐ Complex |
| **Performance** | ⭐⭐⭐⭐⭐ Excellent | ⭐⭐⭐⭐ Very Good | ⭐⭐⭐⭐ Very Good | ⭐⭐⭐⭐ Good |
| **Load Balancing** | ❌ No | ✅ Yes | ✅ Yes | ✅ Depends |
| **SSL Termination** | ⭐⭐⭐ Basic | ⭐⭐⭐⭐⭐ Advanced | ⭐⭐⭐⭐ Good | ✅ Depends |
| **Static Files** | ⭐⭐ Basic | ⭐⭐⭐⭐⭐ Optimized | ⭐⭐⭐⭐ Good | ✅ Depends |
| **Caching** | ❌ No | ✅ Advanced | ✅ Yes | ✅ Depends |
| **Zero Downtime** | ❌ No | ✅ Yes | ✅ Yes | ✅ Yes |
| **Rust Native** | ✅ Yes | ❌ No (C) | ✅ Yes | ✅ Yes |
| **Production Battle-Tested** | ✅ Yes | ⭐⭐⭐⭐⭐ Proven | ⭐⭐ Newer | ⭐⭐ Experimental |
| **Community Support** | ⭐⭐⭐⭐⭐ Large | ⭐⭐⭐⭐⭐ Huge | ⭐⭐⭐ Growing | ⭐⭐ Limited |

---

## Recommendations

### For Development

✅ **Use Hyper directly (current setup)**
- Fast iteration
- Simple debugging
- No extra dependencies

### For Production (Small Scale)

✅ **Hyper with systemd**
- Simple deployment
- Good performance
- No reverse proxy complexity

### For Production (Medium to Large Scale)

✅ **NGINX Reverse Proxy + Hyper**
- Battle-tested in production
- Advanced features (load balancing, caching, SSL)
- Industry standard
- Easy to find expertise

### For Rust-Only Stack

✅ **Ferron Reverse Proxy + Hyper**
- All-Rust stack
- Modern features
- Good performance
- Easier to customize

### For Maximum Flexibility

✅ **Implement Pluggable Backend Trait**
- Choose backend at runtime/compile-time
- Test different servers easily
- Custom implementations possible

---

## Implementation Roadmap

If we want to add pluggable server support:

### Phase 1: Define Server Trait
- [ ] Create `HttpServer` trait
- [ ] Refactor current code to use trait
- [ ] Add feature flags for backends

### Phase 2: Keep Hyper as Default
- [ ] Implement `HyperServer` backend
- [ ] Maintain current API compatibility
- [ ] Add benchmarks

### Phase 3: Add NGINX Backend (Optional)
- [ ] Implement FastCGI/SCGI protocol
- [ ] Create `NginxServer` backend
- [ ] Document integration

### Phase 4: Add Ferron Backend (Optional)
- [ ] Add Ferron as git submodule or dependency
- [ ] Create adapter layer
- [ ] Implement `FerronServer` backend

---

## Conclusion

**Current Recommendation:**

1. **Keep Hyper as default** for development and simple deployments
2. **Document NGINX reverse proxy setup** for production (add to docs)
3. **Consider Ferron** for users wanting all-Rust stack
4. **Implement pluggable backend trait** if there's strong demand

**Next Steps:**

1. Add NGINX configuration examples to documentation
2. Create deployment guides for various scenarios
3. Consider creating `armature-server-*` crates for alternative backends if needed

The **reverse proxy pattern with NGINX** is the industry-standard approach and provides the most production-ready features without requiring changes to Armature's core architecture.