//! The one place the publisher talks to the network. //! //! `run` and `init` stay offline. Only `uteri sync` uses this module, and it //! shells out to the system `curl` so the publisher keeps its small Rust //! dependency set. use std::io::Write; use std::process::{Command, Stdio}; /// One JSON POST. pub struct Request { pub url: String, pub bearer: Option, pub body: String, } /// One HTTP response. A non-2xx status is not an error here: the sync /// layer prints the status and body together. pub struct Response { pub status: u16, pub body: String, } impl Response { pub fn success(&self) -> bool { (200..300).contains(&self.status) } } /// A JSON POST transport. Tests use a fake. pub trait Transport { fn post(&self, request: &Request) -> Result; } /// The production transport: the system `curl`. pub struct Curl; impl Transport for Curl { fn post(&self, request: &Request) -> Result { let mut command = Command::new("curl"); command .arg("--silent") .arg("--show-error") .arg("--connect-timeout") .arg("10") .arg("--max-time") .arg("120") .arg("--header") .arg("Content-Type: application/json") .arg("--data-binary") .arg("@-") .arg("--write-out") .arg("\n%{http_code}") .arg(&request.url); if let Some(token) = &request.bearer { command .arg("--header") .arg(format!("Authorization: Bearer {token}")); } let mut child = command .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .map_err(|error| format!("curl is required for sync and could not run: {error}"))?; if let Some(mut stdin) = child.stdin.take() { if let Err(error) = stdin.write_all(request.body.as_bytes()) { let _ = child.wait(); return Err(format!("{}: {error}", request.url)); } } let output = child .wait_with_output() .map_err(|error| format!("{}: {error}", request.url))?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); let detail = stderr.trim(); return Err(if detail.is_empty() { format!("curl {}: exit status {}", request.url, output.status) } else { format!("curl {}: {detail}", request.url) }); } let stdout = String::from_utf8_lossy(&output.stdout); split_output(&stdout).map_err(|error| format!("{}: {error}", request.url)) } } /// Split curl's `\n` output. fn split_output(stdout: &str) -> Result { let Some((body, status)) = stdout.rsplit_once('\n') else { return Err("curl returned no HTTP status".to_string()); }; let status = status .trim() .parse::() .map_err(|_| format!("curl returned an invalid HTTP status: {status:?}"))?; Ok(Response { status, body: body.to_string(), }) } #[cfg(test)] mod tests { use super::*; #[test] fn splits_curl_output() { let response = split_output("{\"ok\":true}\n200").unwrap(); assert_eq!(response.status, 200); assert_eq!(response.body, "{\"ok\":true}"); assert!(response.success()); } #[test] fn keeps_a_trailing_newline_in_the_body() { let response = split_output("error\n\n403").unwrap(); assert_eq!(response.status, 403); assert_eq!(response.body, "error\n"); assert!(!response.success()); } #[test] fn rejects_a_missing_or_invalid_status() { assert!(split_output("body").is_err()); assert!(split_output("body\nnope").is_err()); } }