ag_ui/client/transport/
http.rs1use futures_util::StreamExt;
9use std::time::Duration;
10
11use crate::{RunAgentInput, SSE_MEDIA_TYPE};
12use reqwest::header::{ACCEPT, CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue};
13use reqwest::{Client, Url};
14
15use crate::client::error::{Error, Result};
16use crate::client::transport::sse::decode_raw_events;
17use crate::client::transport::{Transport, TransportFuture, TransportStream};
18
19const MAX_ERROR_BODY: usize = 2048;
21const ERROR_BODY_TIMEOUT: Duration = Duration::from_secs(1);
23
24#[derive(Clone)]
26pub struct HttpTransport {
27 client: Client,
28 url: Url,
29 headers: HeaderMap,
30 timeout: Option<Duration>,
31}
32
33impl std::fmt::Debug for HttpTransport {
34 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35 f.debug_struct("HttpTransport")
36 .field("timeout", &self.timeout)
37 .field("headers", &"<redacted>")
38 .finish_non_exhaustive()
39 }
40}
41
42impl HttpTransport {
43 pub fn new(url: impl AsRef<str>) -> Result<Self> {
51 Self::builder(url).build()
52 }
53
54 pub fn builder(url: impl AsRef<str>) -> HttpTransportBuilder {
56 HttpTransportBuilder::new(url)
57 }
58
59 pub fn url(&self) -> &Url {
61 &self.url
62 }
63
64 pub fn headers(&self) -> &HeaderMap {
66 &self.headers
67 }
68}
69
70impl Transport for HttpTransport {
71 fn run(&self, input: RunAgentInput) -> TransportFuture {
72 let client = self.client.clone();
75 let url = self.url.clone();
76 let headers = self.headers.clone();
77 let timeout = self.timeout;
78
79 Box::pin(async move {
80 let input = crate::client::agent::outgoing_json(input, &mut Vec::new())?;
81 let mut request = client.post(url).headers(headers).json(&input);
82 if let Some(timeout) = timeout {
83 request = request.timeout(timeout);
84 }
85
86 let response = request
87 .send()
88 .await
89 .map_err(|error| Error::transport(error.without_url()))?;
90 let status = response.status();
91 if !status.is_success() {
92 let mut stream = response.bytes_stream();
93 let mut body = Vec::with_capacity(MAX_ERROR_BODY);
94 let _ = tokio::time::timeout(ERROR_BODY_TIMEOUT, async {
95 while body.len() < MAX_ERROR_BODY {
96 let Some(Ok(chunk)) = stream.next().await else {
97 break;
98 };
99 let remaining = MAX_ERROR_BODY - body.len();
100 body.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
101 }
102 })
103 .await;
104 return Err(Error::Http {
105 status: status.as_u16(),
106 body: String::from_utf8_lossy(&body).into_owned(),
107 });
108 }
109
110 let content_type = response.headers().get(CONTENT_TYPE);
111 let is_sse = content_type
112 .and_then(|value| value.to_str().ok())
113 .and_then(|value| value.split(';').next())
114 .is_some_and(|value| value.trim().eq_ignore_ascii_case(SSE_MEDIA_TYPE));
115 if !is_sse {
116 let actual = match content_type {
117 Some(value) => value
118 .to_str()
119 .map(str::to_owned)
120 .unwrap_or_else(|_| "<non-UTF-8>".to_owned()),
121 None => "<missing>".to_owned(),
122 };
123 return Err(Error::UnexpectedContentType(actual));
124 }
125
126 Ok(TransportStream::json(decode_raw_events(
127 response.bytes_stream(),
128 )))
129 })
130 }
131}
132
133#[derive(Clone)]
139pub struct HttpTransportBuilder {
140 url: String,
141 headers: Vec<(String, String)>,
142 timeout: Option<Duration>,
143 connect_timeout: Option<Duration>,
144 client: Option<Client>,
145 allow_insecure_http: bool,
146}
147
148impl std::fmt::Debug for HttpTransportBuilder {
149 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150 f.debug_struct("HttpTransportBuilder")
151 .field("timeout", &self.timeout)
152 .field("connect_timeout", &self.connect_timeout)
153 .field("headers", &"<redacted>")
154 .finish_non_exhaustive()
155 }
156}
157
158impl HttpTransportBuilder {
159 pub fn new(url: impl AsRef<str>) -> Self {
161 Self {
162 url: url.as_ref().to_owned(),
163 headers: Vec::new(),
164 timeout: None,
165 connect_timeout: None,
166 client: None,
167 allow_insecure_http: false,
168 }
169 }
170
171 #[must_use]
174 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
175 self.headers.push((name.into(), value.into()));
176 self
177 }
178
179 #[must_use]
181 pub fn headers<K, V>(mut self, headers: impl IntoIterator<Item = (K, V)>) -> Self
182 where
183 K: Into<String>,
184 V: Into<String>,
185 {
186 self.headers
187 .extend(headers.into_iter().map(|(k, v)| (k.into(), v.into())));
188 self
189 }
190
191 #[must_use]
197 pub fn timeout(mut self, timeout: Duration) -> Self {
198 self.timeout = Some(timeout);
199 self
200 }
201
202 #[must_use]
204 pub fn connect_timeout(mut self, timeout: Duration) -> Self {
205 self.connect_timeout = Some(timeout);
206 self
207 }
208
209 #[must_use]
213 pub fn allow_insecure_http(mut self, allow: bool) -> Self {
214 self.allow_insecure_http = allow;
215 self
216 }
217
218 #[must_use]
224 pub fn client(mut self, client: Client) -> Self {
225 self.client = Some(client);
226 self
227 }
228
229 pub fn build(self) -> Result<HttpTransport> {
237 let url = Url::parse(&self.url)
238 .map_err(|error| Error::Config(format!("invalid endpoint URL: {error}")))?;
239
240 if !matches!(url.scheme(), "http" | "https") {
241 return Err(Error::Config("expected an HTTP or HTTPS endpoint".into()));
242 }
243 if url.scheme() == "http"
244 && !self.allow_insecure_http
245 && (!self.headers.is_empty()
246 || self.client.is_some()
247 || !url.username().is_empty()
248 || url.password().is_some()
249 || url.query().is_some())
250 && !is_loopback(&url)
251 {
252 return Err(Error::Config(
253 "remote HTTP endpoints with custom headers, a custom client, user information or a query require HTTPS or allow_insecure_http(true)".into()
254 ));
255 }
256
257 let mut headers = HeaderMap::with_capacity(self.headers.len() + 1);
258 headers.insert(ACCEPT, HeaderValue::from_static(SSE_MEDIA_TYPE));
259 for (name, value) in self.headers {
260 let name = HeaderName::try_from(name.as_str())
261 .map_err(|error| Error::Config(format!("invalid header name {name:?}: {error}")))?;
262 let mut value = HeaderValue::try_from(value.as_str()).map_err(|error| {
263 Error::Config(format!("invalid value for header {name:?}: {error}"))
264 })?;
265 value.set_sensitive(true);
266 headers.insert(name, value);
267 }
268
269 let client = match self.client {
270 Some(client) => client,
271 None => {
272 let mut builder = Client::builder().redirect(reqwest::redirect::Policy::none());
273 if let Some(timeout) = self.connect_timeout {
274 builder = builder.connect_timeout(timeout);
275 }
276 builder.build().map_err(|error| {
277 Error::Config(format!("could not build HTTP client: {error}"))
278 })?
279 }
280 };
281
282 Ok(HttpTransport {
283 client,
284 url,
285 headers,
286 timeout: self.timeout,
287 })
288 }
289}
290
291fn is_loopback(url: &Url) -> bool {
293 let Some(host) = url.host_str() else {
294 return false;
295 };
296 host.trim_end_matches('.').eq_ignore_ascii_case("localhost")
297 || host
298 .trim_start_matches('[')
299 .trim_end_matches(']')
300 .parse::<std::net::IpAddr>()
301 .is_ok_and(|address| address.is_loopback())
302}