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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ jobs:
env:
# The commit the expectations were recorded against. The test is given
# it too and refuses to run against another one.
LIBRESPEED_GO_COMMIT: b660d1e6c24f14fc93624538d9e73163e7784335
LIBRESPEED_GO_COMMIT: 8aefd77bd4bde428cd86d3622102f0ac0443d96e
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
Expand Down
75 changes: 68 additions & 7 deletions src/defs/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ impl Server {
Ok(u) => url_join_path(&u, &self.ping_url),
Err(e) => {
write_debug!(out, "Failed when creating HTTP request: {e}\n");
return ServerStatus::default();
return ServerStatus::down(format!("{e:#}"));
}
};

Expand Down Expand Up @@ -164,16 +164,31 @@ impl Server {
"Failed when parsing get IP result: {}\n",
GoQuote(&body)
);
return ServerStatus::default();
}
// Status first: a web server's 404 or 500 comes with an error
// page, and the status names that fault better than the body.
let down_reason = if status != StatusCode::OK {
let code = status.as_u16();
Some(match go_status_text(status) {
Some(text) => format!("the ping request returned HTTP {code} {text}"),
None => format!("the ping request returned HTTP {code}"),
})
} else if !body.is_empty() {
Some("the ping request returned a non-empty body".to_string())
} else {
None
};
ServerStatus {
up: status == StatusCode::OK,
tls: facts.tls,
up: down_reason.is_none(),
down_reason,
// As before, a probe answered with a body reports nothing
// about its connection.
tls: facts.tls.filter(|_| body.is_empty()),
}
}
Err(e) => {
write_debug!(out, "Error checking for server status: {e:#}\n");
ServerStatus::default()
ServerStatus::down(format!("{e:#}"))
}
}
}
Expand Down Expand Up @@ -615,16 +630,43 @@ fn format_rate(label: &str, use_bytes: bool, counter: &BytesCounter) -> String {
}
}

/// How much of a probe response is worth keeping to quote in a diagnostic.
const PROBE_BODY_PEEK: usize = 8 * 1024;
/// How much of a probe response is read. Any body at all means the backend is
/// down, and the Go client reads and quotes the same first 512 bytes.
const PROBE_BODY_PEEK: usize = 512;

/// The reason phrase Go's `http.StatusText` gives a status, as the Go client
/// prints it rather than the one the server sent. The http crate words four
/// codes differently, and for a code neither knows there is none.
fn go_status_text(status: StatusCode) -> Option<&'static str> {
match status.as_u16() {
203 => Some("Non-Authoritative Information"),
413 => Some("Request Entity Too Large"),
414 => Some("Request URI Too Long"),
416 => Some("Requested Range Not Satisfiable"),
_ => status.canonical_reason(),
}
}

/// Whether a backend answered its probe, and what that connection negotiated.
#[derive(Debug, Default)]
pub struct ServerStatus {
pub up: bool,
/// Why the backend is down, when it is: the refused connection, the
/// unreachable network, the wrong status or a body where none belongs.
pub down_reason: Option<String>,
pub tls: Option<crate::http::TlsFacts>,
}

impl ServerStatus {
fn down(reason: String) -> Self {
ServerStatus {
up: false,
down_reason: Some(reason),
tls: None,
}
}
}

/// A running `--json-stream` progress ticker.
struct ProgressTicker {
stop: Arc<tokio::sync::Notify>,
Expand Down Expand Up @@ -940,6 +982,25 @@ mod tests {
fn sponsor_is_empty_without_a_name() {
assert_eq!(Server::default().sponsor(Output::default()), "");
}

// Go's net/http status table, where it differs from the http crate's, a
// few where they agree, and a code neither knows.
#[test]
fn status_text_is_gos() {
for (code, text) in [
(203, Some("Non-Authoritative Information")),
(404, Some("Not Found")),
(413, Some("Request Entity Too Large")),
(414, Some("Request URI Too Long")),
(416, Some("Requested Range Not Satisfiable")),
(422, Some("Unprocessable Entity")),
(500, Some("Internal Server Error")),
(599, None),
] {
let status = StatusCode::from_u16(code).unwrap();
assert_eq!(go_status_text(status), text, "{code}");
}
}
}

#[cfg(test)]
Expand Down
47 changes: 44 additions & 3 deletions src/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ pub async fn do_speed_test(
servers: &[Server],
ctx: &TestContext<'_>,
) -> anyhow::Result<()> {
// With nothing to test the report would be empty, like when every server
// is down (--server -1 with an empty list gets here).
if servers.is_empty() {
anyhow::bail!("No server to test: the server list is empty");
}

let out = ctx.out;
if servers.len() > 1 {
write_ui!(out, "Testing against {} servers\n", servers.len());
Expand All @@ -63,6 +69,9 @@ pub async fn do_speed_test(
let delimiter = cli.csv_delimiter_byte()?;
let mut reps_json: Vec<JSONReport> = Vec::new();
let mut reps_csv: Vec<CSVReport> = Vec::new();
let mut measured = false;
// Each server that did not answer its probe, and why.
let mut down: Vec<(String, String)> = Vec::new();

for current_server in servers {
let tlog = TelemetryLog::new();
Expand Down Expand Up @@ -106,6 +115,16 @@ pub async fn do_speed_test(
if servers.len() > 1 && !out.quiet {
output::write_ui_blank();
}
down.push((
format!(
"{} ({})",
output::sanitize(&current_server.name),
output::sanitize(&hostname)
),
status
.down_reason
.unwrap_or_else(|| "its probe failed".to_string()),
));
continue;
}

Expand Down Expand Up @@ -339,12 +358,20 @@ pub async fn do_speed_test(
});
}

measured = true;

// Add a blank line after each test when testing multiple servers.
if servers.len() > 1 && !out.quiet {
output::write_ui_blank();
}
}

// No server answered: fail instead of printing an empty report, which with
// exit status 0 would pass for a result.
if !measured && !down.is_empty() {
return Err(none_responding(&down));
}

if cli.csv {
match report::csv_rows(&reps_csv, delimiter) {
Ok(s) => write_out!("{s}"),
Expand Down Expand Up @@ -377,11 +404,25 @@ fn report_failure(what: &str, e: anyhow::Error) -> anyhow::Error {
e
}

/// The error for a run whose servers were all down: each one and its cause.
fn none_responding(down: &[(String, String)]) -> anyhow::Error {
match down {
[(server, why)] => anyhow::anyhow!("Selected server {server} is not responding: {why}"),
_ => anyhow::anyhow!(
"None of the {} selected servers is responding: {}",
down.len(),
down.iter()
.map(|(server, why)| format!("{server}: {why}"))
.collect::<Vec<_>>()
.join("; ")
),
}
}

/// The reports as JSON sees them: `null` when nothing was measured.
///
/// Go declares a nil slice, which marshals to `null`, and both clients exit 0
/// even when every server failed -- so the document is the only signal that
/// nothing happened, and a consumer testing for null must keep seeing it.
/// Go declares a nil slice, which marshals to `null`. No run gets here with
/// nothing measured any more: down servers and an empty list fail it first.
fn json_reports(reports: &[JSONReport]) -> Option<&[JSONReport]> {
(!reports.is_empty()).then_some(reports)
}
Expand Down
1 change: 1 addition & 0 deletions tests/data/parity/servers-empty.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[]
Loading
Loading