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
//! Profiling Server Example
//!
//! This example runs an Armature server with CPU profiling enabled.
//! After running, it generates a flamegraph showing where CPU time is spent.
//!
//! **Note:** This example only works on Unix platforms (Linux, macOS).
//! On Windows, it will print an error message and exit.
//!
//! # Usage
//!
//! ```bash
//! # Run the profiling server
//! cargo run --example profiling_server --release
//!
//! # In another terminal, generate load:
//! wrk -t4 -c100 -d30s http://localhost:3000/tasks
//!
//! # Or use curl in a loop
//! for i in {1..1000}; do curl -s http://localhost:3000/tasks > /dev/null; done
//! ```
//!
//! After stopping the server (Ctrl+C), a flamegraph will be generated at
//! `flamegraph-profile.svg`

// Non-Unix platforms: print error and exit
#[cfg(not(unix))]
fn main() {
    eprintln!("Error: CPU profiling is only supported on Unix platforms (Linux, macOS).");
    eprintln!("The pprof crate requires Unix-specific APIs for CPU sampling.");
    eprintln!();
    eprintln!("To profile on Windows, consider using:");
    eprintln!("  - Windows Performance Analyzer (WPA)");
    eprintln!("  - Visual Studio Profiler");
    eprintln!("  - Intel VTune");
    std::process::exit(1);
}

// Unix platforms: full profiling support
#[cfg(unix)]
fn main() {
    unix_impl::run();
}

#[cfg(unix)]
mod unix_impl {
    #![allow(dead_code)]

    use std::net::TcpListener;

    /// Finds an available port on localhost.
    fn find_available_port() -> u16 {
        TcpListener::bind("127.0.0.1:0")
            .expect("Failed to bind to random port")
            .local_addr()
            .expect("Failed to get local address")
            .port()
    }

    use armature::prelude::*;
    use pprof::ProfilerGuardBuilder;
    use serde::{Deserialize, Serialize};
    use std::collections::hash_map::DefaultHasher;
    use std::fs::File;
    use std::hash::{Hash, Hasher};
    use std::sync::atomic::{AtomicU32, Ordering};
    use std::sync::{Arc, RwLock};
    use std::time::Instant;

    // ============================================================================
    // Models
    // ============================================================================

    #[derive(Clone, Serialize, Deserialize)]
    struct Task {
        id: u32,
        title: String,
        completed: bool,
        hash: Option<String>,
    }

    #[derive(Deserialize)]
    struct CreateTask {
        title: String,
        completed: Option<bool>,
    }

    // ============================================================================
    // Service with CPU-intensive operations for profiling
    // ============================================================================

    #[injectable]
    #[derive(Default, Clone)]
    struct TaskService {
        tasks: Arc<RwLock<Vec<Task>>>,
        counter: Arc<AtomicU32>,
    }

    impl TaskService {
        fn new() -> Self {
            Self {
                tasks: Arc::new(RwLock::new(vec![
                    Task {
                        id: 1,
                        title: "Learn Rust".to_string(),
                        completed: true,
                        hash: None,
                    },
                    Task {
                        id: 2,
                        title: "Build with Armature".to_string(),
                        completed: false,
                        hash: None,
                    },
                    Task {
                        id: 3,
                        title: "Profile the application".to_string(),
                        completed: false,
                        hash: None,
                    },
                ])),
                counter: Arc::new(AtomicU32::new(4)),
            }
        }

        fn get_all(&self) -> Vec<Task> {
            self.tasks.read().unwrap().clone()
        }

        fn get_by_id(&self, id: u32) -> Option<Task> {
            self.tasks
                .read()
                .unwrap()
                .iter()
                .find(|t| t.id == id)
                .cloned()
        }

        fn create(&self, title: String, completed: bool) -> Task {
            let id = self.counter.fetch_add(1, Ordering::SeqCst);
            let task = Task {
                id,
                title,
                completed,
                hash: Some(self.compute_hash(id)),
            };
            self.tasks.write().unwrap().push(task.clone());
            task
        }

