quantum-pulse 0.1.13

A lightweight, customizable profiling library for Rust with support for custom categories and percentile statistics
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
//! Example demonstrating custom categories with enum operations using Operation trait

use quantum_pulse::{profile, profile_async, Category, Operation, ProfileCollector};
use std::thread;
use std::time::Duration;
use tokio::time::sleep;

/// Web application operations that implement Operation trait
#[derive(Debug)]
enum WebAppOperation {
    // Authentication operations
    CheckAuthToken,
    ValidatePermissions,

    // Database operations
    FetchUserData,
    UpdateUserProfile,
    VacuumDatabase,

    // Cache operations
    CheckCache,
    UpdateCache,
    WarmCache,

    // Business logic operations
    CalculateRecommendations,
    ProcessPayment,

    // External API operations
    PaymentGatewayApi,
    SyncWithCrm,
    SendNotification,

    // Serialization operations
    SerializeResponse,
    ParseRequest,

    // File I/O operations
    WriteAccessLog,
    ProcessUploadedFile,
    BackupData,
}

/// Database category for all database operations
#[derive(Debug)]
struct DatabaseCategory;

impl Category for DatabaseCategory {
    fn get_name(&self) -> &str {
        "Database"
    }

    fn get_description(&self) -> &str {
        "All database queries, transactions, and maintenance operations"
    }

    fn color_hint(&self) -> Option<&str> {
        Some("#FF6B6B")
    }

    fn priority(&self) -> i32 {
        1
    }
}

/// External API category for third-party service calls
#[derive(Debug)]
struct ExternalApiCategory;

impl Category for ExternalApiCategory {
    fn get_name(&self) -> &str {
        "ExternalAPI"
    }

    fn get_description(&self) -> &str {
        "Calls to third-party services and external APIs"
    }

    fn color_hint(&self) -> Option<&str> {
        Some("#4ECDC4")
    }

    fn priority(&self) -> i32 {
        2
    }
}

/// Cache category for caching operations
#[derive(Debug)]
struct CacheCategory;

impl Category for CacheCategory {
    fn get_name(&self) -> &str {
        "Cache"
    }

    fn get_description(&self) -> &str {
        "Redis, Memcached, and other caching operations"
    }

    fn color_hint(&self) -> Option<&str> {
        Some("#45B7D1")
    }

    fn priority(&self) -> i32 {
        3
    }
}

/// Business logic category for core application logic
#[derive(Debug)]
struct BusinessLogicCategory;

impl Category for BusinessLogicCategory {
    fn get_name(&self) -> &str {
        "BusinessLogic"
    }

    fn get_description(&self) -> &str {
        "Core application business logic and computations"
    }

    fn color_hint(&self) -> Option<&str> {
        Some("#96CEB4")
    }

    fn priority(&self) -> i32 {
        4
    }
}

/// Authentication category for auth operations
#[derive(Debug)]
struct AuthCategory;

impl Category for AuthCategory {
    fn get_name(&self) -> &str {
        "Authentication"
    }

    fn get_description(&self) -> &str {
        "Authentication, authorization, and security operations"
    }

    fn color_hint(&self) -> Option<&str> {
        Some("#DDA0DD")
    }

    fn priority(&self) -> i32 {
        5
    }
}

/// Serialization category for data transformation
#[derive(Debug)]
struct SerializationCategory;

impl Category for SerializationCategory {
    fn get_name(&self) -> &str {
        "Serialization"
    }

    fn get_description(&self) -> &str {
        "JSON, XML parsing and data serialization operations"
    }

    fn color_hint(&self) -> Option<&str> {
        Some("#FFEAA7")
    }

    fn priority(&self) -> i32 {
        6
    }
}

/// File I/O category for file operations
#[derive(Debug)]
struct FileIOCategory;

impl Category for FileIOCategory {
    fn get_name(&self) -> &str {
        "FileIO"
    }

    fn get_description(&self) -> &str {
        "File system read/write operations and logging"
    }

    fn color_hint(&self) -> Option<&str> {
        Some("#F4A460")
    }

    fn priority(&self) -> i32 {
        7
    }
}

