Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

feat(fetch): add HTTP failure flags with status-aware errors

ldm094570ff379d0
diff --git a/moli/src/app.rs b/moli/src/app.rs
index a50fa0419..0a381f91b 100644
--- a/moli/src/app.rs
+++ b/moli/src/app.rs
@@ -7,6 +7,7 @@ use std::{
fmt,
io::{Read, Write},
path::Path,
+ process::ExitCode,
sync::Arc,
};
@@ -20,7 +21,7 @@ use anyhow::{Context, anyhow};
use clap::Parser;
use moli_core::runtime::{
Browser, FetchReadinessTimeout, FetchedDocument, NavigationRuntimeConfig,
- storage_partition::StoragePartitionState,
+ RawDocumentFetchPolicy, storage_partition::StoragePartitionState,
};
use moli_fetch::{NetworkFetchFailureContext, Request};
use moli_protocol_server::ProtocolServer;
@@ -57,6 +58,15 @@ pub async fn run_cli_with_config<W: Write>(
ReadinessPlan::from_fetch_args(&args, config.fetch.response_wait.clone())?;
let raw_document_output =
fetch_dump::RawDocumentOutputPolicy::from_command(&config.fetch);
+ // HTTP failure modes need the response status before deciding
+ // whether the selected output format accepts a raw download.
+ let raw_document_fetch_policy = if args.fail {
+ RawDocumentFetchPolicy::MaterializeBelowStatus(400)
+ } else if args.fail_with_body {
+ RawDocumentFetchPolicy::Materialize
+ } else {
+ raw_document_output.fetch_policy()
+ };
let request = build_fetch_request(&args.url, &config)?;
if config.browser.fetch().obey_robots() {
// Checked before the browser starts so a refused fetch costs
@@ -68,7 +78,7 @@ pub async fn run_cli_with_config<W: Write>(
let browser = Browser::new(config.browser.clone())?;
load_cookie_state(&browser, &config)?;
let fetch_result = readiness
- .fetch_document(&browser, request, raw_document_output.fetch_policy())
+ .fetch_document(&browser, request, raw_document_fetch_policy)
.await;
let fetched_document = match fetch_result {
Ok(document) => document,
@@ -84,38 +94,80 @@ pub async fn run_cli_with_config<W: Write>(
let mut page = match fetched_document {
FetchedDocument::Page(page) => page,
FetchedDocument::Raw(raw_document) => {
- if eval_expression.is_some() {
- finalize_fetch_browser(browser);
- return Err(with_fetch_context(
- anyhow!(
+ let http_failure = http_status_failure(
+ &args,
+ raw_document.status(),
+ raw_document.final_url().as_str(),
+ );
+ let with_output_context = |error| {
+ with_http_status_context(
+ error,
+ &args,
+ raw_document.status(),
+ raw_document.final_url().as_str(),
+ )
+ };
+ if !args.fail || http_failure.is_none() {
+ if eval_expression.is_some() {
+ finalize_fetch_browser(browser);
+ return Err(with_output_context(anyhow!(
"raw non-HTML document fetch does not support --eval or --eval-file"
- ),
- &args.url,
- ));
- }
- if readiness.has_page_waits() || args.delay_ms > 0 {
- finalize_fetch_browser(browser);
- return Err(with_fetch_context(
- anyhow!(
+ )));
+ }
+ if readiness.has_page_waits() || args.delay_ms > 0 {
+ finalize_fetch_browser(browser);
+ return Err(with_output_context(anyhow!(
"raw non-HTML document fetch does not support page wait options"
- ),
- &args.url,
- ));
+ )));
+ }
+ let rendered = fetch_dump::render_raw_document_output(
+ &raw_document,
+ raw_document_output,
+ )
+ .map_err(with_output_context)?;
+ stdout
+ .write_all(&rendered)
+ .context("failed to write raw fetch output")
+ .map_err(with_output_context)?;
+ stdout
+ .flush()
+ .context("failed to flush raw fetch output")
+ .map_err(with_output_context)?;
}
- let rendered =
- fetch_dump::render_raw_document_output(&raw_document, raw_document_output)
- .map_err(|error| with_fetch_context(error, &args.url))?;
- stdout
- .write_all(&rendered)
- .context("failed to write raw fetch output")
- .map_err(|error| with_fetch_context(error, &args.url))?;
- let _ = stdout.flush();
finalize_fetch_browser(browser);
- return Ok(());
+ return http_failure.map_or(Ok(()), Err);
}
};
- if let Err(error) = readiness.wait_for_page(&browser, &mut page).await {
+ let readiness_result = async {
+ readiness.wait_for_page(&browser, &mut page).await?;
+ if args.delay_ms > 0 {
+ browser
+ .wait_for_page_delay(
+ &mut page,
+ std::time::Duration::from_millis(args.delay_ms),
+ )
+ .await
+ .context("failed while waiting for page delay")?;
+ }
+ Ok::<(), anyhow::Error>(())
+ }
+ .await;
+ if let Err(error) = readiness_result {
+ if (args.fail || args.fail_with_body)
+ && let Err(snapshot_error) = page.page_diagnostics_snapshot_async().await
+ {
+ tracing::debug!(
+ error = %snapshot_error,
+ "failed to refresh main-document state after readiness failure"
+ );
+ }
+ let error = with_http_status_context(
+ error,
+ &args,
+ page.status(),
+ page.final_url().as_str(),
+ );
if let Err(close_error) = page.close_async().await {
tracing::warn!(
error = %close_error,
@@ -123,38 +175,43 @@ pub async fn run_cli_with_config<W: Write>(
);
}
finalize_fetch_browser(browser);
- return Err(with_fetch_context(error, &args.url));
+ return Err(error);
}
- if args.delay_ms > 0 {
- browser
- .wait_for_page_delay(&mut page, std::time::Duration::from_millis(args.delay_ms))
- .await
- .context("failed while waiting for page delay")
- .map_err(|error| with_fetch_context(error, &args.url))?;
- }
-
- let rendered = if let Some(expression) = eval_expression.as_deref() {
- if config.browser.layout_policy().uses_real_layout() {
- page.publish_layout_async()
- .await
- .context("failed to publish layout before evaluating JavaScript")
- .map_err(|error| with_fetch_context(error, &args.url))?;
+ let page_status = page.status();
+ let final_url = page.final_url().clone();
+ let http_failure = http_status_failure(&args, page_status, final_url.as_str());
+ let with_output_context =
+ |error| with_http_status_context(error, &args, page_status, final_url.as_str());
+ if !args.fail || http_failure.is_none() {
+ let rendered = if let Some(expression) = eval_expression.as_deref() {
+ if config.browser.layout_policy().uses_real_layout() {
+ page.publish_layout_async()
+ .await
+ .context("failed to publish layout before evaluating JavaScript")
+ .map_err(with_output_context)?;
+ }
+ eval_output::evaluate(&mut page, expression).await
+ } else {
+ fetch_dump::render_page_output_async(&mut page, &config.fetch).await
}
- eval_output::evaluate(&mut page, expression).await
- } else {
- fetch_dump::render_page_output_async(&mut page, &config.fetch).await
+ .map_err(with_output_context)?;
+ stdout
+ .write_all(&rendered)
+ .context("failed to write fetch output")
+ .map_err(with_output_context)?;
+ stdout
+ .flush()
+ .context("failed to flush fetch output")
+ .map_err(with_output_context)?;
}
- .map_err(|error| with_fetch_context(error, &args.url))?;
- stdout
- .write_all(&rendered)
- .context("failed to write fetch output")
- .map_err(|error| with_fetch_context(error, &args.url))?;
- let _ = stdout.flush();
if let Err(error) = page.close_async().await {
tracing::warn!(error = %error, "failed to close fetched page before browser shutdown");
}
finalize_fetch_browser(browser);
+ if let Some(error) = http_failure {
+ return Err(error);
+ }
}
Commands::Serve(_) => {
if config.browser.fetch().obey_robots() {
@@ -225,6 +282,57 @@ fn build_fetch_request(url: &str, config: &AppConfig) -> Result<Request> {
Ok(request)
}
+#[derive(Debug)]
+struct CliHttpStatusFailure {
+ status: u16,
+ final_url: String,
+}
+
+impl fmt::Display for CliHttpStatusFailure {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(
+ formatter,
+ "final main document returned HTTP status {} at `{}`",
+ self.status, self.final_url
+ )
+ }
+}
+
+impl std::error::Error for CliHttpStatusFailure {}
+
+fn http_status_failure(args: &FetchArgs, status: u16, final_url: &str) -> Option<anyhow::Error> {
+ if status < 400 || !(args.fail || args.fail_with_body) {
+ return None;
+ }
+ Some(with_fetch_context(
+ anyhow::Error::new(CliHttpStatusFailure {
+ status,
+ final_url: final_url.to_owned(),
+ }),
+ &args.url,
+ ))
+}
+
+fn with_http_status_context(
+ error: anyhow::Error,
+ args: &FetchArgs,
+ status: u16,
+ final_url: &str,
+) -> anyhow::Error {
+ let Some(http_failure) = http_status_failure(args, status, final_url) else {
+ return with_fetch_context(error, &args.url);
+ };
+ let reason = fetch_failure_reason(&error);
+ let http_reason = fetch_failure_reason(&http_failure);
+ if args.fail {
+ with_fetch_context_reason(http_failure, &args.url, format!("{http_reason}; {reason}"))
+ } else {
+ // Keeping the processing error as the source preserves its exit code.
+ // HTTP status is additional diagnostic context for --fail-with-body.
+ with_fetch_context_reason(error, &args.url, format!("{reason}; {http_reason}"))
+ }
+}
+
struct CliFetchFailureContext {
url: String,
reason: String,
@@ -250,14 +358,20 @@ fn with_fetch_context(error: anyhow::Error, url: &str) -> anyhow::Error {
if error.is::<CliFetchFailureContext>() {
return error;
}
- let reason = if let Some(failure) = error.downcast_ref::<NetworkFetchFailureContext>() {
+ let reason = fetch_failure_reason(&error);
+ with_fetch_context_reason(error, url, reason)
+}
+
+fn fetch_failure_reason(error: &anyhow::Error) -> String {
+ if let Some(fetch) = error.downcast_ref::<CliFetchFailureContext>() {
+ fetch.reason.clone()
+ } else if let Some(failure) = error.downcast_ref::<NetworkFetchFailureContext>() {
failure.reason().to_owned()
} else if let Some(timeout) = error.downcast_ref::<FetchReadinessTimeout>() {
timeout.to_string()
} else {
format!("{error:#}")
- };
- with_fetch_context_reason(error, url, reason)
+ }
}
fn with_fetch_context_reason(
@@ -286,6 +400,15 @@ pub fn write_error_report<W: Write>(writer: &mut W, error: &anyhow::Error) -> st
writeln!(writer, "Error: {error:#}")
}
+/// Selects the curl-compatible HTTP failure code without changing other CLI errors.
+pub fn error_exit_code(error: &anyhow::Error) -> ExitCode {
+ if error.is::<CliHttpStatusFailure>() {
+ ExitCode::from(22)
+ } else {
+ ExitCode::FAILURE
+ }
+}
+
fn one_line_reason(reason: &str) -> String {
reason.split_whitespace().collect::<Vec<_>>().join(" ")
}
diff --git a/moli/src/cli.rs b/moli/src/cli.rs
index 0f43d4a53..da4a11ce6 100644
--- a/moli/src/cli.rs
+++ b/moli/src/cli.rs
@@ -117,6 +117,17 @@ pub struct FetchArgs {
#[arg(short, long, value_enum)]
pub dump: Option<DumpFormat>,
+ /// Exit with code 22 if the final main-document HTTP status is >= 400,
+ /// suppressing response output and reporting the status to stderr.
+ #[arg(long, conflicts_with = "fail_with_body")]
+ pub fail: bool,
+
+ /// Exit with code 22 if the final main-document HTTP status is >= 400,
+ /// preserving the selected output format and reporting the status to stderr.
+ /// Readiness or output errors retain exit code 1 and include the known HTTP status.
+ #[arg(long, conflicts_with = "fail")]
+ pub fail_with_body: bool,
+
/// Evaluate one JavaScript expression after page readiness and write its
/// value to stdout. Promises are awaited. Strings are written as text;
/// other serializable values are written as compact JSON.
diff --git a/moli/src/main.rs b/moli/src/main.rs
index 70729443c..805bceec5 100644
--- a/moli/src/main.rs
+++ b/moli/src/main.rs
@@ -37,7 +37,7 @@ fn main() -> ExitCode {
Err(error) => {
let stderr = std::io::stderr();
let _ = moli::app::write_error_report(&mut stderr.lock(), &error);
- ExitCode::FAILURE
+ moli::app::error_exit_code(&error)
}
}
}
diff --git a/moli/tests/cli.rs b/moli/tests/cli.rs
index 419d2bf5a..df4e38ce5 100644
--- a/moli/tests/cli.rs
+++ b/moli/tests/cli.rs
@@ -74,6 +74,8 @@ fn parses_explicit_fetch_command_with_compatibility_flags() {
assert_eq!(
cli.command,
Commands::Fetch(Box::new(FetchArgs {
+ fail: false,
+ fail_with_body: false,
dump: Some(DumpFormat::SemanticTree),
eval: None,
eval_file: None,
@@ -160,6 +162,45 @@ fn parses_explicit_fetch_command_with_compatibility_flags() {
);
}
+#[test]
+fn parses_http_failure_flags_in_explicit_and_inferred_fetch_commands() {
+ for explicit_command in [true, false] {
+ for (flag, fail, fail_with_body) in
+ [("--fail", true, false), ("--fail-with-body", false, true)]
+ {
+ let raw = if explicit_command {
+ vec!["moli", "fetch", flag, "https://example.com"]
+ } else {
+ vec!["moli", "https://example.com", flag]
+ };
+ let cli = Cli::try_parse_from(normalize_args_for_compat(raw)).unwrap();
+ let Commands::Fetch(args) = cli.command else {
+ panic!("expected fetch command");
+ };
+ assert_eq!(args.fail, fail);
+ assert_eq!(args.fail_with_body, fail_with_body);
+ }
+ }
+}
+
+#[test]
+fn http_failure_flags_are_mutually_exclusive() {
+ for flags in [
+ ["--fail", "--fail-with-body"],
+ ["--fail-with-body", "--fail"],
+ ] {
+ let err = Cli::try_parse_from(normalize_args_for_compat([
+ "moli",
+ "fetch",
+ flags[0],
+ flags[1],
+ "https://example.com",
+ ]))
+ .unwrap_err();
+ assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
+ }
+}
+
#[test]
fn rejects_zero_runtime_transfer_limits() {
for flag in ["--http-max-concurrent", "--http-max-host-open"] {
@@ -423,6 +464,8 @@ fn infers_fetch_mode_from_bare_url() {
assert_eq!(
cli.command,
Commands::Fetch(Box::new(FetchArgs {
+ fail: false,
+ fail_with_body: false,
dump: None,
eval: None,
eval_file: None,
@@ -466,6 +509,8 @@ fn parses_bare_dump_with_explicit_fetch_command_and_defaults_to_html() {
assert_eq!(
cli.command,
Commands::Fetch(Box::new(FetchArgs {
+ fail: false,
+ fail_with_body: false,
dump: Some(DumpFormat::Html),
eval: None,
eval_file: None,
@@ -510,6 +555,8 @@ fn parses_header_flag_with_explicit_fetch_command() {
assert_eq!(
cli.command,
Commands::Fetch(Box::new(FetchArgs {
+ fail: false,
+ fail_with_body: false,
dump: None,
eval: None,
eval_file: None,
diff --git a/moli/tests/fetch_cli.rs b/moli/tests/fetch_cli.rs
index 8795d0b37..4e1662434 100644
--- a/moli/tests/fetch_cli.rs
+++ b/moli/tests/fetch_cli.rs
@@ -49,6 +49,8 @@ mod disable_css_boundaries;
mod disable_js;
#[path = "fetch_cli/eval.rs"]
mod eval;
+#[path = "fetch_cli/http_fail.rs"]
+mod http_fail;
#[path = "fetch_cli/markdown.rs"]
mod markdown;
#[path = "fetch_cli/readiness.rs"]
diff --git a/moli/tests/fetch_cli/http_fail.rs b/moli/tests/fetch_cli/http_fail.rs
new file mode 100644
index 000000000..f4dfdeb0d
--- /dev/null
+++ b/moli/tests/fetch_cli/http_fail.rs
@@ -0,0 +1,752 @@
+use anyhow::Result;
+use axum::{
+ Router,
+ extract::Path,
+ http::StatusCode,
+ response::{Html, IntoResponse, Redirect},
+ routing::get,
+};
+use base64::{Engine as _, engine::general_purpose::STANDARD};
+use clap::Parser;
+use moli::{app, cli::Cli};
+use serde_json::{Value, json};
+use std::{
+ io::{self, Write},
+ process::{Command, ExitCode, Output},
+ time::Duration,
+};
+use tokio::{
+ io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
+ net::TcpListener,
+ task::JoinHandle,
+};
+
+const HTML: &str =
+ "<!doctype html><title>HTTP fixture</title><h1>HTTP fixture</h1><p>response body</p>";
+const RAW_BODY: &[u8] = b"\0\xffraw HTTP error body";
+
+struct HttpFailureFixture {
+ base_url: String,
+ task: JoinHandle<()>,
+}
+
+impl HttpFailureFixture {
+ async fn spawn() -> Result<Self> {
+ let app = Router::new()
+ .route(
+ "/status/{status}",
+ get(|Path(status): Path<u16>| async move {
+ (StatusCode::from_u16(status).unwrap(), Html(HTML))
+ }),
+ )
+ .route(
+ "/raw",
+ get(|| async {
+ (
+ StatusCode::SERVICE_UNAVAILABLE,
+ [("content-type", "application/octet-stream")],
+ RAW_BODY,
+ )
+ }),
+ )
+ .route(
+ "/raw/{status}",
+ get(|Path(status): Path<u16>| async move {
+ (
+ StatusCode::from_u16(status).unwrap(),
+ [("content-type", "application/octet-stream")],
+ RAW_BODY,
+ )
+ }),
+ )
+ .route(
+ "/pdf/{status}",
+ get(|Path(status): Path<u16>| async move {
+ (
+ StatusCode::from_u16(status).unwrap(),
+ [("content-type", "application/pdf")],
+ b"%PDF-1.7\nHTTP fixture".as_slice(),
+ )
+ }),
+ )
+ .route(
+ "/empty",
+ get(|| async { Html("<!doctype html><body></body>") }),
+ )
+ .route(
+ "/empty-error",
+ get(|| async { (StatusCode::FORBIDDEN, Html("<!doctype html><body></body>")) }),
+ )
+ .route(
+ "/redirect/{status}",
+ get(|Path(status): Path<u16>| async move {
+ Redirect::temporary(&format!("/status/{status}"))
+ }),
+ )
+ .route(
+ "/challenge/{status}",
+ get(|Path(status): Path<u16>| async move {
+ (
+ StatusCode::FORBIDDEN,
+ Html(format!(
+ "<!doctype html><script>location.replace('/status/{status}')</script>"
+ )),
+ )
+ .into_response()
+ }),
+ );
+ let listener = TcpListener::bind("127.0.0.1:0").await?;
+ let base_url = format!("http://{}", listener.local_addr()?);
+ let task = tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+ Ok(Self { base_url, task })
+ }
+
+ async fn spawn_stalled_raw(status: u16, content_type: &str) -> Result<Self> {
+ let listener = TcpListener::bind("127.0.0.1:0").await?;
+ let base_url = format!("http://{}", listener.local_addr()?);
+ let headers = format!(
+ "HTTP/1.1 {status} Error\r\nContent-Type: {content_type}\r\nContent-Length: 1048576\r\n\r\n"
+ );
+ let task = tokio::spawn(async move {
+ let (stream, _) = listener.accept().await.unwrap();
+ let mut stream = BufReader::new(stream);
+ let mut line = String::new();
+ loop {
+ line.clear();
+ assert_ne!(stream.read_line(&mut line).await.unwrap(), 0);
+ if line == "\r\n" {
+ break;
+ }
+ }
+ stream
+ .get_mut()
+ .write_all(headers.as_bytes())
+ .await
+ .unwrap();
+ // Send no body. The client must cancel rather than wait for it.
+ match stream.read(&mut [0_u8; 1]).await {
+ Ok(0) => {}
+ Err(error) if error.kind() == io::ErrorKind::ConnectionReset => {}
+ result => panic!("expected download cancellation, got {result:?}"),
+ }
+ });
+ Ok(Self { base_url, task })
+ }
+
+ fn run(&self, path: &str, args: &[&str]) -> Result<Output> {
+ self.run_with_timeout(path, args, 5000)
+ }
+
+ fn run_with_timeout(&self, path: &str, args: &[&str], timeout_ms: u64) -> Result<Output> {
+ Ok(Command::new(env!("CARGO_BIN_EXE_moli"))
+ .env("MOLI_LAYOUT", "false")
+ .args(["fetch", "--http-no-proxy", "*", "--redirect-wait-ms", "0"])
+ .arg("--timeout")
+ .arg(timeout_ms.to_string())
+ .args(args)
+ .arg(format!("{}{path}", self.base_url))
+ .output()?)
+ }
+
+ fn assert_http_failure(&self, output: &Output, status: u16, final_path: &str) {
+ assert_eq!(output.status.code(), Some(22), "{output:?}");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains(&format!("HTTP status {status}")),
+ "{stderr}"
+ );
+ assert!(
+ stderr.contains(&format!("{}{final_path}", self.base_url)),
+ "{stderr}"
+ );
+ assert_eq!(stderr.lines().count(), 2, "{stderr}");
+ }
+}
+
+impl Drop for HttpFailureFixture {
+ fn drop(&mut self) {
+ self.task.abort();
+ }
+}
+
+struct FailingOutput {
+ fail_on_flush: bool,
+ written: Vec<u8>,
+}
+
+impl Write for FailingOutput {
+ fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
+ if !self.fail_on_flush {
+ return Err(io::Error::other("fixture write failure"));
+ }
+ self.written.extend_from_slice(bytes);
+ Ok(bytes.len())
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Err(io::Error::other("fixture flush failure"))
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn default_http_errors_keep_selected_output_and_exit_zero() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ for status in [403, 500] {
+ for dump in ["html", "markdown", "json"] {
+ let output = server.run(&format!("/status/{status}"), &["--dump", dump])?;
+ assert_eq!(output.status.code(), Some(0), "{output:?}");
+ assert!(output.stderr.is_empty(), "{output:?}");
+ match dump {
+ "markdown" => assert_eq!(output.stdout, b"# HTTP fixture\n\nresponse body"),
+ "json" => {
+ let value: Value = serde_json::from_slice(&output.stdout)?;
+ assert_eq!(value["status"], status);
+ assert!(value["html"].as_str().unwrap().contains("response body"));
+ }
+ _ => assert!(
+ String::from_utf8_lossy(&output.stdout).contains("<h1>HTTP fixture</h1>")
+ ),
+ }
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn fail_suppresses_output_and_exits_22_for_4xx_and_5xx() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ for status in [400, 403, 500, 599] {
+ let path = format!("/status/{status}");
+ let output = server.run(&path, &["--fail", "--dump", "markdown"])?;
+ server.assert_http_failure(&output, status, &path);
+ assert!(output.stdout.is_empty(), "{output:?}");
+ }
+ // Suppression also avoids evaluating an expression on the failed page.
+ let output = server.run(
+ "/status/403",
+ &[
+ "--fail",
+ "--eval",
+ "(() => { throw new Error('must not run'); })()",
+ ],
+ )?;
+ server.assert_http_failure(&output, 403, "/status/403");
+ assert!(output.stdout.is_empty(), "{output:?}");
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn fail_with_body_preserves_selected_output_format() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ for args in [
+ vec![],
+ vec!["--dump", "html"],
+ vec!["--dump", "markdown"],
+ vec!["--dump", "json"],
+ vec!["--dump", "semantic_tree"],
+ vec!["--dump", "semantic_tree_text"],
+ vec!["--eval", "document.querySelector('h1').textContent"],
+ ] {
+ let expected = server.run("/status/500", &args)?;
+ assert_eq!(expected.status.code(), Some(0), "{expected:?}");
+ assert!(!expected.stdout.is_empty(), "{args:?}");
+ let mut fail_args = args.clone();
+ fail_args.push("--fail-with-body");
+ let output = server.run("/status/500", &fail_args)?;
+ server.assert_http_failure(&output, 500, "/status/500");
+ assert_eq!(output.stdout, expected.stdout, "{args:?}");
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn fail_with_body_keeps_output_generation_errors_and_http_diagnostics() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ for (args, reason) in [
+ (
+ vec!["--eval", "document.querySelector('#app').textContent"],
+ "TypeError",
+ ),
+ (vec!["--dump", "screenshot"], "requires --layout"),
+ (vec!["--dump", "pdf"], "requires --layout"),
+ ] {
+ for status in [200, 403] {
+ let path = format!("/status/{status}");
+ for flag in [None, Some("--fail-with-body")] {
+ let mut fail_args = args.clone();
+ fail_args.extend(flag);
+ let output = server.run(&path, &fail_args)?;
+ assert_eq!(output.status.code(), Some(1), "{output:?}");
+ assert!(output.stdout.is_empty(), "{output:?}");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains(reason), "{stderr}");
+ assert_eq!(
+ stderr.contains("HTTP status 403"),
+ status == 403 && flag.is_some(),
+ "{stderr}"
+ );
+ assert_eq!(stderr.lines().count(), 2, "{stderr}");
+ }
+ let output = server.run(&path, &[args.as_slice(), &["--fail"]].concat())?;
+ if status == 403 {
+ server.assert_http_failure(&output, status, &path);
+ assert!(output.stdout.is_empty(), "{output:?}");
+ } else {
+ assert_eq!(output.status.code(), Some(1), "{output:?}");
+ }
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn fail_with_body_reports_http_status_when_raw_output_is_unsupported() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ for prefix in ["raw", "pdf"] {
+ for status in [403, 503] {
+ let path = format!("/{prefix}/{status}");
+ for (args, reason) in [
+ (
+ vec!["--dump", "markdown"],
+ "raw download output only supports",
+ ),
+ (vec!["--dump", "pdf"], "raw download output only supports"),
+ (vec!["--eval", "1"], "does not support --eval"),
+ (
+ vec!["--wait-selector", "#app"],
+ "does not support page wait options",
+ ),
+ (
+ vec!["--delay-ms", "1"],
+ "does not support page wait options",
+ ),
+ ] {
+ let mut fail_args = args;
+ fail_args.push("--fail-with-body");
+ let output = server.run(&path, &fail_args)?;
+ assert_eq!(output.status.code(), Some(1), "{output:?}");
+ assert!(output.stdout.is_empty(), "{output:?}");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains(reason), "{stderr}");
+ assert!(
+ stderr.contains(&format!("HTTP status {status}")),
+ "{stderr}"
+ );
+ assert!(
+ stderr.contains(&format!("{}{path}", server.base_url)),
+ "{stderr}"
+ );
+ assert_eq!(stderr.lines().count(), 2, "{stderr}");
+ }
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn http_failure_modes_preserve_write_and_flush_errors() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ for prefix in ["status", "raw"] {
+ for status in [200, 403] {
+ let url = format!("{}/{prefix}/{status}", server.base_url);
+ for flag in [None, Some("--fail"), Some("--fail-with-body")] {
+ for fail_on_flush in [false, true] {
+ let mut args = vec![
+ "moli",
+ "fetch",
+ "--http-no-proxy",
+ "*",
+ "--redirect-wait-ms",
+ "0",
+ ];
+ args.extend(flag);
+ args.push(&url);
+ let cli = Cli::try_parse_from(args)?;
+ let mut stdout = FailingOutput {
+ fail_on_flush,
+ written: Vec::new(),
+ };
+ let error = app::run_cli(&mut stdout, cli)
+ .await
+ .expect_err("HTTP or output error should fail");
+ let mut report = Vec::new();
+ app::write_error_report(&mut report, &error)?;
+ let report = String::from_utf8(report)?;
+ if status == 403 && flag == Some("--fail") {
+ assert_eq!(app::error_exit_code(&error), ExitCode::from(22), "{report}");
+ assert!(stdout.written.is_empty(), "{report}");
+ assert!(!report.contains("fixture"), "{report}");
+ } else {
+ assert_eq!(app::error_exit_code(&error), ExitCode::FAILURE, "{report}");
+ assert!(error.downcast_ref::<io::Error>().is_some(), "{error:?}");
+ let phase = if fail_on_flush { "flush" } else { "write" };
+ assert!(
+ report.contains(&format!("fixture {phase} failure")),
+ "{report}"
+ );
+ if fail_on_flush {
+ assert!(!stdout.written.is_empty(), "{report}");
+ }
+ }
+ assert_eq!(
+ report.contains("HTTP status 403"),
+ status == 403 && flag.is_some(),
+ "{report}"
+ );
+ assert_eq!(report.lines().count(), 2, "{report}");
+ }
+ }
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn http_failure_modes_handle_raw_binary_and_json_output() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ for args in [vec![], vec!["--dump", "json"]] {
+ let expected = server.run("/raw", &args)?;
+ assert_eq!(expected.status.code(), Some(0), "{expected:?}");
+ if args.is_empty() {
+ assert_eq!(expected.stdout, RAW_BODY);
+ } else {
+ let value: Value = serde_json::from_slice(&expected.stdout)?;
+ assert_eq!(value["status"], 503);
+ assert_eq!(
+ STANDARD.decode(value["body_base64"].as_str().unwrap())?,
+ RAW_BODY
+ );
+ }
+ for flag in ["--fail", "--fail-with-body"] {
+ let mut fail_args = args.clone();
+ fail_args.push(flag);
+ let output = server.run("/raw", &fail_args)?;
+ server.assert_http_failure(&output, 503, "/raw");
+ if flag == "--fail" {
+ assert!(output.stdout.is_empty(), "{output:?}");
+ } else {
+ assert_eq!(output.stdout, expected.stdout);
+ }
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn fail_checks_raw_http_status_before_output_format_and_page_options() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ for prefix in ["raw", "pdf"] {
+ for status in [403, 503] {
+ let path = format!("/{prefix}/{status}");
+ for args in [
+ vec!["--dump", "markdown"],
+ vec!["--dump", "pdf"],
+ vec!["--dump", "html"],
+ vec!["--dump", "markdown", "--wait-selector", "#app"],
+ vec!["--eval", "document.querySelector('#app').textContent"],
+ ] {
+ let mut fail_args = args;
+ fail_args.push("--fail");
+ let output = server.run(&path, &fail_args)?;
+ server.assert_http_failure(&output, status, &path);
+ assert!(output.stdout.is_empty(), "{output:?}");
+ }
+ }
+ // Successful raw responses still have to satisfy output constraints.
+ for flag in [None, Some("--fail"), Some("--fail-with-body")] {
+ let mut args = vec!["--dump", "markdown"];
+ args.extend(flag);
+ let output = server.run(&format!("/{prefix}/200"), &args)?;
+ assert_eq!(output.status.code(), Some(1), "{output:?}");
+ assert!(output.stdout.is_empty(), "{output:?}");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("raw download output only supports"),
+ "{stderr}"
+ );
+ assert!(!stderr.contains("HTTP status"), "{stderr}");
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn fail_cancels_raw_http_errors_without_waiting_for_the_body() -> Result<()> {
+ for (status, content_type) in [(403, "application/octet-stream"), (503, "application/pdf")] {
+ for wait_until in ["done", "networkidle"] {
+ let mut server = HttpFailureFixture::spawn_stalled_raw(status, content_type).await?;
+ let mut command = Command::new(env!("CARGO_BIN_EXE_moli"));
+ command
+ .args([
+ "fetch",
+ "--fail",
+ "--dump",
+ "markdown",
+ "--http-no-proxy",
+ "*",
+ "--redirect-wait-ms",
+ "0",
+ "--timeout",
+ "5000",
+ "--wait-until",
+ wait_until,
+ ])
+ .arg(format!("{}/raw", server.base_url));
+ let output = tokio::time::timeout(
+ Duration::from_secs(2),
+ tokio::task::spawn_blocking(move || command.output()),
+ )
+ .await
+ .expect("--fail must return before the raw body timeout")??;
+ server.assert_http_failure(&output, status, "/raw");
+ assert!(output.stdout.is_empty(), "{output:?}");
+ tokio::time::timeout(Duration::from_secs(2), &mut server.task)
+ .await
+ .expect("the HTTP download must be cancelled")?;
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn http_failure_modes_accept_success_3xx_and_empty_markdown() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ for flag in [None, Some("--fail"), Some("--fail-with-body")] {
+ let mut args = vec!["--dump", "markdown"];
+ args.extend(flag);
+ let output = server.run("/empty-error", &args)?;
+ assert!(output.stdout.is_empty(), "{output:?}");
+ if flag.is_some() {
+ server.assert_http_failure(&output, 403, "/empty-error");
+ } else {
+ assert_eq!(output.status.code(), Some(0), "{output:?}");
+ assert!(output.stderr.is_empty(), "{output:?}");
+ }
+ }
+ for flag in ["--fail", "--fail-with-body"] {
+ for path in ["/status/200", "/status/399", "/empty"] {
+ let output = server.run(path, &[flag, "--dump", "markdown"])?;
+ assert_eq!(output.status.code(), Some(0), "{output:?}");
+ assert!(output.stderr.is_empty(), "{output:?}");
+ if path == "/empty" {
+ assert!(output.stdout.is_empty(), "{output:?}");
+ } else {
+ assert_eq!(output.stdout, b"# HTTP fixture\n\nresponse body");
+ }
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn http_failure_modes_preserve_binary_dump_formats() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ for dump in ["screenshot", "screenshot_full", "pdf"] {
+ for flag in ["--fail", "--fail-with-body"] {
+ let output = server.run("/status/403", &[flag, "--layout", "--dump", dump])?;
+ server.assert_http_failure(&output, 403, "/status/403");
+ if flag == "--fail" {
+ assert!(output.stdout.is_empty(), "{dump}: {output:?}");
+ } else {
+ let signature: &[u8] = if dump == "pdf" {
+ b"%PDF-"
+ } else {
+ b"\x89PNG\r\n\x1a\n"
+ };
+ assert!(output.stdout.starts_with(signature), "{dump}: {output:?}");
+ }
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn http_failure_modes_use_final_status_after_http_and_script_redirects() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ for flag in ["--fail", "--fail-with-body"] {
+ for prefix in ["redirect", "challenge"] {
+ for status in [200, 500] {
+ let output = server.run(
+ &format!("/{prefix}/{status}"),
+ &[flag, "--dump", "json", "--wait-selector", "h1"],
+ )?;
+ if status == 200 {
+ assert_eq!(output.status.code(), Some(0), "{output:?}");
+ assert!(output.stderr.is_empty(), "{output:?}");
+ } else {
+ server.assert_http_failure(&output, 500, "/status/500");
+ if flag == "--fail" {
+ assert!(output.stdout.is_empty(), "{output:?}");
+ continue;
+ }
+ }
+ let value: Value = serde_json::from_slice(&output.stdout)?;
+ assert_eq!(value["status"], status);
+ assert_eq!(
+ value["final_url"],
+ format!("{}/status/{status}", server.base_url)
+ );
+ }
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn http_failure_modes_report_status_when_page_readiness_times_out() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ for status in [403, 503] {
+ let path = format!("/status/{status}");
+ for (wait_option, condition, phase) in [
+ ("--wait-selector", "#app", "waiting for a selector"),
+ ("--wait-script", "false", "waiting for a script"),
+ (
+ "--wait-response-url",
+ "/missing-api",
+ "waiting for a subresource response",
+ ),
+ ] {
+ for flag in ["--fail", "--fail-with-body"] {
+ let output = server.run_with_timeout(
+ &path,
+ &[flag, "--dump", "markdown", wait_option, condition],
+ 1000,
+ )?;
+ if flag == "--fail" {
+ server.assert_http_failure(&output, status, &path);
+ } else {
+ assert_eq!(output.status.code(), Some(1), "{output:?}");
+ }
+ assert!(output.stdout.is_empty(), "{output:?}");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("fetch readiness timed out"), "{stderr}");
+ assert!(stderr.contains(phase), "{stderr}");
+ assert!(
+ stderr.contains(&format!("HTTP status {status}")),
+ "{stderr}"
+ );
+ assert!(
+ stderr.contains(&format!("{}{path}", server.base_url)),
+ "{stderr}"
+ );
+ assert_eq!(stderr.lines().count(), 2, "{stderr}");
+ }
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn http_failure_modes_use_redirect_status_when_readiness_fails() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ for flag in ["--fail", "--fail-with-body"] {
+ for prefix in ["redirect", "challenge"] {
+ for status in [200, 500] {
+ let output = server.run_with_timeout(
+ &format!("/{prefix}/{status}"),
+ &[flag, "--dump", "markdown", "--wait-selector", "#app"],
+ 1000,
+ )?;
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("waiting for a selector"), "{stderr}");
+ assert!(output.stdout.is_empty(), "{output:?}");
+ if status == 500 && flag == "--fail" {
+ server.assert_http_failure(&output, status, "/status/500");
+ } else {
+ assert_eq!(output.status.code(), Some(1), "{output:?}");
+ }
+ if status == 200 {
+ assert!(!stderr.contains("HTTP status"), "{stderr}");
+ } else {
+ assert!(stderr.contains("HTTP status 500"), "{stderr}");
+ assert!(
+ stderr.contains(&format!("{}/status/500", server.base_url)),
+ "{stderr}"
+ );
+ }
+ assert!(!stderr.contains("HTTP status 403"), "{stderr}");
+ }
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn http_failure_modes_report_status_when_readiness_script_throws() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ for status in [200, 403] {
+ let path = format!("/status/{status}");
+ for flag in ["--fail", "--fail-with-body"] {
+ let output = server.run(
+ &path,
+ &[
+ flag,
+ "--wait-script",
+ "(() => { throw new Error('readiness failed'); })()",
+ ],
+ )?;
+ if status == 403 && flag == "--fail" {
+ server.assert_http_failure(&output, status, &path);
+ } else {
+ assert_eq!(output.status.code(), Some(1), "{output:?}");
+ }
+ assert!(output.stdout.is_empty(), "{output:?}");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("readiness failed"), "{stderr}");
+ assert_eq!(
+ stderr.contains("HTTP status 403"),
+ status == 403,
+ "{stderr}"
+ );
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn http_failure_modes_preserve_fetch_and_xhr_error_responses() -> Result<()> {
+ let server = HttpFailureFixture::spawn().await?;
+ let expression = r#"(async () => {
+ const response = await fetch('/status/403');
+ const text = await response.text();
+ const xhr = await new Promise((resolve, reject) => {
+ const request = new XMLHttpRequest();
+ request.open('GET', '/status/500');
+ request.onload = () => resolve({status: request.status, body: request.responseText.includes('response body')});
+ request.onerror = reject;
+ request.send();
+ });
+ return {status: response.status, ok: response.ok, body: text.includes('response body'), xhr};
+ })()"#;
+ for flag in ["--fail", "--fail-with-body"] {
+ let output = server.run("/status/200", &[flag, "--eval", expression])?;
+ assert_eq!(output.status.code(), Some(0), "{output:?}");
+ assert!(output.stderr.is_empty(), "{output:?}");
+ let value: Value = serde_json::from_slice(&output.stdout)?;
+ assert_eq!(
+ value,
+ json!({
+ "status": 403,
+ "ok": false,
+ "body": true,
+ "xhr": {"status": 500, "body": true}
+ })
+ );
+ }
+ Ok(())
+}
+
+#[test]
+fn http_failure_modes_keep_exit_code_one_for_non_http_errors() -> Result<()> {
+ for flag in ["--fail", "--fail-with-body"] {
+ let output = Command::new(env!("CARGO_BIN_EXE_moli"))
+ .args(["fetch", flag, "https://["])
+ .output()?;
+ assert_eq!(output.status.code(), Some(1), "{output:?}");
+ assert!(output.stdout.is_empty(), "{output:?}");
+ assert!(!output.stderr.is_empty(), "{output:?}");
+ }
+ Ok(())
+}