Skip to content
Closed
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
79 changes: 45 additions & 34 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}")]
Expand Down Expand Up @@ -92,7 +98,10 @@ async fn read_body(mut response: reqwest::Response) -> Result<Vec<u8>, 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;
Expand All @@ -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<u16> {
match self {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -369,7 +388,7 @@ impl Api {
}

async fn get(&self, url: Url) -> Result<serde_json::Value, ApiError> {
let reply = self.read(url, "application/json").await?;
let reply = self.read(url, MEDIA_TYPE_JSON).await?;
self.decode(&reply.body)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No try_decode here, as a successful read asserts that the request succeeded.

Can be treated as micro-optimization and switched to try_decode nonetheless.

}

Expand All @@ -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(
Expand Down Expand Up @@ -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(
Expand All @@ -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<T: DeserializeOwned>(&self, reply: &Reply) -> Result<T, ApiError> {
// 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,
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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" {
Expand Down
24 changes: 11 additions & 13 deletions src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -112,8 +113,8 @@ pub(crate) async fn export(api: &Api, args: &ExportArgs) -> anyhow::Result<Verdi
bail!("--group-by is available only for finding_outcomes");
}
let (format, accept) = match args.format {
Format::Csv => ("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()),
Expand All @@ -127,19 +128,16 @@ pub(crate) async fn export(api: &Api, args: &ExportArgs) -> anyhow::Result<Verdi
query.push(("group_by", group.clone()));
}
let reply = api.export(args.dataset.name(), &query, accept).await?;
let content_type = reply
if !has_content_type(&reply.headers, accept) {
bail!("the server returned an unsupported export format");
}
if reply
.headers
.get("content-type")
.get("x-proofline-export-version")
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
if content_type.split(';').next().map(str::trim) != Some(accept)
|| reply
.headers
.get("x-proofline-export-version")
.and_then(|v| v.to_str().ok())
!= Some("1")
!= Some("1")
{
bail!("the server returned an unsupported export format or version");
bail!("the server returned an unsupported export version");
}
let horizon = reply
.headers
Expand Down