        fn update(&self, id: u32, title: String, completed: bool) -> Option<Task> {
            let mut tasks = self.tasks.write().unwrap();
            if let Some(task) = tasks.iter_mut().find(|t| t.id == id) {
                task.title = title;
                task.completed = completed;
                task.hash = Some(self.compute_hash(id));
                Some(task.clone())
            } else {
                None
            }
        }

        fn delete(&self, id: u32) -> bool {
            let mut tasks = self.tasks.write().unwrap();
            if let Some(pos) = tasks.iter().position(|t| t.id == id) {
                tasks.remove(pos);
                true
            } else {
                false
            }
        }

        // CPU-intensive operation for profiling demonstration
        fn compute_hash(&self, seed: u32) -> String {
            let mut result = String::new();
            let data = format!("task-{}-data", seed);

            // Do some work to make this show up in the profiler
            for i in 0..50 {
                let mut hasher = DefaultHasher::new();
                data.hash(&mut hasher);
                (i as u64).hash(&mut hasher);
                result.push_str(&format!("{:x}", hasher.finish()));
            }

            result[..32].to_string()
        }

        // More CPU-intensive operation
        fn compute_heavy(&self, iterations: u32) -> String {
            let mut result: u64 = 0;
            for i in 0..iterations {
                let mut hasher = DefaultHasher::new();
                i.hash(&mut hasher);
                result ^= hasher.finish();
            }
            format!("{:016x}", result)
        }
    }

    // ============================================================================
    // Controller
    // ============================================================================

    #[controller("/tasks")]
    #[derive(Default, Clone)]
    struct TaskController;

    #[routes]
    impl TaskController {
        #[get("")]
        async fn list() -> Result<HttpResponse, Error> {
            let service = TaskService::new();
            HttpResponse::json(&service.get_all())
        }

        #[get("/:id")]
        async fn get(req: HttpRequest) -> Result<HttpResponse, Error> {
            let id_str = req
                .param("id")
                .ok_or_else(|| Error::Validation("Missing id".to_string()))?;
            let id: u32 = id_str
                .parse()
                .map_err(|_| Error::Validation("Invalid id".to_string()))?;

            let service = TaskService::new();
            let task = service
                .get_by_id(id)
                .ok_or_else(|| Error::RouteNotFound("Task not found".to_string()))?;

            HttpResponse::json(&task)
        }

        #[post("")]
        async fn create(req: HttpRequest) -> Result<HttpResponse, Error> {
            let input: CreateTask = req.json()?;
            let service = TaskService::new();
            let task = service.create(input.title, input.completed.unwrap_or(false));
            HttpResponse::json(&task)
        }

        #[put("/:id")]
        async fn update(req: HttpRequest) -> Result<HttpResponse, Error> {
            let id_str = req
                .param("id")
                .ok_or_else(|| Error::Validation("Missing id".to_string()))?;
            let id: u32 = id_str
                .parse()
                .map_err(|_| Error::Validation("Invalid id".to_string()))?;

            let input: CreateTask = req.json()?;
            let service = TaskService::new();
            let task = service
                .update(id, input.title, input.completed.unwrap_or(false))
                .ok_or_else(|| Error::RouteNotFound("Task not found".to_string()))?;

            HttpResponse::json(&task)
        }

        #[delete("/:id")]
        async fn delete(req: HttpRequest) -> Result<HttpResponse, Error> {
            let id_str = req
                .param("id")
                .ok_or_else(|| Error::Validation("Missing id".to_string()))?;
            let id: u32 = id_str
                .parse()
                .map_err(|_| Error::Validation("Invalid id".to_string()))?;

            let service = TaskService::new();
            if service.delete(id) {
                Ok(HttpResponse::no_content())
            } else {
                Err(Error::RouteNotFound("Task not found".to_string()))
            }
        }
    }

    // CPU-intensive endpoint for stress testing
    #[controller("/compute")]
    #[derive(Default, Clone)]
    struct ComputeController;

