oxidite 2.1.0

A modern, batteries-included web framework for Rust inspired by Laravel and Rails - Oxidite
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
# Oxidite Architecture Overview

This document provides a comprehensive overview of Oxidite's architecture, design principles, and internal workings.

---

## ๐ŸŽฏ Design Principles

### 1. **Performance First**
- Zero-cost abstractions leveraging Rust's type system
- Async I/O with Tokio for maximum throughput
- Efficient memory management without garbage collection

### 2. **Security by Default**
- Secure defaults for all configurations
- Memory safety guaranteed by Rust
- Protection against OWASP Top 10 vulnerabilities
- Constant-time cryptographic operations

### 3. **Developer Ergonomics**
- Type-safe APIs that prevent runtime errors
- Comprehensive error messages
- Automatic documentation generation
- Familiar patterns from popular frameworks

### 4. **Modularity**
- Composable crates that can be used independently
- Clean separation of concerns
- Plugin architecture for extensibility

---

## ๐Ÿ—๏ธ System Architecture

```mermaid
graph TD
    A[HTTP Request] --> B[oxidite-core]
    B --> C[Middleware Stack]
    C --> D[Router]
    D --> E[Handler]
    E --> F[oxidite-db]
    E --> G[oxidite-cache]
    E --> H[oxidite-queue]
    F --> I[SQL/NoSQL]
    G --> J[Redis/Memory]
    H --> K[Job Queue]
    E --> L[Response]
    L --> C
    C --> M[HTTP Response]
```

---

## ๐Ÿ“ฆ Crate Dependency Graph

```mermaid
graph LR
    CLI[oxidite-cli] --> Core[oxidite-core]
    CLI --> Router[oxidite-router]
    CLI --> DB[oxidite-db]
    CLI --> Migrate[oxidite-migrate]
    
    Router --> Core
    Middleware[oxidite-middleware] --> Core
    Auth[oxidite-auth] --> Core
    Auth --> DB
    DB --> Core
    Queue[oxidite-queue] --> Core
    Cache[oxidite-cache] --> Core
    Realtime[oxidite-realtime] --> Core

```

---

## ๐Ÿ”„ Request Lifecycle

### 1. **Connection Accepted**
```rust
TcpListener::bind(addr).await
    -> Accept connection
    -> Spawn task
```

### 2. **HTTP Parsing**
```rust
Hyper parses HTTP request
    -> Creates Request<Body>
    -> Passes to service
```

### 3. **Middleware Processing (Pre)**
```rust
ServiceBuilder::new()
    .layer(LoggerLayer)      // Log request
    .layer(CorsLayer)        // Check CORS
    .layer(AuthLayer)        // Authenticate
    .layer(RateLimitLayer)   // Rate limit
    .service(router)
```

### 4. **Routing**
```rust
Router matches path & method
    -> Extracts path params
    -> Extracts query params
    -> Extracts body
    -> Calls handler
```

### 5. **Handler Execution**
```rust
async fn handler(params: Path<UserId>) -> Result<Json<User>> {
    let user = User::find(params.id).await?;
    Ok(Json(user))
}
```

### 6. **Middleware Processing (Post)**
```rust
Response flows back through middleware
    -> Compression
    -> Security headers
    -> Logging
```

### 7. **Response Sent**
```rust
Hyper serializes response
    -> Sends over TCP
    -> Connection closed or kept alive
```

---

## ๐ŸŽจ Core Components

### oxidite-core (Implemented)

**Purpose**: HTTP server foundation, request/response handling, and routing.

**Key Types**:
- `Server<S>`: Generic HTTP server accepting any Tower service.
- `Router`: Main routing struct implementing `Service`.
- `OxiditeRequest`: Alias for `Request<Incoming>`.
- `OxiditeResponse`: Alias for `Response<BoxBody>`.
- `Path<T>`, `Query<T>`, `Json<T>`: Extractors for typed parameters and bodies.
- `Error`: Common error type.
- `Result<T>`: Common result type.

**Responsibilities**:
- TCP connection management and HTTP protocol handling (via Hyper).
- Service integration (via Tower).
- Path matching, HTTP method routing, and parameter extraction.
- Error propagation.

