async-inspect 0.2.0

X-ray vision for async Rust - inspect and debug async state machines
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
//! async-inspect CLI
//!
//! Command-line interface for inspecting and monitoring async Rust applications.

use async_inspect::config::Config;
use async_inspect::export::{CsvExporter, JsonExporter};
use async_inspect::inspector::Inspector;
use async_inspect::reporter::Reporter;
use async_inspect::telemetry;
use clap::{Parser, Subcommand};
use colored::Colorize;
use std::path::PathBuf;
use std::time::Instant;

#[cfg(feature = "cli")]
use async_inspect::tui::run_tui;

/// async-inspect - X-ray vision for async Rust
#[derive(Parser, Debug)]
#[command(name = "async-inspect")]
#[command(author, version)]
#[command(about = "[async-inspect] X-ray vision for async Rust")]
#[command(long_about = None)]
#[command(arg_required_else_help = true)]
#[command(
    after_help = "[INFO] For detailed information, run: async-inspect info\n[TIP] Quick start guide, examples, and documentation available with 'info' command"
)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    /// Enable verbose output
    #[arg(short, long, global = true)]
    verbose: bool,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Launch interactive TUI monitor
    #[cfg(feature = "cli")]
    Monitor {
        /// Update interval in milliseconds
        #[arg(short, long, default_value = "100")]
        interval: u64,
    },

    /// Export task data to various formats
    Export {
        /// Output format
        #[arg(short, long, value_enum)]
        format: ExportFormat,

        /// Output file path
        #[arg(short, long)]
        output: PathBuf,

        /// Export events separately (CSV only)
        #[arg(long)]
        with_events: bool,
    },

    /// Show current statistics
    Stats {
        /// Show detailed performance metrics
        #[arg(short, long)]
        detailed: bool,
    },

    /// Configure production settings
    Config {
        /// Configuration mode
        #[arg(value_enum)]
        mode: ConfigMode,

        /// Custom sampling rate (1 in N tasks)
        #[arg(short, long)]
        sampling_rate: Option<usize>,

        /// Maximum events to retain
        #[arg(short = 'e', long)]
        max_events: Option<usize>,

        /// Maximum tasks to track
        #[arg(short = 't', long)]
        max_tasks: Option<usize>,
    },

    /// Show configuration and overhead information
    Info,

    /// Show version information
    Version,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum ExportFormat {
    /// Export as JSON
    Json,
    /// Export as CSV
    Csv,
}

#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum ConfigMode {
    /// Production mode (1% sampling, minimal tracking)
    Production,
    /// Development mode (full tracking)
    Development,
    /// Debug mode (unlimited tracking)
    Debug,
    /// Custom configuration
    Custom,
}

