netspeed-cli 0.7.0

Command-line interface for testing internet bandwidth using speedtest.net
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
//! Orchestrates the full speed test lifecycle.
//!
//! Extracted from `main.rs` to follow single-responsibility and enable
//! unit testing of the test flow independent of the binary entry point.

use crate::cli::{CliArgs, ShellType};
use crate::common;
use crate::config::Config;
use crate::error::SpeedtestError;
use crate::formatter::{OutputFormat, format_list};
use crate::history;
use crate::http;
use crate::progress::{create_spinner, finish_ok, no_color};
use crate::servers::{fetch_servers, ping_test, select_best_server};
use crate::test_runner::{self, TestRunResult};
use crate::types::Server;
use crate::types::{self, TestResult};
use crate::{download, upload};

use owo_colors::OwoColorize;

/// Orchestrates the full speed test lifecycle.
pub struct SpeedTestOrchestrator {
    args: CliArgs,
    config: Config,
    client: reqwest::Client,
}

impl SpeedTestOrchestrator {
    /// Create a new orchestrator from CLI arguments.
    pub fn new(args: CliArgs) -> Result<Self, SpeedtestError> {
        let config = Config::from_args(&args);
        let client = http::create_client(&config)?;
        Ok(Self {
            args,
            config,
            client,
        })
    }

    /// Run the full speed test workflow.
    pub async fn run(&self) -> Result<(), SpeedtestError> {
        // Shell completion early-exit
        if let Some(shell) = self.args.generate_completion {
            Self::generate_shell_completion(shell);
            return Ok(());
        }

        // History display early-exit
        if self.args.history {
            history::print_history()?;
            return Ok(());
        }

        let is_verbose = self.is_verbose();

        // Print header
        if is_verbose {
            Self::print_header();
        }

        // Fetch and filter servers
        let servers = self.fetch_and_filter_servers(is_verbose).await?;

        // Handle --list: format_list already printed, signal completion
        if self.config.list {
            return Ok(());
        }

        // Select best server
        let server = select_best_server(&servers)?;

        // Server info
        if is_verbose {
            Self::print_server_info(&server);
        }

        // Discover client IP
        let client_ip = http::discover_client_ip(&self.client).await.ok();

        // Run ping test
        let (ping, jitter, packet_loss, ping_samples) =
            self.run_ping_test(&server, is_verbose).await?;

        // Run download test
        let dl_result = self.run_download_test(&server, is_verbose).await?;

        // Run upload test
        let ul_result = self.run_upload_test(&server, is_verbose).await?;

        // Build result
        let result = TestResult::from_test_runs(
            types::ServerInfo {
                id: server.id.clone(),
                name: server.name.clone(),
                sponsor: server.sponsor.clone(),
                country: server.country.clone(),
                distance: server.distance,
            },
            ping,
            jitter,
            packet_loss,
            ping_samples,
            &dl_result,
            &ul_result,
            client_ip,
        );

        // Save to history (unless --json or --csv)
        if !self.config.json && !self.config.csv {
            history::save_result(&result).ok();
        }

        // Output — Strategy pattern dispatch
        self.output_results(&result, &dl_result, &ul_result)?;

        Ok(())
    }

    /// Whether verbose output should be shown.
    pub fn is_verbose(&self) -> bool {
        use crate::cli::OutputFormatType;
        // Quiet mode suppresses all stderr output
        if self.config.quiet {
            return false;
        }
        let format_non_verbose = matches!(
            self.args.format,
            Some(
                OutputFormatType::Simple
                    | OutputFormatType::Json
                    | OutputFormatType::Csv
                    | OutputFormatType::Dashboard
            )
        );
        !self.config.simple
            && !self.config.json
            && !self.config.csv
            && !self.config.list
            && !format_non_verbose
    }

    fn print_header() {
        eprintln!(
            "{}",
            format!("  ═══  NetSpeed CLI v{}  ═══", env!("CARGO_PKG_VERSION"))
                .dimmed()
                .bold()
        );
        eprintln!("{}", "  Bandwidth test · speedtest.net".dimmed());
        eprintln!();
    }