impl Operation for WebAppOperation {
    fn get_category(&self) -> &dyn Category {
        match self {
            WebAppOperation::FetchUserData
            | WebAppOperation::UpdateUserProfile
            | WebAppOperation::VacuumDatabase => &DatabaseCategory,

            WebAppOperation::PaymentGatewayApi
            | WebAppOperation::SyncWithCrm
            | WebAppOperation::SendNotification => &ExternalApiCategory,

            WebAppOperation::CheckCache
            | WebAppOperation::UpdateCache
            | WebAppOperation::WarmCache => &CacheCategory,

            WebAppOperation::CalculateRecommendations | WebAppOperation::ProcessPayment => {
                &BusinessLogicCategory
            }

            WebAppOperation::CheckAuthToken | WebAppOperation::ValidatePermissions => &AuthCategory,

            WebAppOperation::SerializeResponse | WebAppOperation::ParseRequest => {
                &SerializationCategory
            }

            WebAppOperation::WriteAccessLog
            | WebAppOperation::ProcessUploadedFile
            | WebAppOperation::BackupData => &FileIOCategory,
        }
    }

    fn to_str(&self) -> String {
        match self {
            WebAppOperation::CheckAuthToken => "check_auth_token".to_string(),
            WebAppOperation::ValidatePermissions => "validate_permissions".to_string(),
            WebAppOperation::FetchUserData => "fetch_user_data".to_string(),
            WebAppOperation::UpdateUserProfile => "update_user_profile".to_string(),
            WebAppOperation::VacuumDatabase => "vacuum_database".to_string(),
            WebAppOperation::CheckCache => "check_cache".to_string(),
            WebAppOperation::UpdateCache => "update_cache".to_string(),
            WebAppOperation::WarmCache => "warm_cache".to_string(),
            WebAppOperation::CalculateRecommendations => "calculate_recommendations".to_string(),
            WebAppOperation::ProcessPayment => "process_payment".to_string(),
            WebAppOperation::PaymentGatewayApi => "payment_gateway_api".to_string(),
            WebAppOperation::SyncWithCrm => "sync_with_crm".to_string(),
            WebAppOperation::SendNotification => "send_notification".to_string(),
            WebAppOperation::SerializeResponse => "serialize_response".to_string(),
            WebAppOperation::ParseRequest => "parse_request".to_string(),
            WebAppOperation::WriteAccessLog => "write_access_log".to_string(),
            WebAppOperation::ProcessUploadedFile => "process_uploaded_file".to_string(),
            WebAppOperation::BackupData => "backup_data".to_string(),
        }
    }
}

#[tokio::main]
async fn main() {
    println!("=== Custom Categories Example - Web Application ===\n");

    // Clear any existing data
    ProfileCollector::clear_all();

    // Simulate various web application operations
    simulate_web_requests().await;

    // Use UpdateUserProfile to avoid unused warning
    if false {
        profile!(WebAppOperation::UpdateUserProfile, {
            println!("Updating user profile");
        });
    }

    // Generate and display categorized report
    show_profiling_results();
}

async fn simulate_web_requests() {
    println!("Simulating web application operations...\n");

    // Simulate multiple user requests
    for request_id in 1..=3 {
        println!("Processing request #{}...", request_id);
        handle_user_request(request_id).await;
    }

    // Simulate background jobs
    println!("\nRunning background jobs...");
    run_background_jobs().await;
}

