netrunner_cli 2.0.4

A feature-rich Rust-based CLI to test and analyze your internet connection
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
//! Bridges [`netrunner_core`] progress events to the cyberpunk terminal UI.
//!
//! The core engine is UI-agnostic: it streams [`TestEvent`]s over a channel.
//! This module runs a speed test and renders those events exactly the way the
//! standalone CLI always has β€” status lines, section headers, the live
//! download/upload bandwidth graph and the final results table.

use colored::*;
use netrunner_core::{
    ConnectionQuality, NetworkDiagnostics, NetworkDiagnosticsTool, Phase, SpeedTest,
    SpeedTestResult, TestConfig, TestEvent,
};
use tokio::sync::mpsc;

use crate::ui::{BandwidthMonitor, UI};

/// Run a full speed test and render its progress to the terminal.
///
/// Returns the final [`SpeedTestResult`]. This reproduces the classic cyberpunk
/// output, including the live bandwidth graphs, by consuming the core engine's
/// [`TestEvent`] stream.
pub async fn run_speed_test_tui(
    config: TestConfig,
) -> Result<SpeedTestResult, Box<dyn std::error::Error>> {
    let ui = UI::new(config.clone());
    let (tx, mut rx) = mpsc::unbounded_channel::<TestEvent>();

    // Live bandwidth graph state for the current transfer phase.
    let mut monitor: Option<BandwidthMonitor> = None;
    let mut first_render = true;

    // Drive the engine and render its events on the same task (the core error
    // type is not `Send`, so we can't move the future to another thread).
    let test = SpeedTest::with_events(config.clone(), Some(tx))?;
    let engine = test.run_full_test();
    tokio::pin!(engine);
    let mut result: Option<SpeedTestResult> = None;

    loop {
        tokio::select! {
            biased;
            maybe_event = rx.recv() => {
                match maybe_event {
                    Some(event) => {
                        render_speed_event(&ui, event, &mut monitor, &mut first_render).await;
                    }
                    None => break,
                }
            }
            res = &mut engine => {
                result = Some(res?);
                break;
            }
        }
    }

    // Drain any events buffered after the engine finished.
    while let Ok(event) = rx.try_recv() {
        render_speed_event(&ui, event, &mut monitor, &mut first_render).await;
    }

    result.ok_or_else(|| "speed test did not complete".into())
}

/// Render a single speed-test event to the terminal.
async fn render_speed_event(
    ui: &UI,
    event: TestEvent,
    monitor: &mut Option<BandwidthMonitor>,
    first_render: &mut bool,
) {
    match event {
        TestEvent::Status(msg) => {
            println!("{} {}", "Β»".bright_cyan(), msg.bright_cyan());
        }
        TestEvent::LocationDetected {
            city,
            country,
            isp,
            source,
        } => {
            println!(
                "{} {}, {} (via {})",
                "πŸ“ Location:".bright_green(),
                city,
                country,
                source
            );
            if let Some(isp) = isp {
                println!("{} {}", "πŸ”Œ ISP:".bright_blue(), isp);
            }
        }
        TestEvent::ServerPoolBuilt { count } => {
            println!("{} {} servers in pool", "βœ“".bright_green(), count);
        }
        TestEvent::NearbyServersFound { count } => {
            println!("{} {} nearby servers", "βœ“ Found".bright_green(), count);
        }
        TestEvent::ServersSelected { servers } => {
            println!(
                "{} {} servers selected for testing",
                "βœ“".bright_green(),
                servers.len()
            );
            for (i, s) in servers.iter().enumerate() {
                println!(
                    "  {}. {} - {:.1} ms ({:.0} km)",
                    i + 1,
                    s.name,
                    s.latency_ms,
                    s.distance_km
                );
            }
        }
        TestEvent::PrimarySelected {
            name,
            location,
            distance_km,
        } => {
            println!(
                "{} {} ({}, {:.0} km)",
                "βœ“ Selected:".bright_green().bold(),
                name,
                location,
                distance_km
            );
        }
        TestEvent::PhaseStarted(phase) => {
            let _ = ui.show_section_header(phase.title());
            match phase {
                Phase::Download => {
                    *monitor = Some(
                        ui.create_bandwidth_monitor("DOWNLOAD SPEED BANDWIDTH MONITOR", "Download"),
                    );
                    *first_render = true;
                }
                Phase::Upload => {
                    *monitor = Some(
                        ui.create_bandwidth_monitor("UPLOAD SPEED BANDWIDTH MONITOR", "Upload"),
                    );
                    *first_render = true;
                }
                _ => {}
            }
        }
        TestEvent::DownloadSample { mbps, .. } | TestEvent::UploadSample { mbps, .. } => {
            if let Some(m) = monitor.as_ref() {
                m.update(mbps).await;
                if *first_render {
                    let _ = m.render_live().await;
                    *first_render = false;
                } else {
                    let _ = m.render_live_update().await;
                }
            }
        }
        TestEvent::DownloadComplete { mbps } | TestEvent::UploadComplete { mbps } => {
            if let Some(m) = monitor.take() {
                m.update(mbps).await;
                m.mark_final().await;
                let _ = m.render_live_update().await;
            }
            *first_render = true;
        }
        TestEvent::LatencyComplete { avg_ms } => {
            let explanation = if avg_ms <= 20.0 {
                "(Excellent - ideal for gaming)".bright_green().dimmed()
            } else if avg_ms <= 50.0 {
                "(Good - suitable for most activities)"
                    .bright_cyan()
                    .dimmed()
            } else if avg_ms <= 100.0 {
                "(Fair - noticeable lag)".bright_yellow().dimmed()
            } else {
                "(Poor - significant lag)".bright_red().dimmed()
            };
            println!(
                "βœ“ Latency: {} {}",
                format!("{:.1} ms", avg_ms).bright_cyan(),
                explanation
            );
        }
        TestEvent::Completed(result) => {
            display_results(&result);
        }
        TestEvent::LatencyProgress { .. }
        | TestEvent::JitterComplete { .. }
        | TestEvent::DiagnosticsComplete(_) => {}
    }
}