    fn print_server_info(server: &Server) {
        let dist = common::format_distance(server.distance);
        eprintln!();
        if no_color() {
            eprintln!("  Server:   {} ({})", server.sponsor, server.name);
            eprintln!("  Location: {} ({dist})", server.country);
        } else {
            eprintln!(
                "  {}   {} ({})",
                "Server:".dimmed(),
                server.sponsor.white().bold(),
                server.name
            );
            eprintln!("  {} {} ({dist})", "Location:".dimmed(), server.country);
        }
        eprintln!();
    }

    async fn fetch_and_filter_servers(
        &self,
        is_verbose: bool,
    ) -> Result<Vec<Server>, SpeedtestError> {
        let fetch_spinner = if is_verbose {
            Some(create_spinner("Finding servers..."))
        } else {
            None
        };
        let mut servers = fetch_servers(&self.client).await?;
        if let Some(ref pb) = fetch_spinner {
            finish_ok(pb, &format!("Found {} servers", servers.len()));
            eprintln!();
        }

        // Handle --list option
        if self.config.list {
            format_list(&servers)?;
            return Ok(Vec::new()); // caller checks config.list
        }

        // Filter servers
        if !self.config.server_ids.is_empty() {
            servers.retain(|s| self.config.server_ids.contains(&s.id));
        }
        if !self.config.exclude_ids.is_empty() {
            servers.retain(|s| !self.config.exclude_ids.contains(&s.id));
        }

        if servers.is_empty() {
            return Err(SpeedtestError::ServerNotFound(
                "No servers match your criteria. Try running without --server/--exclude filters, or use --list to see available servers.".to_string(),
            ));
        }

        Ok(servers)
    }

    async fn run_ping_test(
        &self,
        server: &Server,
        is_verbose: bool,
    ) -> Result<(Option<f64>, Option<f64>, Option<f64>, Vec<f64>), SpeedtestError> {
        if self.config.no_download && self.config.no_upload {
            return Ok((None, None, None, Vec::new()));
        }

        let ping_spinner = if is_verbose {
            Some(create_spinner("Testing latency..."))
        } else {
            None
        };
        let ping_result = ping_test(&self.client, server).await?;
        if let Some(ref pb) = ping_spinner {
            let msg = if no_color() {
                format!("Latency: {:.2} ms", ping_result.0)
            } else {
                format!(
                    "Latency: {}",
                    format!("{:.2} ms", ping_result.0).cyan().bold()
                )
            };
            finish_ok(pb, &msg);
        }
        Ok((
            Some(ping_result.0),
            Some(ping_result.1),
            Some(ping_result.2),
            ping_result.3,
        ))
    }

    async fn run_download_test(
        &self,
        server: &Server,
        is_verbose: bool,
    ) -> Result<TestRunResult, SpeedtestError> {
        if self.config.no_download {
            return Ok(TestRunResult::default());
        }

        test_runner::run_bandwidth_test(
            &self.config,
            server,
            "Download",
            is_verbose,
            |progress| async {
                download::download_test(&self.client, server, self.config.single, progress).await
            },
        )
        .await
    }

    async fn run_upload_test(
        &self,
        server: &Server,
        is_verbose: bool,
    ) -> Result<TestRunResult, SpeedtestError> {
        if self.config.no_upload {
            return Ok(TestRunResult::default());
        }

        test_runner::run_bandwidth_test(
            &self.config,
            server,
            "Upload",
            is_verbose,
            |progress| async {
                upload::upload_test(&self.client, server, self.config.single, progress).await
            },
        )
        .await
    }