---

### oxidite-middleware (Implemented)

**Purpose**: Cross-cutting concerns via Tower layers

**Key Middleware**:
- `Logger`: Request/response logging
- `Cors`: CORS policy enforcement
- `Compression`: gzip/brotli response compression
- `RateLimit`: Token bucket rate limiting
- `Timeout`: Request timeout handling
- `SecurityHeaders`: CSP, HSTS, X-Frame-Options, etc.

**Architecture**:
```rust
impl<S> Service<Request> for Middleware<S> {
    type Response = Response;
    type Error = Error;
    type Future = Future;
    
    fn call(&mut self, req: Request) -> Self::Future {
        // Pre-processing
        let fut = self.inner.call(req);
        // Post-processing
    }
}
```

---

### oxidite-db (In Progress)

**Purpose**: Database abstraction and ORM

**Key Types**:
- `Connection`: Database connection trait
- `QueryBuilder`: Type-safe query construction
- `Model`: Trait for database models
- `Transaction`: Transaction handling

**Supported Databases**:
- PostgreSQL (via `tokio-postgres`)
- MySQL (via `mysql_async`)
- SQLite (via `rusqlite` + async wrapper)
- MongoDB (via `mongodb`)
- Redis (via `redis-rs`)

**Architecture**:
```rust
pub trait Database: Send + Sync {
    async fn execute(&self, query: &str) -> Result<u64>;
    async fn query<T>(&self, query: &str) -> Result<Vec<T>>;
}

pub trait Model: Sized {
    fn table_name() -> &'static str;
    async fn find(id: impl Into<Id>) -> Result<Self>;
    async fn create(self) -> Result<Self>;
    async fn update(&self) -> Result<()>;
    async fn delete(&self) -> Result<()>;
}
```

---

### oxidite-migrate (Planned)

**Purpose**: Database schema migrations

**Key Concepts**:
- **Up migrations**: Apply schema changes
- **Down migrations**: Rollback schema changes
- **Auto-diffing**: Generate migrations from model changes
- **History tracking**: Track applied migrations

**Migration Format**:
```rust
pub struct Migration {
    pub version: String,
    pub up: Box<dyn Fn(&Connection) -> BoxFuture<Result<()>>>,
    pub down: Box<dyn Fn(&Connection) -> BoxFuture<Result<()>>>,
}
```

---

### oxidite-auth (In Progress)

**Purpose**: Authentication and authorization

**Strategies**:
1. **Session**: Cookie-based sessions
2. **JWT**: Stateless token authentication
3. **Paseto**: Modern token alternative
4. **OAuth2**: Third-party authentication
5. **API Key**: Simple API authentication

**RBAC/PBAC**:
```rust
pub trait Authorizable {
    fn has_role(&self, role: &str) -> bool;
    fn can(&self, permission: &str) -> bool;
}

// Middleware usage
.layer(RequireAuth::new())
.layer(RequireRole::new("admin"))
.layer(RequirePermission::new("users:delete"))
```

---

### oxidite-queue (In Progress)

**Purpose**: Background job processing

**Architecture**:
```rust
pub trait Job: Serialize + DeserializeOwned + Send + Sync {
    async fn perform(&self) -> Result<()>;
    fn max_retries(&self) -> u32 { 3 }
    fn backoff(&self) -> Duration { Duration::from_secs(60) }
}

// Enqueue
SendEmailJob { to: "user@example.com" }
    .delay(Duration::from_secs(300))
    .enqueue()
    .await?;

// Worker
Queue::new()
    .worker_count(4)
    .start()
    .await;
```

**Backends**:
- In-memory (development)
- Redis (production)
- PostgreSQL (production)

---

### oxidite-cache (In Progress)

**Purpose**: Multi-layer caching

**Architecture**:
```rust
pub trait Cache: Send + Sync {
    async fn get<T>(&self, key: &str) -> Result<Option<T>>;
    async fn set<T>(&self, key: &str, value: &T, ttl: Duration) -> Result<()>;
    async fn delete(&self, key: &str) -> Result<()>;
    async fn flush(&self) -> Result<()>;
}

// Usage
cache.remember("user:123", Duration::from_secs(300), || async {
    User::find(123).await
}).await?;
```