/// Run network diagnostics and render their progress to the terminal.
pub async fn run_diagnostics_tui(
    config: TestConfig,
) -> Result<NetworkDiagnostics, Box<dyn std::error::Error>> {
    let ui = UI::new(config.clone());
    let _ = ui.show_section_header("Running Network Diagnostics");

    let (tx, mut rx) = mpsc::unbounded_channel::<TestEvent>();
    let tool = NetworkDiagnosticsTool::with_events(config.clone(), Some(tx));
    let engine = tool.run_diagnostics();
    tokio::pin!(engine);
    let mut result: Option<NetworkDiagnostics> = None;

    loop {
        tokio::select! {
            biased;
            maybe_event = rx.recv() => {
                match maybe_event {
                    Some(event) => render_diag_event(event),
                    None => break,
                }
            }
            res = &mut engine => {
                result = Some(res?);
                break;
            }
        }
    }

    while let Ok(event) = rx.try_recv() {
        render_diag_event(event);
    }

    result.ok_or_else(|| "diagnostics did not complete".into())
}

fn render_diag_event(event: TestEvent) {
    match event {
        TestEvent::Status(msg) => {
            println!("{} {}", "Β»".bright_magenta(), msg.bright_blue());
        }
        TestEvent::DiagnosticsComplete(diag) => display_diagnostics(&diag),
        _ => {}
    }
}

