use crate::{Error, Result};
const MAX_BODY_BYTES: usize = 64 * 1024 * 1024;
pub fn client() -> Result<reqwest::Client> {
Ok(reqwest::Client::builder()
.https_only(true)
.redirect(reqwest::redirect::Policy::limited(3))
.build()?)
}
pub fn github() -> Result<octocrab::Octocrab> {
let builder = octocrab::Octocrab::builder();
let builder = match std::env::var("ADNV_GITHUB_TOKEN") {
Ok(token) => builder.personal_token(token),
Err(_) => builder,
};
builder
.build()
.map_err(|err| crate::Error::github(err, "Could not build GitHub client"))
}
pub async fn body(response: reqwest::Response) -> Result<String> {
use futures::TryStreamExt as _;
let url = response.url().clone();
let mut stream = response.bytes_stream();
let mut body = Vec::new();
while let Some(chunk) = stream.try_next().await? {
if body.len() + chunk.len() > MAX_BODY_BYTES {
return Err(Error::io(
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("response from {url} exceeds {MAX_BODY_BYTES} bytes"),
),
"Refusing to read an oversized response",
));
}
body.extend_from_slice(&chunk);
}
String::from_utf8(body).map_err(|err| {
Error::io(
std::io::Error::new(std::io::ErrorKind::InvalidData, err),
format!("Response from {url} is not valid UTF-8"),
)
})
}