    #[routes]
    impl ComputeController {
        #[get("/light")]
        async fn light() -> Result<HttpResponse, Error> {
            let service = TaskService::new();
            let result = service.compute_hash(42);
            HttpResponse::json(&serde_json::json!({ "result": result }))
        }

        #[get("/heavy/:iterations")]
        async fn heavy(req: HttpRequest) -> Result<HttpResponse, Error> {
            let iterations_str = req
                .param("iterations")
                .ok_or_else(|| Error::Validation("Missing iterations".to_string()))?;
            let iterations: u32 = iterations_str
                .parse()
                .map_err(|_| Error::Validation("Invalid iterations".to_string()))?;

            let service = TaskService::new();
            let result = service.compute_heavy(iterations.min(100000)); // Cap at 100k
            HttpResponse::json(&serde_json::json!({
                "iterations": iterations,
                "result": result
            }))
        }

        #[get("/health")]
        async fn health() -> Result<HttpResponse, Error> {
            HttpResponse::json(&serde_json::json!({
                "status": "healthy"
            }))
        }
    }

    // ============================================================================
    // Module
    // ============================================================================

    #[module(
        providers: [TaskService],
        controllers: [TaskController, ComputeController]
    )]
    #[derive(Default)]
    struct AppModule;

    // ============================================================================
    // Main
    // ============================================================================

    #[tokio::main]
    pub async fn run() {
        let port = find_available_port();

        println!("🔬 Armature Profiling Server");
        println!("============================");
        println!();

        // Start CPU profiler
        println!("Starting CPU profiler (1000 Hz sampling)...");
        let guard = ProfilerGuardBuilder::default()
            .frequency(1000)
            .blocklist(&["libc", "libgcc", "pthread", "vdso"])
            .build()
            .expect("Failed to create profiler");

        println!("✅ Profiler started");
        println!();
        println!("📡 Server: http://localhost:{}", port);
        println!();
        println!("Endpoints:");
        println!("  GET  /tasks           - List all tasks");
        println!("  GET  /tasks/:id       - Get task by ID");
        println!("  POST /tasks           - Create task");
        println!("  GET  /compute/light   - Light CPU work");
        println!("  GET  /compute/heavy/N - Heavy CPU work (N iterations)");
        println!();
        println!("Generate load with:");
        println!("  curl http://localhost:{}/tasks", port);
        println!(
            "  for i in {{1..1000}}; do curl -s http://localhost:{}/compute/light > /dev/null; done",
            port
        );
        println!();
        println!("Press Ctrl+C to stop and generate flamegraph...");
        println!();

        let start_time = Instant::now();

        // Set up Ctrl+C handler
        let guard_ref = std::sync::Arc::new(std::sync::Mutex::new(Some(guard)));
        let guard_clone = guard_ref.clone();

        ctrlc::set_handler(move || {
            println!();
            println!("🛑 Stopping server...");

            let elapsed = start_time.elapsed();
            println!("⏱️  Server ran for {:.2}s", elapsed.as_secs_f64());

            // Generate flamegraph
            if let Some(guard) = guard_clone.lock().unwrap().take() {
                println!();
                println!("📊 Generating flamegraph...");

                match guard.report().build() {
                    Ok(report) => {
                        // Save SVG flamegraph
                        match File::create("flamegraph-profile.svg") {
                            Ok(file) => {
                                if report.flamegraph(file).is_ok() {
                                    println!("✅ Flamegraph saved: flamegraph-profile.svg");
                                    println!();
                                    println!(
                                        "Open the SVG file in a browser to explore the flamegraph."
                                    );
                                    println!("Wider bars = more CPU time spent in that function.");
                                }
                            }
                            Err(e) => println!("❌ Failed to create file: {}", e),
                        }
                    }
                    Err(e) => println!("❌ Failed to generate report: {}", e),
                }
            }

            println!();
            println!("🎉 Done!");
            std::process::exit(0);
        })
        .expect("Failed to set Ctrl+C handler");

        // Start the server
        let app = Application::create::<AppModule>().await;
        app.listen(port).await.unwrap();
    }
}