use std::time::Duration;
use crate::{RunAgentInput, SSE_MEDIA_TYPE};
use reqwest::header::{ACCEPT, HeaderMap, HeaderName, HeaderValue};
use reqwest::{Client, Url};
use crate::client::error::{Error, Result};
use crate::client::transport::sse::decode_events;
use crate::client::transport::{EventStream, Transport, TransportFuture};
const MAX_ERROR_BODY: usize = 2048;
#[derive(Clone, Debug)]
pub struct HttpTransport {
client: Client,
url: Url,
headers: HeaderMap,
timeout: Option<Duration>,
}
impl HttpTransport {
pub fn new(url: impl AsRef<str>) -> Result<Self> {
Self::builder(url).build()
}
pub fn builder(url: impl AsRef<str>) -> HttpTransportBuilder {
HttpTransportBuilder::new(url)
}
pub fn url(&self) -> &Url {
&self.url
}
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
}
impl Transport for HttpTransport {
fn run(&self, input: RunAgentInput) -> TransportFuture {
let client = self.client.clone();
let url = self.url.clone();
let headers = self.headers.clone();
let timeout = self.timeout;
Box::pin(async move {
let mut request = client.post(url).headers(headers).json(&input);
if let Some(timeout) = timeout {
request = request.timeout(timeout);
}
let response = request.send().await.map_err(Error::transport)?;
let status = response.status();
if !status.is_success() {
let body = response.text().await.unwrap_or_default();
return Err(Error::Http {
status: status.as_u16(),
body: body.chars().take(MAX_ERROR_BODY).collect(),
});
}
Ok(Box::pin(decode_events(response.bytes_stream())) as EventStream)
})
}
}
#[derive(Clone, Debug)]
pub struct HttpTransportBuilder {
url: String,
headers: Vec<(String, String)>,
timeout: Option<Duration>,
connect_timeout: Option<Duration>,
client: Option<Client>,
}
impl HttpTransportBuilder {
pub fn new(url: impl AsRef<str>) -> Self {
Self {
url: url.as_ref().to_owned(),
headers: Vec::new(),
timeout: None,
connect_timeout: None,
client: None,
}
}
#[must_use]
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
#[must_use]
pub fn headers<K, V>(mut self, headers: impl IntoIterator<Item = (K, V)>) -> Self
where
K: Into<String>,
V: Into<String>,
{
self.headers
.extend(headers.into_iter().map(|(k, v)| (k.into(), v.into())));
self
}
#[must_use]
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
#[must_use]
pub fn connect_timeout(mut self, timeout: Duration) -> Self {
self.connect_timeout = Some(timeout);
self
}
#[must_use]
pub fn client(mut self, client: Client) -> Self {
self.client = Some(client);
self
}
pub fn build(self) -> Result<HttpTransport> {
let url = Url::parse(&self.url)
.map_err(|error| Error::Config(format!("invalid URL {:?}: {error}", self.url)))?;
let mut headers = HeaderMap::with_capacity(self.headers.len() + 1);
headers.insert(ACCEPT, HeaderValue::from_static(SSE_MEDIA_TYPE));
for (name, value) in self.headers {
let name = HeaderName::try_from(name.as_str())
.map_err(|error| Error::Config(format!("invalid header name {name:?}: {error}")))?;
let value = HeaderValue::try_from(value.as_str()).map_err(|error| {
Error::Config(format!("invalid value for header {name:?}: {error}"))
})?;
headers.insert(name, value);
}
let client = match self.client {
Some(client) => client,
None => {
let mut builder = Client::builder();
if let Some(timeout) = self.connect_timeout {
builder = builder.connect_timeout(timeout);
}
builder.build().map_err(|error| {
Error::Config(format!("could not build HTTP client: {error}"))
})?
}
};
Ok(HttpTransport {
client,
url,
headers,
timeout: self.timeout,
})
}
}