1use async_trait::async_trait;
4use serde::Serialize;
5use serde::de::DeserializeOwned;
6use thiserror::Error;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum Method {
12 Get,
13 Post,
14 Delete,
15}
16
17#[derive(Debug, Clone, PartialEq)]
20#[non_exhaustive]
21pub struct HttpRequest {
22 pub method: Method,
23 pub url: String,
24 pub headers: Vec<(String, String)>,
25 pub body: Option<Vec<u8>>,
26}
27
28impl HttpRequest {
29 pub fn new(method: Method, url: impl Into<String>) -> Self {
31 Self {
32 method,
33 url: url.into(),
34 headers: Vec::new(),
35 body: None,
36 }
37 }
38
39 pub fn get(url: impl Into<String>) -> Self {
41 Self::new(Method::Get, url)
42 }
43
44 pub fn post(url: impl Into<String>) -> Self {
46 Self::new(Method::Post, url)
47 }
48
49 pub fn delete(url: impl Into<String>) -> Self {
51 Self::new(Method::Delete, url)
52 }
53
54 pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
56 self.headers.push((name.into(), value.into()));
57 self
58 }
59
60 pub fn with_bearer_token(self, token: &str) -> Self {
63 if token.is_empty() {
64 self
65 } else {
66 self.with_header("Authorization", format!("Bearer {token}"))
67 }
68 }
69
70 pub fn with_body(mut self, body: impl Into<Vec<u8>>) -> Self {
72 self.body = Some(body.into());
73 self
74 }
75
76 pub fn with_json(self, body: &impl Serialize) -> Result<Self, HttpError> {
78 let body = serde_json::to_vec(body).map_err(HttpError::Json)?;
79 Ok(self
80 .with_header("Content-Type", "application/json")
81 .with_body(body))
82 }
83
84 pub fn with_multipart(self, form: Multipart) -> Self {
86 let (content_type, body) = form.into_body();
87 self.with_header("Content-Type", content_type)
88 .with_body(body)
89 }
90
91 pub fn header(&self, name: &str) -> Option<&str> {
93 find_header(&self.headers, name)
94 }
95}
96
97#[derive(Debug, Clone, PartialEq)]
99#[non_exhaustive]
100pub struct HttpResponse {
101 pub status: u16,
102 pub headers: Vec<(String, String)>,
103 pub body: Vec<u8>,
104}
105
106impl HttpResponse {
107 pub fn new(status: u16, body: impl Into<Vec<u8>>) -> Self {
109 Self {
110 status,
111 headers: Vec::new(),
112 body: body.into(),
113 }
114 }
115
116 pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
118 self.headers.push((name.into(), value.into()));
119 self
120 }
121
122 pub fn is_success(&self) -> bool {
124 (200..300).contains(&self.status)
125 }
126
127 pub fn error_for_status(self) -> Result<Self, HttpError> {
130 if self.is_success() {
131 Ok(self)
132 } else {
133 Err(HttpError::Status {
134 status: self.status,
135 message: self.error_message(),
136 })
137 }
138 }
139
140 fn error_message(&self) -> String {
143 self.json::<serde_json::Value>()
144 .ok()
145 .and_then(|json| {
146 let detail = &json["detail"];
147 json["error"]["message"]
148 .as_str()
149 .or_else(|| detail.as_str())
150 .or_else(|| detail["message"].as_str())
151 .or_else(|| detail[0]["msg"].as_str())
152 .map(str::to_string)
153 })
154 .unwrap_or_else(|| self.text())
155 }
156
157 pub fn header(&self, name: &str) -> Option<&str> {
159 find_header(&self.headers, name)
160 }
161
162 pub fn content_type(&self) -> Option<&str> {
164 self.header("content-type")
165 .and_then(|value| value.split(';').next())
166 .map(str::trim)
167 .filter(|value| !value.is_empty())
168 }
169
170 pub fn json<T: DeserializeOwned>(&self) -> Result<T, HttpError> {
172 serde_json::from_slice(&self.body).map_err(HttpError::Json)
173 }
174
175 pub fn text(&self) -> String {
177 String::from_utf8_lossy(&self.body).into_owned()
178 }
179}
180
181pub fn percent_encode(value: &str) -> String {
188 let mut encoded = String::with_capacity(value.len());
189 for byte in value.bytes() {
190 if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
191 encoded.push(byte as char);
192 } else {
193 encoded.push_str(&format!("%{byte:02X}"));
194 }
195 }
196 encoded
197}
198
199fn find_header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
200 headers
201 .iter()
202 .find(|(key, _)| key.eq_ignore_ascii_case(name))
203 .map(|(_, value)| value.as_str())
204}
205
206#[derive(Debug, Error)]
208#[non_exhaustive]
209pub enum HttpError {
210 #[error("HTTP request failed: {0}")]
213 Transport(#[source] Box<dyn std::error::Error + Send + Sync>),
214 #[error("invalid JSON body: {0}")]
216 Json(serde_json::Error),
217 #[error("HTTP status {status}: {message}")]
219 Status { status: u16, message: String },
220 #[error("invalid base64 media: {0}")]
222 InvalidMedia(String),
223}
224
225impl HttpError {
226 pub fn transport(err: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
228 Self::Transport(err.into())
229 }
230}
231
232#[async_trait]
240pub trait HttpClient: Send + Sync + 'static {
241 async fn send(&self, request: HttpRequest) -> Result<HttpResponse, HttpError>;
244}
245
246#[derive(Debug, Clone, Default, PartialEq)]
257pub struct Multipart {
258 parts: Vec<FormPart>,
259}
260
261#[derive(Debug, Clone, PartialEq)]
262struct FormPart {
263 name: String,
264 filename: Option<String>,
265 content_type: Option<String>,
266 data: Vec<u8>,
267}
268
269impl Multipart {
270 pub fn new() -> Self {
272 Self::default()
273 }
274
275 pub fn with_text(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
277 self.parts.push(FormPart {
278 name: name.into(),
279 filename: None,
280 content_type: None,
281 data: value.into().into_bytes(),
282 });
283 self
284 }
285
286 pub fn with_file(
288 mut self,
289 name: impl Into<String>,
290 filename: impl Into<String>,
291 content_type: impl Into<String>,
292 data: impl Into<Vec<u8>>,
293 ) -> Self {
294 self.parts.push(FormPart {
295 name: name.into(),
296 filename: Some(filename.into()),
297 content_type: Some(content_type.into()),
298 data: data.into(),
299 });
300 self
301 }
302
303 pub fn with_json(
305 mut self,
306 name: impl Into<String>,
307 value: &impl Serialize,
308 ) -> Result<Self, HttpError> {
309 self.parts.push(FormPart {
310 name: name.into(),
311 filename: None,
312 content_type: Some("application/json".into()),
313 data: serde_json::to_vec(value).map_err(HttpError::Json)?,
314 });
315 Ok(self)
316 }
317
318 fn into_body(self) -> (String, Vec<u8>) {
320 let boundary = self.boundary();
321 let mut body = Vec::new();
322 for part in self.parts {
323 body.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
324 let name = escape(&part.name);
325 let mut head = format!("Content-Disposition: form-data; name=\"{name}\"");
326 if let Some(filename) = &part.filename {
327 head.push_str(&format!("; filename=\"{}\"", escape(filename)));
328 }
329 head.push_str("\r\n");
330 if let Some(content_type) = &part.content_type {
331 head.push_str(&format!("Content-Type: {content_type}\r\n"));
332 }
333 head.push_str("\r\n");
334 body.extend_from_slice(head.as_bytes());
335 body.extend_from_slice(&part.data);
336 body.extend_from_slice(b"\r\n");
337 }
338 body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
339 (format!("multipart/form-data; boundary={boundary}"), body)
340 }
341
342 fn boundary(&self) -> String {
345 (0u64..)
346 .map(|n| format!("agentai-boundary-{n:016x}"))
347 .find(|boundary| {
348 !self
349 .parts
350 .iter()
351 .any(|part| contains(&part.data, boundary.as_bytes()))
352 })
353 .expect("some boundary is not in the data")
354 }
355}
356
357fn contains(haystack: &[u8], needle: &[u8]) -> bool {
358 haystack
359 .windows(needle.len())
360 .any(|window| window == needle)
361}
362
363fn escape(value: &str) -> String {
365 value
366 .replace('"', "%22")
367 .replace('\r', "%0D")
368 .replace('\n', "%0A")
369}
370
371#[cfg(feature = "test-support")]
372pub mod mock;
373#[cfg(feature = "reqwest")]
374mod reqwest;
375#[cfg(feature = "reqwest")]
376pub use reqwest::ReqwestClient;
377
378#[cfg(test)]
379mod tests {
380 use super::*;
381
382 #[test]
383 fn multipart_json_part_has_a_content_type_and_no_filename() {
384 let form = Multipart::new()
385 .with_json("request", &serde_json::json!({"model": "m"}))
386 .unwrap()
387 .with_file("image", "a.png", "image/png", vec![1u8]);
388 let (_, body) = form.into_body();
389 let body = String::from_utf8_lossy(&body);
390 assert!(body.contains(
391 "Content-Disposition: form-data; name=\"request\"\r\nContent-Type: application/json\r\n\r\n{\"model\":\"m\"}\r\n"
392 ));
393 assert!(
394 body.contains("name=\"image\"; filename=\"a.png\"\r\nContent-Type: image/png\r\n\r\n")
395 );
396 }
397
398 #[test]
399 fn error_for_status_reads_every_error_shape() {
400 let message = |body: &str| match HttpResponse::new(400, body).error_for_status() {
401 Err(HttpError::Status {
402 status: 400,
403 message,
404 }) => message,
405 other => panic!("{other:?}"),
406 };
407 assert_eq!(message(r#"{"error": {"message": "openai"}}"#), "openai");
408 assert_eq!(message(r#"{"detail": "omlx"}"#), "omlx");
409 assert_eq!(message(r#"{"detail": {"message": "eleven"}}"#), "eleven");
410 assert_eq!(
411 message(r#"{"detail": [{"msg": "validation"}]}"#),
412 "validation"
413 );
414 assert_eq!(message(r#"{"other":1}"#), r#"{"other":1}"#);
415 assert_eq!(message("bad gateway"), "bad gateway");
416 assert!(HttpResponse::new(204, "").error_for_status().is_ok());
417 }
418
419 #[test]
420 fn multipart_body_has_the_fields_and_files_between_boundaries() {
421 let request = HttpRequest::post("u").with_multipart(
422 Multipart::new().with_text("prompt", "a cat").with_file(
423 "image[]",
424 "a.png",
425 "image/png",
426 b"PNG".to_vec(),
427 ),
428 );
429 let boundary = "agentai-boundary-0000000000000000";
430 assert_eq!(
431 request.header("content-type"),
432 Some(format!("multipart/form-data; boundary={boundary}").as_str())
433 );
434 let expected = format!(
435 "--{boundary}\r\n\
436 Content-Disposition: form-data; name=\"prompt\"\r\n\r\n\
437 a cat\r\n\
438 --{boundary}\r\n\
439 Content-Disposition: form-data; name=\"image[]\"; filename=\"a.png\"\r\n\
440 Content-Type: image/png\r\n\r\n\
441 PNG\r\n\
442 --{boundary}--\r\n"
443 );
444 assert_eq!(String::from_utf8(request.body.unwrap()).unwrap(), expected);
445 }
446
447 #[test]
448 fn multipart_boundary_never_appears_in_the_data() {
449 let data = "agentai-boundary-0000000000000000";
450 let request =
451 HttpRequest::post("u").with_multipart(Multipart::new().with_text("prompt", data));
452 let content_type = request.header("Content-Type").unwrap();
453 assert!(content_type.ends_with("agentai-boundary-0000000000000001"));
454 }
455}