fn main() -> anyhow::Result<()> {
    // Initialize telemetry early
    telemetry::init();

    let start_time = Instant::now();
    let cli = Cli::parse();

    if cli.verbose {
        println!(
            "{} - Verbose mode enabled\n",
            "[async-inspect]".on_purple().white().bold()
        );
    }

    let command = match cli.command {
        Some(cmd) => cmd,
        None => {
            // This shouldn't happen due to arg_required_else_help, but handle it anyway
            eprintln!("No command specified. Use --help to see available commands.");
            std::process::exit(1);
        }
    };

    // Get command name for telemetry
    let command_name = match &command {
        #[cfg(feature = "cli")]
        Commands::Monitor { .. } => "monitor",
        Commands::Export { .. } => "export",
        Commands::Stats { .. } => "stats",
        Commands::Config { .. } => "config",
        Commands::Info => "info",
        Commands::Version => "version",
    };

    let result = match command {
        #[cfg(feature = "cli")]
        Commands::Monitor { interval } => {
            println!("╔════════════════════════════════════════════════════════════╗");
            println!(
                "{} - TUI Monitor                               ║",
                "[async-inspect]".on_purple().white().bold()
            );
            println!("╚════════════════════════════════════════════════════════════╝\n");
            println!("[>] Launching TUI (update interval: {}ms)...\n", interval);

            let inspector = Inspector::global().clone();

            // Note: The TUI will display any tasks that get registered.
            // In a library context, tasks are tracked when using #[async_inspect::trace]
            // or spawn_tracked() in your application code.

            run_tui(inspector)?;

            println!("\n[OK] Monitor closed.");
            Ok(())
        }

        Commands::Export {
            format,
            output,
            with_events,
        } => {
            let inspector = Inspector::global();
            let stats = inspector.stats();

            if stats.total_tasks == 0 {
                println!("[WARN] No tasks tracked yet. Use #[async_inspect::trace] in your code.");
                return Ok(());
            }

            println!(
                "{} Exporting {} tasks and {} events...",
                "[*]".on_yellow().white().bold(),
                stats.total_tasks,
                stats.total_events
            );

            match format {
                ExportFormat::Json => {
                    JsonExporter::export_to_file(inspector, &output)?;
                    println!("[OK] Exported to JSON: {}", output.display());
                }
                ExportFormat::Csv => {
                    CsvExporter::export_tasks_to_file(inspector, &output)?;
                    println!("[OK] Exported tasks to CSV: {}", output.display());

                    if with_events {
                        let mut events_path = output.clone();
                        events_path.set_file_name(format!(
                            "{}_events.csv",
                            output.file_stem().unwrap().to_string_lossy()
                        ));
                        CsvExporter::export_events_to_file(inspector, &events_path)?;
                        println!("[OK] Exported events to CSV: {}", events_path.display());
                    }
                }
            }

            Ok(())
        }

        Commands::Stats { detailed } => {
            let inspector = Inspector::global();
            let reporter = Reporter::global();
            let stats = inspector.stats();

            if stats.total_tasks == 0 {
                println!("[WARN] No tasks tracked yet. Use #[async_inspect::trace] in your code.");
                return Ok(());
            }

            println!("╔════════════════════════════════════════════════════════════╗");
            println!(
                "{} - Statistics                                ║",
                "[async-inspect]".on_purple().white().bold()
            );
            println!("╚════════════════════════════════════════════════════════════╝\n");

            reporter.print_summary();

            if detailed {
                println!("\n[STATS] Performance Metrics\n");
                let profiler = inspector.build_profiler();
                let perf_reporter = async_inspect::profile::PerformanceReporter::new(&profiler);
                perf_reporter.print_report();
            }

            Ok(())
        }

        Commands::Config {
            mode,
            sampling_rate,
            max_events,
            max_tasks,
        } => {
            let config = Config::global();

            println!(
                "{} {}\n",
                "[CONFIG]".on_cyan().white().bold(),
                "Configuring [async-inspect]...".bright_white()
            );

            match mode {
                ConfigMode::Production => {
                    config.production_mode();
                    println!("[OK] Applied production mode:");
                    println!("   • 1% sampling (1 in 100 tasks)");
                    println!("   • 1,000 event limit");
                    println!("   • 500 task limit");
                    println!("   • Await tracking disabled");
                    println!("   • HTML reports disabled");
                }
                ConfigMode::Development => {
                    config.development_mode();
                    println!("[OK] Applied development mode:");
                    println!("   • Full sampling (all tasks)");
                    println!("   • 10,000 event limit");
                    println!("   • 1,000 task limit");
                    println!("   • Await tracking enabled");
                    println!("   • HTML reports enabled");
                }
                ConfigMode::Debug => {
                    config.debug_mode();
                    println!("[OK] Applied debug mode:");
                    println!("   • Full sampling (all tasks)");
                    println!("   • Unlimited events");
                    println!("   • Unlimited tasks");
                    println!("   • Await tracking enabled");
                    println!("   • HTML reports enabled");
                }
                ConfigMode::Custom => {
                    if let Some(rate) = sampling_rate {
                        config.set_sampling_rate(rate);
                        println!("[OK] Set sampling rate: 1 in {}", rate);
                    }
                    if let Some(events) = max_events {
                        config.set_max_events(events);
                        println!("[OK] Set max events: {}", events);
                    }
                    if let Some(tasks) = max_tasks {
                        config.set_max_tasks(tasks);
                        println!("[OK] Set max tasks: {}", tasks);
                    }
                    println!("\n[OK] Applied custom configuration");
                }
            }

            println!("\n[CONFIG] Current Configuration:");
            print_config(config);

            Ok(())
        }

        Commands::Info => {
            let config = Config::global();
            let inspector = Inspector::global();
            let stats = inspector.stats();

            println!("╔════════════════════════════════════════════════════════════╗");
            println!(
                "{} - Information                               ║",
                "[async-inspect]".on_purple().white().bold()
            );
            println!("╚════════════════════════════════════════════════════════════╝\n");

            println!(
                "{} Version: {}",
                "[*]".on_yellow().white().bold(),
                env!("CARGO_PKG_VERSION")
            );
            println!(
                "{} Description: {}\n",
                "[*]".on_yellow().white().bold(),
                env!("CARGO_PKG_DESCRIPTION")
            );

            println!("[CONFIG] Configuration:");
            print_config(config);

            println!("\n[STATS] Current State:");
            println!("  Total tasks:     {}", stats.total_tasks);
            println!("  Running tasks:   {}", stats.running_tasks);
            println!("  Completed tasks: {}", stats.completed_tasks);
            println!("  Failed tasks:    {}", stats.failed_tasks);
            println!("  Total events:    {}", stats.total_events);
            println!(
                "  Duration:        {:.2}s",
                stats.timeline_duration.as_secs_f64()
            );

            let overhead = config.overhead_stats();
            if overhead.calls > 0 {
                println!("\n[PERF] Overhead Statistics:");
                println!("  Total overhead:        {:.2}ms", overhead.total_ms());
                println!("  Instrumentation calls: {}", overhead.calls);
                println!("  Average per call:      {:.2}µs", overhead.avg_us());
            }

            println!("\n[INFO] Features:");
            println!("  • Task tracking and inspection");
            println!("  • Automatic instrumentation (#[async_inspect::trace])");
            println!("  • Deadlock detection");
            println!("  • Performance profiling");
            #[cfg(feature = "cli")]
            println!("  • Real-time TUI monitoring");
            println!("  • JSON/CSV export");
            println!("  • Production-ready configuration");

            println!("\n{}", "[*] Links:".on_yellow().white().bold());
            println!(
                "  {} {}",
                "Homepage:     ".bright_white(),
                env!("CARGO_PKG_HOMEPAGE").bright_blue()
            );
            println!(
                "  {} {}",
                "Repository:   ".bright_white(),
                env!("CARGO_PKG_REPOSITORY").bright_blue()
            );
            println!(
                "  {} {}",
                "Documentation:".bright_white(),
                "https://docs.rs/async-inspect".bright_blue()
            );

            println!("\n{}", "[*] Quick Start:".on_yellow().white().bold());
            println!("  1. Add to your Cargo.toml:");
            println!("     async-inspect = \"{}\"", env!("CARGO_PKG_VERSION"));
            println!("\n  2. Annotate async functions:");
            println!("     #[async_inspect::trace]");
            println!("     async fn my_function() {{ ... }}");
            println!("\n  3. Launch TUI monitor:");
            println!("     async-inspect monitor");
            println!("\n  4. Export data:");
            println!("     async-inspect export -f json -o trace.json");

            Ok(())
        }

        Commands::Version => {
            println!(
                "{} {}",
                "[async-inspect]".on_purple().white().bold(),
                env!("CARGO_PKG_VERSION")
            );
            println!("X-ray vision for async Rust\n");

            println!("Features enabled:");
            #[cfg(feature = "cli")]
            println!("  • cli (TUI support)");
            #[cfg(feature = "tokio")]
            println!("  • tokio");
            #[cfg(feature = "telemetry")]
            println!("  • telemetry (usage analytics)");

            println!("\nAuthors: {}", env!("CARGO_PKG_AUTHORS"));
            println!("License: {}", env!("CARGO_PKG_LICENSE"));

            Ok(())
        }
    };

    // Track command execution
    let duration_ms = start_time.elapsed().as_millis() as u64;
    let success = result.is_ok();
    telemetry::track_command_sync(command_name, success, Some(duration_ms));

    result
}

fn print_config(config: &Config) {
    println!("  Sampling rate:   1 in {}", config.sampling_rate());
    println!(
        "  Max events:      {}",
        if config.max_events() == 0 {
            "unlimited".to_string()
        } else {
            config.max_events().to_string()
        }
    );
    println!(
        "  Max tasks:       {}",
        if config.max_tasks() == 0 {
            "unlimited".to_string()
        } else {
            config.max_tasks().to_string()
        }
    );
    println!("  Track awaits:    {}", config.track_awaits());
    println!("  Track polls:     {}", config.track_polls());
    println!("  Enable HTML:     {}", config.enable_html());
}