async fn handle_user_request(request_id: u32) {
    // Authentication
    let auth_op = WebAppOperation::CheckAuthToken;
    profile!(auth_op, {
        simulate_work(5 + (request_id % 3) as u64);
    });

    // Validate permissions
    let perm_op = WebAppOperation::ValidatePermissions;
    profile!(perm_op, {
        simulate_work(3);
    });

    // Parse incoming request
    let parse_op = WebAppOperation::ParseRequest;
    profile!(parse_op, {
        simulate_work(2);
    });

    // Database query for user data
    let fetch_op = WebAppOperation::FetchUserData;
    let _user_data = profile!(fetch_op, {
        simulate_work(20 + (request_id * 2) as u64);
        format!("User_{}", request_id)
    });

    // Check cache for computed results
    let cache_check_op = WebAppOperation::CheckCache;
    let cached = profile!(cache_check_op, {
        simulate_work(2);
        request_id % 3 == 0 // Some requests hit cache
    });

    if !cached {
        // Business logic processing
        let rec_op = WebAppOperation::CalculateRecommendations;
        profile!(rec_op, {
            simulate_work(50 + (request_id * 5) as u64);
        });

        // Store in cache
        let cache_update_op = WebAppOperation::UpdateCache;
        profile!(cache_update_op, {
            simulate_work(3);
        });
    }

    // External API call (e.g., payment processing)
    if request_id % 2 == 0 {
        let payment_op = WebAppOperation::PaymentGatewayApi;
        profile_async!(payment_op, async {
            sleep(Duration::from_millis(80 + (request_id * 10) as u64)).await;
        })
        .await;
    }

    // Process payment (business logic)
    if request_id == 2 {
        let process_payment_op = WebAppOperation::ProcessPayment;
        profile!(process_payment_op, {
            simulate_work(30);
        });
    }

    // Serialize response
    let serialize_op = WebAppOperation::SerializeResponse;
    profile!(serialize_op, {
        simulate_work(8);
    });

    // Log to file
    let log_op = WebAppOperation::WriteAccessLog;
    profile!(log_op, {
        simulate_work(5);
    });
}

async fn run_background_jobs() {
    // Database maintenance
    let vacuum_op = WebAppOperation::VacuumDatabase;
    profile!(vacuum_op, {
        simulate_work(200);
        println!("  - Database maintenance completed");
    });

    // Cache warming
    let warm_op = WebAppOperation::WarmCache;
    profile_async!(warm_op, async {
        sleep(Duration::from_millis(50)).await;
        println!("  - Cache warmed");
    })
    .await;

    // File processing
    for i in 1..=2 {
        let file_op = WebAppOperation::ProcessUploadedFile;
        profile!(file_op, {
            simulate_work(30);
            println!("  - Processed uploaded file #{}", i);
        });
    }

    // External API sync
    let sync_op = WebAppOperation::SyncWithCrm;
    profile_async!(sync_op, async {
        sleep(Duration::from_millis(120)).await;
        println!("  - CRM sync completed");
    })
    .await;

    // Send notifications
    let notify_op = WebAppOperation::SendNotification;
    profile_async!(notify_op, async {
        sleep(Duration::from_millis(15)).await;
        println!("  - Notifications sent");
    })
    .await;

    // Backup data
    let backup_op = WebAppOperation::BackupData;
    profile!(backup_op, {
        simulate_work(100);
        println!("  - Data backup completed");
    });
}

