diff --git a/src/api.rs b/src/api.rs index f908670..05a073a 100644 --- a/src/api.rs +++ b/src/api.rs @@ -25,6 +25,12 @@ const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); const READ_ATTEMPTS: u32 = 4; const MAX_RETRY_AFTER: u64 = 60; +// Media types +pub(crate) const MEDIA_TYPE_CSV: &str = "text/csv"; +const MEDIA_TYPE_JSON: &str = "application/json"; +pub(crate) const MEDIA_TYPE_NDJSON: &str = "application/x-ndjson"; +const MEDIA_TYPE_SERVER_SENT_EVENT: &str = "text/event-stream"; + #[derive(Debug, thiserror::Error)] pub enum ApiError { #[error("{origin} returned HTTP {status}: {detail}")] @@ -92,7 +98,10 @@ async fn read_body(mut response: reqwest::Response) -> Result, BodyError Ok(body) } -fn json_content_type(headers: &header::HeaderMap) -> bool { +/// Checks if a response headers signals a given content type +/// +/// It's considered a mismatch, if the headers have multiple content type headers. +pub(crate) fn has_content_type(headers: &header::HeaderMap, expected: &str) -> bool { let mut values = headers.get_all(header::CONTENT_TYPE).iter(); let Some(value) = values.next() else { return false; @@ -102,10 +111,17 @@ fn json_content_type(headers: &header::HeaderMap) -> bool { value .split(';') .next() - .is_some_and(|media| media.trim().eq_ignore_ascii_case("application/json")) + .is_some_and(|media| media.trim().eq_ignore_ascii_case(expected)) }) } +/// Checks if a response headers signals a JSON type +/// +/// It's considered a mismatch, if the headers have multiple content type headers. +fn json_content_type(headers: &header::HeaderMap) -> bool { + has_content_type(headers, MEDIA_TYPE_JSON) +} + impl ApiError { pub const fn status(&self) -> Option { match self { @@ -231,8 +247,11 @@ impl Http { .client .post(self.origin.join(["mcp"])) .bearer_auth(token.expose_secret()) - .header(header::CONTENT_TYPE, "application/json") - .header(header::ACCEPT, "application/json, text/event-stream") + .header(header::CONTENT_TYPE, MEDIA_TYPE_JSON) + .header( + header::ACCEPT, + [MEDIA_TYPE_JSON, MEDIA_TYPE_SERVER_SENT_EVENT].join(","), + ) .header(header::ORIGIN, self.origin.as_key()) .body(body); if let Some(protocol) = protocol { @@ -334,7 +353,7 @@ impl Api { .client .request(method, url) .bearer_auth(self.token.expose_secret()) - .header(header::ACCEPT, "application/json") + .header(header::ACCEPT, MEDIA_TYPE_JSON) } /// GET with up to three retries on 429 and 503, honoring `Retry-After` up @@ -369,7 +388,7 @@ impl Api { } async fn get(&self, url: Url) -> Result { - let reply = self.read(url, "application/json").await?; + let reply = self.read(url, MEDIA_TYPE_JSON).await?; self.decode(&reply.body) } @@ -386,10 +405,7 @@ impl Api { .http .send(self.request(Method::POST, self.url(path)).json(body)) .await?; - if !reply.status.is_success() { - return Err(self.http.problem(&reply)); - } - self.decode(&reply.body) + self.try_decode(&reply) } pub(crate) async fn list_page( @@ -442,10 +458,7 @@ impl Api { self.url(&["reviews", &review.to_string(), "rerun"]), )) .await?; - if !reply.status.is_success() { - return Err(self.http.problem(&reply)); - } - self.decode(&reply.body) + self.try_decode(&reply) } pub(crate) async fn export( @@ -464,6 +477,19 @@ impl Api { serde_json::from_slice(body).map_err(|error| self.http.protocol(error.to_string())) } + /// Decode a successful reply from JSON to `T` + /// + /// `Err`, if the reply did not flag success or the decoding fails. + fn try_decode(&self, reply: &Reply) -> Result { + // Err out if the reply was not successful + if !reply.status.is_success() { + return Err(self.http.problem(reply)); + } + + // At this point, the reply was successful, so we can decode + self.decode(&reply.body) + } + /// Fetches a review as the raw document and its typed reading. pub async fn review( &self, @@ -553,10 +579,7 @@ impl Api { None => request, }; let (reply, _) = self.http.send(request).await?; - if reply.status.is_success() { - return self.decode(&reply.body); - } - Err(self.http.problem(&reply)) + self.try_decode(&reply) } /// Requests a review of a patch on a base commit. One attempt; the server @@ -572,10 +595,7 @@ impl Api { .http .send(self.request(Method::POST, url).json(request)) .await?; - if reply.status.is_success() { - return self.decode(&reply.body); - } - Err(self.http.problem(&reply)) + self.try_decode(&reply) } /// Uploads reports for one exact tested commit. Both a new report and an @@ -609,10 +629,7 @@ impl Api { .http .send(self.request(Method::POST, url).json(request)) .await?; - if reply.status.is_success() { - return self.decode(&reply.body); - } - Err(self.http.problem(&reply)) + self.try_decode(&reply) } /// Requests a review of the change from one pushed commit to another. One @@ -628,10 +645,7 @@ impl Api { .http .send(self.request(Method::POST, url).json(request)) .await?; - if reply.status.is_success() { - return self.decode(&reply.body); - } - Err(self.http.problem(&reply)) + self.try_decode(&reply) } /// Stops the holder's own local review in one bounded attempt. A refusal @@ -645,10 +659,7 @@ impl Api { .http .send(self.request(Method::POST, self.url(&["reviews", &id, "stop"]))) .await?; - if !reply.status.is_success() { - return Err(self.http.problem(&reply)); - } - let raw: serde_json::Value = self.decode(&reply.body)?; + let raw: serde_json::Value = self.try_decode(&reply)?; let stopped: StopResponse = serde_json::from_value(raw.clone()) .map_err(|error| self.http.protocol(error.to_string()))?; if stopped.review_id != review_id || stopped.status != "STOPPED" { diff --git a/src/tools.rs b/src/tools.rs index 962f633..37f2f2d 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -5,7 +5,8 @@ use anyhow::{Context as _, bail}; use clap::{Args, Subcommand, ValueEnum}; use uuid::Uuid; -use crate::{OutputArgs, OutputFormat, RepositoryArgs, Verdict, api::Api, say, show}; +use crate::api::{Api, MEDIA_TYPE_CSV, MEDIA_TYPE_NDJSON, has_content_type}; +use crate::{OutputArgs, OutputFormat, RepositoryArgs, Verdict, say, show}; #[derive(Debug, Args)] pub(crate) struct RerunArgs { @@ -112,8 +113,8 @@ pub(crate) async fn export(api: &Api, args: &ExportArgs) -> anyhow::Result ("csv", "text/csv"), - Format::Ndjson => ("ndjson", "application/x-ndjson"), + Format::Csv => ("csv", MEDIA_TYPE_CSV), + Format::Ndjson => ("ndjson", MEDIA_TYPE_NDJSON), }; let mut query = vec![ ("from", args.from.clone()), @@ -127,19 +128,16 @@ pub(crate) async fn export(api: &Api, args: &ExportArgs) -> anyhow::Result