    fn output_results(
        &self,
        result: &TestResult,
        dl_result: &TestRunResult,
        ul_result: &TestRunResult,
    ) -> Result<(), SpeedtestError> {
        use crate::cli::OutputFormatType;

        // --format flag takes precedence over legacy --json/--csv/--simple booleans
        let output_format = match self.args.format {
            Some(OutputFormatType::Json) => OutputFormat::Json,
            Some(OutputFormatType::Csv) => OutputFormat::Csv {
                delimiter: self.config.csv_delimiter,
                header: self.config.csv_header,
            },
            Some(OutputFormatType::Simple) => OutputFormat::Simple,
            Some(OutputFormatType::Dashboard) => OutputFormat::Dashboard {
                dl_mbps: dl_result.avg_bps / 1_000_000.0,
                dl_peak_mbps: dl_result.peak_bps / 1_000_000.0,
                dl_bytes: dl_result.total_bytes,
                dl_duration: dl_result.duration_secs,
                ul_mbps: ul_result.avg_bps / 1_000_000.0,
                ul_peak_mbps: ul_result.peak_bps / 1_000_000.0,
                ul_bytes: ul_result.total_bytes,
                ul_duration: ul_result.duration_secs,
            },
            Some(OutputFormatType::Detailed) => OutputFormat::Detailed {
                dl_bytes: dl_result.total_bytes,
                ul_bytes: ul_result.total_bytes,
                dl_duration: dl_result.duration_secs,
                ul_duration: ul_result.duration_secs,
                dl_skipped: self.config.no_download,
                ul_skipped: self.config.no_upload,
            },
            None => {
                // Legacy boolean flag fallback
                if self.config.json {
                    OutputFormat::Json
                } else if self.config.csv {
                    OutputFormat::Csv {
                        delimiter: self.config.csv_delimiter,
                        header: self.config.csv_header,
                    }
                } else if self.config.simple {
                    OutputFormat::Simple
                } else {
                    OutputFormat::Detailed {
                        dl_bytes: dl_result.total_bytes,
                        ul_bytes: ul_result.total_bytes,
                        dl_duration: dl_result.duration_secs,
                        ul_duration: ul_result.duration_secs,
                        dl_skipped: self.config.no_download,
                        ul_skipped: self.config.no_upload,
                    }
                }
            }
        };
        output_format.format(result, self.config.bytes)?;

        Ok(())
    }

    fn generate_shell_completion(shell: ShellType) {
        use clap::CommandFactory;
        use clap_complete::{Shell as CompleteShell, generate};
        use std::io;

        let shell_type = match shell {
            ShellType::Bash => CompleteShell::Bash,
            ShellType::Zsh => CompleteShell::Zsh,
            ShellType::Fish => CompleteShell::Fish,
            ShellType::PowerShell => CompleteShell::PowerShell,
            ShellType::Elvish => CompleteShell::Elvish,
        };

        let mut cmd = CliArgs::command();
        let bin_name = "netspeed-cli";
        generate(shell_type, &mut cmd, bin_name, &mut io::stdout());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::CliArgs;
    use clap::Parser;

    #[test]
    fn test_is_verbose_default() {
        let args = CliArgs::parse_from(["netspeed-cli"]);
        let orch = SpeedTestOrchestrator::new(args).unwrap();
        assert!(orch.is_verbose());
    }

    #[test]
    fn test_is_verbose_simple() {
        let args = CliArgs::parse_from(["netspeed-cli", "--simple"]);
        let orch = SpeedTestOrchestrator::new(args).unwrap();
        assert!(!orch.is_verbose());
    }

    #[test]
    fn test_is_verbose_json() {
        let args = CliArgs::parse_from(["netspeed-cli", "--json"]);
        let orch = SpeedTestOrchestrator::new(args).unwrap();
        assert!(!orch.is_verbose());
    }

    #[test]
    fn test_is_verbose_csv() {
        let args = CliArgs::parse_from(["netspeed-cli", "--csv"]);
        let orch = SpeedTestOrchestrator::new(args).unwrap();
        assert!(!orch.is_verbose());
    }

    #[test]
    fn test_is_verbose_list() {
        let args = CliArgs::parse_from(["netspeed-cli", "--list"]);
        let orch = SpeedTestOrchestrator::new(args).unwrap();
        assert!(!orch.is_verbose());
    }

    #[test]
    fn test_orchestrator_creation() {
        let args = CliArgs::parse_from(["netspeed-cli"]);
        let orch = SpeedTestOrchestrator::new(args);
        assert!(orch.is_ok());
    }

    #[test]
    fn test_orchestrator_creation_default() {
        // Default args (no source IP) should always create successfully
        let args = CliArgs::parse_from(["netspeed-cli"]);
        let orch = SpeedTestOrchestrator::new(args);
        assert!(orch.is_ok());
    }
}