fn show_profiling_results() {
    println!("\n{}", "=".repeat(70));
    println!("PROFILING RESULTS BY CATEGORY");
    println!("{}", "=".repeat(70));

    ProfileCollector::report_stats();

    let summary = ProfileCollector::get_summary();
    println!("\nSUMMARY:");
    println!("- Total operations: {}", summary.total_operations);
    println!("- Unique operations: {}", summary.unique_operations);
    println!("- Total time: {}μs", summary.total_time_micros);

    println!("\n{}", "=".repeat(70));
    println!("DETAILED ANALYSIS BY CATEGORY");
    println!("{}", "=".repeat(70));

    let all_stats = ProfileCollector::get_all_stats();

    // Group operations by category
    let mut categories: std::collections::HashMap<
        String,
        Vec<(String, quantum_pulse::OperationStats)>,
    > = std::collections::HashMap::new();

    for (key, stats) in all_stats {
        if let Some((category, operation)) = key.split_once("::") {
            categories
                .entry(category.to_string())
                .or_insert_with(Vec::new)
                .push((operation.to_string(), stats));
        }
    }

    // Display results grouped by category
    let category_order = vec![
        "Authentication",
        "Database",
        "Cache",
        "BusinessLogic",
        "ExternalAPI",
        "Serialization",
        "FileIO",
    ];

    for category_name in category_order {
        if let Some(ops) = categories.get(category_name) {
            println!("\n📂 {} Category:", category_name);
            let mut total_calls = 0;
            let mut total_time = Duration::ZERO;

            for (op_name, stats) in ops {
                println!(
                    "   {} - {} calls, avg: {:?}",
                    op_name,
                    stats.count,
                    stats.mean()
                );
                total_calls += stats.count;
                total_time += stats.total;
            }

            println!(
                "   📊 Category Total: {} calls, {:?} total time",
                total_calls, total_time
            );
        }
    }

    println!("\n{}", "=".repeat(70));
    println!("TOP OPERATIONS");
    println!("{}", "=".repeat(70));

    let all_stats = ProfileCollector::get_all_stats();

    // Top by total time
    let mut sorted_by_total: Vec<_> = all_stats.iter().collect();
    sorted_by_total.sort_by(|a, b| b.1.total.cmp(&a.1.total));

    println!("\n⏱️  Most Time Consuming (Top 5):");
    for (i, (name, stats)) in sorted_by_total.iter().take(5).enumerate() {
        println!(
            "  {}. {} - {:?} total ({} calls)",
            i + 1,
            name,
            stats.total,
            stats.count
        );
    }

    // Top by call count
    let mut sorted_by_count: Vec<_> = all_stats.iter().collect();
    sorted_by_count.sort_by(|a, b| b.1.count.cmp(&a.1.count));

    println!("\n📈 Most Frequently Called (Top 5):");
    for (i, (name, stats)) in sorted_by_count.iter().take(5).enumerate() {
        println!(
            "  {}. {} - {} calls (avg: {:?})",
            i + 1,
            name,
            stats.count,
            stats.mean()
        );
    }

    // Top by average time
    let mut sorted_by_avg: Vec<_> = all_stats.iter().collect();
    sorted_by_avg.sort_by(|a, b| b.1.mean().cmp(&a.1.mean()));

    println!("\n⚡ Highest Average Latency (Top 5):");
    for (i, (name, stats)) in sorted_by_avg.iter().take(5).enumerate() {
        println!(
            "  {}. {} - avg: {:?} ({} calls)",
            i + 1,
            name,
            stats.mean(),
            stats.count
        );
    }
}

fn simulate_work(millis: u64) {
    thread::sleep(Duration::from_millis(millis));
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_web_app_operation_categories() {
        let db_op = WebAppOperation::FetchUserData;
        assert_eq!(db_op.get_category().get_name(), "Database");
        assert_eq!(db_op.to_str(), "fetch_user_data");

        let api_op = WebAppOperation::PaymentGatewayApi;
        assert_eq!(api_op.get_category().get_name(), "ExternalAPI");
        assert_eq!(api_op.to_str(), "payment_gateway_api");

        let auth_op = WebAppOperation::CheckAuthToken;
        assert_eq!(auth_op.get_category().get_name(), "Authentication");
        assert_eq!(auth_op.to_str(), "check_auth_token");
    }

    #[test]
    fn test_category_properties() {
        let db_cat = DatabaseCategory;
        assert_eq!(db_cat.get_name(), "Database");
        assert_eq!(db_cat.priority(), 1);
        assert!(db_cat.color_hint().is_some());

        let ext_cat = ExternalApiCategory;
        assert_eq!(ext_cat.get_name(), "ExternalAPI");
        assert_eq!(ext_cat.priority(), 2);
    }

    #[test]
    fn test_profiling_with_categories() {
        ProfileCollector::clear_all();

        let op = WebAppOperation::FetchUserData;
        profile!(op, {
            std::thread::sleep(Duration::from_millis(1));
        });

        assert!(ProfileCollector::has_data());
        let stats = ProfileCollector::get_stats("Database::fetch_user_data");
        assert!(stats.is_some());
        assert_eq!(stats.unwrap().count, 1);
    }

    #[tokio::test]
    async fn test_async_profiling_with_categories() {
        ProfileCollector::clear_all();

        let op = WebAppOperation::PaymentGatewayApi;
        profile_async!(op, async {
            sleep(Duration::from_millis(1)).await;
        })
        .await;

        assert!(ProfileCollector::has_data());
        let stats = ProfileCollector::get_stats("ExternalAPI::payment_gateway_api");
        assert!(stats.is_some());
        assert_eq!(stats.unwrap().count, 1);
    }
}