/// Render the final network-diagnostics table.
fn display_diagnostics(d: &NetworkDiagnostics) {
    use prettytable::{format, Cell, Row, Table};

    println!();
    println!(
        "{}",
        ">>> CYBERNETIC NETWORK ANALYSIS <<<"
            .bright_magenta()
            .bold()
    );

    let mut table = Table::new();
    table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);

    let gateway = d
        .gateway_ip
        .map(|g| format!("{} ⚑", g))
        .unwrap_or_else(|| "❌ OFFLINE".to_string());
    table.add_row(Row::new(vec![
        Cell::new("🌐 Neural Gateway").style_spec("Fb"),
        Cell::new(&gateway),
    ]));

    let dns_servers = if d.dns_servers.is_empty() {
        "None detected".to_string()
    } else {
        d.dns_servers
            .iter()
            .map(|ip| ip.to_string())
            .collect::<Vec<_>>()
            .join(", ")
    };
    table.add_row(Row::new(vec![
        Cell::new("🧬 DNS Matrix").style_spec("Fb"),
        Cell::new(&format!("{} πŸ”—", dns_servers)),
    ]));

    table.add_row(Row::new(vec![
        Cell::new("⚑ DNS Response").style_spec("Fb"),
        Cell::new(&format!("{:.2} ms", d.dns_response_time_ms)),
    ]));

    table.add_row(Row::new(vec![
        Cell::new("πŸ›°οΈ IPv6 Protocol").style_spec("Fb"),
        Cell::new(if d.is_ipv6_available {
            "βœ… ACTIVE"
        } else {
            "⚠️ INACTIVE"
        }),
    ]));

    if let Some(conn) = &d.connection_type {
        table.add_row(Row::new(vec![
            Cell::new("πŸ“‘ Signal Interface").style_spec("Fb"),
            Cell::new(conn),
        ]));
    }
    if let Some(iface) = &d.network_interface {
        table.add_row(Row::new(vec![
            Cell::new("πŸ”— Neural Port").style_spec("Fb"),
            Cell::new(&format!("⟨{}⟩", iface)),
        ]));
    }
    table.printstd();

    if !d.route_hops.is_empty() {
        println!(
            "\n{}",
            " 🌐 NEURAL PATHWAY MAPPING 🌐 ".bright_magenta().bold()
        );
        let mut trace = Table::new();
        trace.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
        trace.add_row(Row::new(vec![
            Cell::new("πŸ”— Node").style_spec("Fb"),
            Cell::new("πŸ“ Address").style_spec("Fb"),
            Cell::new("🏷️ Identity").style_spec("Fb"),
            Cell::new("⚑ Delay").style_spec("Fb"),
        ]));
        for hop in &d.route_hops {
            let addr = hop.address.map_or("⟨⟨⟨ ENCRYPTED ⟩⟩⟩".to_string(), |a| {
                format!("{} πŸ”—", a)
            });
            let hostname = hop
                .hostname
                .clone()
                .unwrap_or_else(|| "⟨ANONYMOUS⟩".to_string());
            let time = hop
                .response_time_ms
                .map_or("πŸ”’ STEALTH".to_string(), |t| format!("{:.2} ms", t));
            trace.add_row(Row::new(vec![
                Cell::new(&format!("{:02}", hop.hop_number)),
                Cell::new(&addr),
                Cell::new(&hostname),
                Cell::new(&time),
            ]));
        }
        trace.printstd();
    }
}

/// Render the final speed-test results table.
fn display_results(result: &SpeedTestResult) {
    println!();
    println!("{}", "═".repeat(60).bright_blue());
    println!(
        "{}",
        "           SPEED TEST RESULTS           "
            .bright_yellow()
            .bold()
    );
    println!("{}", "═".repeat(60).bright_blue());
    println!();

    println!(
        "{:20} {}",
        "Download:".bright_blue().bold(),
        format!("{:.1} Mbps", result.download_mbps)
            .bright_green()
            .bold()
    );
    println!(
        "{:20} {}",
        "Upload:".bright_blue().bold(),
        format!("{:.1} Mbps", result.upload_mbps)
            .bright_green()
            .bold()
    );
    println!(
        "{:20} {}",
        "Ping:".bright_blue().bold(),
        format!("{:.1} ms", result.ping_ms).bright_cyan().bold()
    );
    println!(
        "{:20} {}",
        "Jitter:".bright_blue().bold(),
        format!("{:.1} ms", result.jitter_ms).bright_cyan()
    );

    if result.packet_loss_percent > 0.0 {
        println!(
            "{:20} {}",
            "Packet Loss:".bright_blue().bold(),
            format!("{:.1}%", result.packet_loss_percent).bright_red()
        );
    }

    println!(
        "{:20} {}",
        "Server:".bright_blue().bold(),
        result.server_location.bright_cyan()
    );

    if let Some(isp) = &result.isp {
        println!("{:20} {}", "ISP:".bright_blue().bold(), isp.bright_cyan());
    }

    let quality_colored = match result.quality {
        ConnectionQuality::Excellent | ConnectionQuality::Good => {
            format!("{}", result.quality).bright_green().bold()
        }
        ConnectionQuality::Average => format!("{}", result.quality).bright_yellow().bold(),
        _ => format!("{}", result.quality).bright_red().bold(),
    };
    println!("{:20} {}", "Quality:".bright_blue().bold(), quality_colored);

    println!();
    println!("{}", "═".repeat(60).bright_blue());
}