use std::{fmt, sync::Arc, time::Duration};
use futures_util::StreamExt;
use reqwest::{Client, Method};
use serde::de::DeserializeOwned;
use serde_json::Value;
use zeroize::Zeroizing;
use crate::{Error, Result, RuntimeMode};
#[derive(Clone)]
pub(crate) struct Secret(Arc<Zeroizing<String>>);
impl Secret {
pub fn new(value: String) -> Self {
Self(Arc::new(Zeroizing::new(value)))
}
pub fn expose(&self) -> &str {
self.0.as_str()
}
}
impl fmt::Debug for Secret {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("Secret([REDACTED])")
}
}
#[derive(Clone, Debug)]
pub(crate) struct Core {
pub runtime_url: String,
pub hub_url: String,
pub api_key: Option<Secret>,
pub mode: RuntimeMode,
pub client: Client,
pub headers: reqwest::header::HeaderMap,
pub max_response_bytes: Option<usize>,
}
impl Core {
pub fn new(
runtime_url: String,
hub_url: String,
api_key: Option<String>,
mode: RuntimeMode,
timeout: Duration,
) -> Result<Self> {
let client = Client::builder()
.timeout(timeout)
.connect_timeout(Duration::from_secs(15))
.pool_idle_timeout(Duration::from_secs(90))
.build()?;
Ok(Self {
runtime_url: runtime_url.trim_end_matches('/').to_owned(),
hub_url: hub_url.trim_end_matches('/').to_owned(),
api_key: api_key
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
.map(Secret::new),
mode,
client,
headers: reqwest::header::HeaderMap::new(),
max_response_bytes: None,
})
}
pub async fn json<T: DeserializeOwned>(
&self,
base: &str,
method: Method,
path: &str,
body: Option<&Value>,
) -> Result<T> {
let mut request = self
.client
.request(method, format!("{}{}", base.trim_end_matches('/'), path))
.headers(self.headers.clone())
.bearer_auth(self.require_api_key()?);
if let Some(value) = body {
request = request.json(value);
}
let response = request.send().await?;
let status = response.status();
let bytes = self.response_body(response).await?;
let payload = serde_json::from_slice::<Value>(&bytes).ok();
if !status.is_success() {
return Err(Error::api(status, payload));
}
serde_json::from_slice(&bytes)
.map_err(|error| Error::Protocol(format!("invalid JSON response: {error}")))
}
pub fn check_response(&self, response: &reqwest::Response) -> Result<()> {
if let Some(limit) = self.max_response_bytes {
if response
.headers()
.get(reqwest::header::CONTENT_ENCODING)
.is_some_and(|value| {
!value
.to_str()
.is_ok_and(|encoding| encoding.trim().eq_ignore_ascii_case("identity"))
})
{
return Err(Error::Protocol(
"Unsupported response content encoding".into(),
));
}
if let Some(length) = response.headers().get(reqwest::header::CONTENT_LENGTH) {
let length = length
.to_str()
.ok()
.and_then(|value| value.parse::<u64>().ok())
.ok_or_else(|| Error::Protocol("Invalid response Content-Length".into()))?;
if length > limit as u64 {
return Err(Error::Protocol(
"Response exceeds configured byte limit".into(),
));
}
}
}
Ok(())
}
pub fn response_size(&self, received: usize, additional: usize) -> Result<usize> {
let total = received
.checked_add(additional)
.ok_or_else(|| Error::Protocol("Response exceeds configured byte limit".into()))?;
if self.max_response_bytes.is_some_and(|limit| total > limit) {
return Err(Error::Protocol(
"Response exceeds configured byte limit".into(),
));
}
Ok(total)
}
pub async fn response_body(&self, response: reqwest::Response) -> Result<Vec<u8>> {
self.check_response(&response)?;
let mut chunks = response.bytes_stream();
let mut body = Vec::new();
while let Some(chunk) = chunks.next().await {
let chunk = chunk?;
self.response_size(body.len(), chunk.len())?;
body.extend_from_slice(&chunk);
}
Ok(body)
}
pub fn require_api_key(&self) -> Result<&str> {
self.api_key.as_ref().map(Secret::expose).ok_or_else(|| {
Error::missing_api_key(
"Marona Developer Key is required.\n\nProvide it through the SDK configuration or set the MARONA_API_KEY environment variable.\n\nCreate/manage developer keys from the Marona Developer Portal.",
)
})
}
}