Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .agents/skills/interactive-cli-pr/scripts/record_preview.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,7 @@ def main():
"--scenario", choices=("clean", "retry", "partial"), default="clean"
)
parser.add_argument("--max-payload-size", choices=tuple(SIZES), default="10m")
parser.add_argument("--bytes", action="store_true", help="Show throughput in MB/s")
parser.add_argument(
"--max-duration",
type=int,
Expand Down Expand Up @@ -367,8 +368,12 @@ def main():
"--server",
url,
]
unit_flag = ""
if args.bytes:
flags.insert(0, "--bytes")
unit_flag = " --bytes"
prompt = (
f"$ cfspeedtest --max-payload-size {args.max_payload_size} --max-duration {args.max_duration} \\\r\n"
f"$ cfspeedtest{unit_flag} --max-payload-size {args.max_payload_size} --max-duration {args.max_duration} \\\r\n"
f" --disable-dynamic-max-payload-size --server {url}\r\n"
)
code, frames = capture(
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ Options:
Test upload speed only
--generate-completion <COMPLETION>
Generate shell completion script for the specified shell [possible values: bash, elvish, fish, powershell, zsh]
--bytes
Show human-readable throughput in MB/s instead of Mbit/s
--server <SERVER>
Base URL of a compatible Cloudflare speed-test service [default: https://speed.cloudflare.com]
--max-duration <MAX_DURATION>
Expand All @@ -68,6 +70,10 @@ Example with json-pretty output:

In human-readable mode, live progress is shown on stderr only when it is a terminal. When both stdout and stderr are terminals, each completed transfer size adds a row to the results table. Redirecting stdout keeps the end-of-run summary instead, without progress redraws. CSV and JSON modes never draw a progress bar.

By default, cfspeedtest reports throughput in decimal megabits per second (`Mbit/s`). Use `cfspeedtest --bytes` to see decimal megabytes per second (`MB/s`) in the live display and summary. For example, `100 Mbit/s` is `12.50 MB/s`.

CSV, JSON, and JSON-pretty always report throughput in `Mbit/s` and do not support `--bytes`.

### Run limits and failures

Runs have a shared 120-second measurement deadline and a 30-second cumulative retry-wait budget by default. Both limits cover the entire run, including metadata, latency, and both transfer directions. Each request is limited to the smaller of 30 seconds and the remaining run time.
Expand Down
23 changes: 20 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
mod diagnostics;

use cfspeedtest::measurements::ThroughputUnit;
use cfspeedtest::run::RunConfig;
use cfspeedtest::speedtest::speed_test_with_config;
use cfspeedtest::speedtest::speed_test_with_config_and_unit;
use cfspeedtest::stdout;
use cfspeedtest::{OutputFormat, SpeedTestCLIOptions};
use clap::error::ErrorKind;
Expand All @@ -19,6 +20,9 @@ use std::time::Duration;
struct CliOptions {
#[command(flatten)]
options: SpeedTestCLIOptions,
/// Show human-readable throughput in MB/s instead of Mbit/s
#[arg(long)]
bytes: bool,
/// Base URL of a compatible Cloudflare speed-test service
#[arg(long, default_value = "https://speed.cloudflare.com")]
server: reqwest::Url,
Expand Down Expand Up @@ -74,6 +78,20 @@ fn main() -> ExitCode {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("off")).init();
let cli = CliOptions::parse();
let options = cli.options;
let human_output = options.output_format == OutputFormat::StdOut;
if cli.bytes && !human_output {
CliOptions::command()
.error(
ErrorKind::ArgumentConflict,
"--bytes is only available with human-readable output (default or -o stdout)",
)
.exit();
}
let throughput_unit = if cli.bytes {
ThroughputUnit::Megabytes
} else {
ThroughputUnit::Megabits
};
let local_address = local_address(&options);

if let Some(generator) = options.completion {
Expand Down Expand Up @@ -111,11 +129,10 @@ fn main() -> ExitCode {
eprintln!("Failed to install cancellation handler: {error}");
return ExitCode::FAILURE;
}
let human_output = options.output_format == OutputFormat::StdOut;
if human_output {
stdout::write(|stdout| writeln!(stdout, "Starting Cloudflare speed test"));
}
let report = speed_test_with_config(client, options, config);
let report = speed_test_with_config_and_unit(client, options, config, throughput_unit);
if human_output {
// Diagnostics are best-effort and do not change the run's exit status.
let _ = diagnostics::write_human(&report, io::stderr().lock());
Expand Down
136 changes: 120 additions & 16 deletions src/measurements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,36 @@ use std::{
io::{self, Write},
};

/// Decimal throughput unit used in human-readable output.
#[derive(Clone, Copy, Debug, Default)]
pub enum ThroughputUnit {
/// Megabits per second (Mbit/s).
#[default]
Megabits,
/// Megabytes per second (MB/s).
Megabytes,
}

impl ThroughputUnit {
pub(crate) fn label(self) -> &'static str {
match self {
Self::Megabits => "Mbit/s",
Self::Megabytes => "MB/s",
}
}

pub(crate) fn convert(self, mbits_per_second: f64) -> f64 {
match self {
Self::Megabits => mbits_per_second,
Self::Megabytes => mbits_per_second / 8.0,
}
}

fn display_stats(self, (min, q1, median, q3, max, avg): ThroughputStats) -> [f64; 6] {
[min, q1, median, q3, max, avg].map(|rate| self.convert(rate))
}
}

#[derive(Serialize)]
struct StatMeasurement {
test_type: TestType,
Expand Down Expand Up @@ -112,13 +142,15 @@ pub(crate) mod transfer_columns {
/// A running summary for interactive output. Each payload is rendered once.
pub(crate) struct TransferTable {
verbose: bool,
unit: ThroughputUnit,
started: bool,
}

impl TransferTable {
pub(crate) fn new(verbose: bool) -> Self {
pub(crate) fn new(verbose: bool, unit: ThroughputUnit) -> Self {
Self {
verbose,
unit,
started: false,
}
}
Expand All @@ -139,18 +171,22 @@ impl TransferTable {
.chars()
.map(|c| if c == '|' { '+' } else { '-' })
.collect();
format!("Speed test results (Mbit/s)\n\n{header}\n{rule}\n")
format!(
"Speed test results ({})\n\n{header}\n{rule}\n",
self.unit.label()
)
}

pub(crate) fn print_row(&self, attempts: &PayloadAttemptStats, samples: &[Measurement]) {
stdout::print(format_args!("{}", self.render_row(attempts, samples)));
}

fn render_row(&self, attempts: &PayloadAttemptStats, samples: &[Measurement]) -> String {
let stats = calc_stats(samples.iter().map(|sample| sample.mbit).collect());
let stats = calc_stats(samples.iter().map(|sample| sample.mbit).collect())
.map(|stats| self.unit.display_stats(stats));
let [avg, min, max] = stats.map_or_else(
|| ["N/A".to_owned(), "N/A".to_owned(), "N/A".to_owned()],
|(min, _, _, _, max, avg)| [avg, min, max].map(format_table_rate),
|[min, _, _, _, max, avg]| [avg, min, max].map(format_table_rate),
);
let label = transfer_columns::payload_label(attempts.test_type, attempts.payload_size);
let count = format!("{}/{}", attempts.successes, attempts.target_successes);
Expand All @@ -163,7 +199,7 @@ impl TransferTable {
}
output.push('\n');
if self.verbose {
if let Some((min, q1, median, q3, max, _)) = stats {
if let Some([min, q1, median, q3, max, _]) = stats {
let plot = boxplot::render_plot(min, q1, median, q3, max);
output.push_str(&format!("{plot}\n\n"));
}
Expand All @@ -187,18 +223,21 @@ pub(crate) fn log_measurements(
payload_sizes: Vec<usize>,
verbose: bool,
output_format: OutputFormat,
throughput_unit: ThroughputUnit,
) {
let measurements = &report.measurements;
let payload_attempt_stats = &report.payload_attempt_stats;
if output_format == OutputFormat::StdOut {
stdout::print_line(format_args!("\nSummary Statistics"));
if verbose {
stdout::print_line(format_args!(
"Type Payload | min/max/avg in Mbit/s | attempts/success/skipped",
));
let label = throughput_unit.label();
let counts = if verbose {
" | attempts/success/skipped"
} else {
stdout::print_line(format_args!("Type Payload | min/max/avg in Mbit/s"));
}
""
};
stdout::print_line(format_args!(
"Type Payload | min/max/avg in {label}{counts}"
));
}
let mut stat_measurements: Vec<StatMeasurement> = Vec::new();
let mut test_types = measurements
Expand All @@ -216,6 +255,7 @@ pub(crate) fn log_measurements(
payload_sizes.clone(),
verbose,
output_format,
throughput_unit,
*test_type,
))
});
Expand Down Expand Up @@ -307,6 +347,7 @@ fn log_measurements_by_test_type(
payload_sizes: Vec<usize>,
verbose: bool,
output_format: OutputFormat,
throughput_unit: ThroughputUnit,
test_type: TestType,
) -> Vec<StatMeasurement> {
let mut stat_measurements: Vec<StatMeasurement> = Vec::new();
Expand All @@ -333,9 +374,7 @@ fn log_measurements_by_test_type(
let formatted_payload = format_bytes(payload_size);
let fmt_test_type = format!("{test_type:?}");

if !type_measurements.is_empty() {
let (min, q1, median, q3, max, avg) = calc_stats(type_measurements).unwrap();

if let Some(stats @ (min, q1, median, q3, max, avg)) = calc_stats(type_measurements) {
stat_measurements.push(StatMeasurement {
test_type,
payload_size,
Expand All @@ -351,6 +390,7 @@ fn log_measurements_by_test_type(
target_successes,
});
if output_format == OutputFormat::StdOut {
let [min, q1, median, q3, max, avg] = throughput_unit.display_stats(stats);
if verbose {
stdout::print_line(format_args!(
"{fmt_test_type:<9} {formatted_payload:<7}| min {min:<7.2} max {max:<7.2} avg {avg:<7.2} | {attempts:>3}/{successes:>3}/{skipped:>3}"
Expand Down Expand Up @@ -402,7 +442,9 @@ fn log_measurements_by_test_type(
stat_measurements
}

fn calc_stats(mbit_measurements: Vec<f64>) -> Option<(f64, f64, f64, f64, f64, f64)> {
type ThroughputStats = (f64, f64, f64, f64, f64, f64);

fn calc_stats(mbit_measurements: Vec<f64>) -> Option<ThroughputStats> {
log::debug!("calc_stats for mbit_measurements {mbit_measurements:?}");
let length = mbit_measurements.len();
if length == 0 {
Expand Down Expand Up @@ -475,7 +517,7 @@ mod tests {

#[test]
fn interactive_table_aligns_dividers_and_keeps_partial_and_empty_payloads() {
let table = TransferTable::new(false);
let table = TransferTable::new(false, ThroughputUnit::Megabits);
let partial = PayloadAttemptStats {
test_type: TestType::Download,
payload_size: 100_000,
Expand Down Expand Up @@ -517,6 +559,68 @@ mod tests {
);
}

#[test]
fn byte_display_converts_table_statistics_and_boxplot_axis() {
let table = TransferTable::new(true, ThroughputUnit::Megabytes);
let attempts = PayloadAttemptStats {
test_type: TestType::Download,
payload_size: 100_000,
attempts: 2,
successes: 2,
skipped: 0,
target_successes: 2,
};
let samples = [60.0, 100.0].map(|mbit| Measurement {
test_type: attempts.test_type,
payload_size: attempts.payload_size,
mbit,
});
assert!(table
.render_header()
.starts_with("Speed test results (MB/s)\n"));
let row = table.render_row(&attempts, &samples);
let mut lines = row.lines();
assert_eq!(
lines.next().unwrap().split_whitespace().collect::<Vec<_>>(),
["Download", "100", "KB", "|", "10.00", "7.50", "12.50", "|", "2/2", "2", "0"]
);
let axis = lines.nth(1).unwrap();
assert_eq!(
axis.split_whitespace().collect::<Vec<_>>(),
["7.50", "10.00", "12.50"]
);
}

#[test]
fn machine_statistics_always_use_megabits() {
let sample = Measurement {
test_type: TestType::Download,
payload_size: 100_000,
mbit: 100.0,
};
for format in [
OutputFormat::Csv,
OutputFormat::Json,
OutputFormat::JsonPretty,
] {
let stats = log_measurements_by_test_type(
std::slice::from_ref(&sample),
&[],
vec![sample.payload_size],
false,
format,
ThroughputUnit::Megabytes,
sample.test_type,
);
assert_eq!(stats.len(), 1);
let stat = &stats[0];
assert_eq!(
[stat.min, stat.q1, stat.median, stat.q3, stat.max, stat.avg],
[Some(100.0); 6]
);
}
}

#[test]
fn live_bar_brackets_replace_table_dividers() {
use transfer_columns::{BAR_OFFSET, BAR_WIDTH, ROW_WIDTH, SAMPLES_WIDTH};
Expand Down
Loading
Loading