---

### oxidite-realtime (In Progress)

**Purpose**: WebSockets and pub/sub

**Architecture**:
```rust
// WebSocket handler
router.ws("/ws", |socket: WebSocket| async move {
    socket.join("room:lobby").await;
    
    while let Some(msg) = socket.recv().await {
        socket.broadcast("room:lobby", msg).await;
    }
});

// Broadcasting
Broadcast::to_channel("notifications")
    .send(json!({ "type": "new_message" }))
    .await;
```

---

### oxidite-cli (In Progress)

**Purpose**: Command-line interface

**Commands**:
- `new`: Project scaffolding
- `dev`: Development server with hot reload
- `build`: Production build
- `migrate`: Database migrations
- `make:*`: Code generation
- `queue:work`: Start queue workers
- `test`: Run test suite

**Implementation**:
```rust
#[derive(Parser)]
enum Commands {
    New { name: String },
    Dev { port: u16 },
    Migrate,
    // ...
}
```

---

## ๐Ÿ” Security Architecture

### Memory Safety
- No buffer overflows (Rust prevents)
- No use-after-free (ownership system)
- No data races (borrow checker)

### Cryptography
- Argon2id for password hashing
- Constant-time comparisons
- Secure random number generation
- TLS 1.3 for transport security

### Input Validation
- Type-safe parameter extraction
- Automatic deserialization validation
- SQL injection prevention (prepared statements)
- XSS prevention (auto-escaping templates)

### CSRF Protection
- Token generation and validation
- SameSite cookie attribute
- Double-submit cookie pattern

### Rate Limiting
- Token bucket algorithm
- Per-IP and per-user limits
- Distributed via Redis

---

## โšก Performance Optimizations

### Async I/O
- Non-blocking I/O for all operations
- Efficient task scheduling with Tokio
- Connection pooling for databases

### Zero-Copy
- Body streaming without buffering
- Efficient serialization with serde

### Caching
- Response caching middleware
- Database query result caching
- Static file caching

### Connection Pooling
- Database connection pools (bb8/deadpool)
- Redis connection pools
- HTTP/2 connection reuse

---

## ๐Ÿงช Testing Strategy

### Unit Tests
- Test individual functions
- Mock external dependencies
- Fast execution

### Integration Tests
- Test full request/response cycle
- Use test database
- Reset state between tests

### Load Tests
- Benchmark throughput
- Identify bottlenecks
- Wrk/Bombardier integration

### Fuzz Testing
- Discover edge cases
- cargo-fuzz integration
- Continuous fuzzing

---

## ๐Ÿ“ˆ Monitoring & Observability

### Logging
- Structured JSON logging
- Log levels (trace, debug, info, warn, error)
- Request ID tracking

### Metrics
- Prometheus metrics
- Request duration histograms
- Database query metrics
- Queue depth metrics

### Tracing
- Distributed tracing with OpenTelemetry
- Span creation for each layer
- Trace context propagation

---

## ๐Ÿš€ Deployment Architecture

### Single Server
```
[Load Balancer]
      |
[Oxidite Server]
      |
   [Database]
```

### Horizontal Scaling
```
[Load Balancer]
      |
   [Oxidite Server 1] [Oxidite Server 2] [Oxidite Server N]
      |                     |                     |
      +---------------------+---------------------+
                            |
                    [Shared Database]
                    [Shared Redis]
```

### Microservices
```
[API Gateway]
      |
      +-- [Auth Service]
      +-- [User Service]
      +-- [Order Service]
      |
[Service Mesh]
      |
[Shared Infrastructure]
```

---

## ๐Ÿ”ฎ Future Directions

- GraphQL support
- gRPC native support
- Hot reloading in production
- Built-in service discovery
- Distributed tracing
- Machine learning integration
- Serverless deployment

---

This architecture is designed to be **fast**, **secure**, **scalable**, and **maintainable**. Every design decision prioritizes these goals while maintaining developer ergonomics.