1use crate::{join_url, ApiError, ClientConfig, OAuthTokenProvider, RequestOptions};
2use base64::Engine;
3use futures::{future::BoxFuture, Stream, StreamExt};
4use reqwest::{
5 header::{HeaderMap, HeaderName, HeaderValue},
6 Client, Method, Request, Response,
7};
8use serde::de::DeserializeOwned;
9use serde::de::Error as SerdeError;
10
11use std::{
12 collections::HashMap,
13 pin::Pin,
14 str::FromStr,
15 sync::Arc,
16 task::{Context, Poll},
17};
18
19#[derive(Debug)]
22pub struct RawResponse<T> {
23 pub body: T,
25 pub status_code: u16,
27 pub headers: HeaderMap,
29}
30
31pub struct ByteStream {
33 content_length: Option<u64>,
34 inner: Pin<Box<dyn Stream<Item = Result<bytes::Bytes, reqwest::Error>> + Send>>,
35}
36
37impl ByteStream {
38 pub(crate) fn new(response: Response) -> Self {
40 let content_length = response.content_length();
41 let stream = response.bytes_stream();
42
43 Self {
44 content_length,
45 inner: Box::pin(stream),
46 }
47 }
48
49 pub async fn collect(mut self) -> Result<Vec<u8>, ApiError> {
60 let mut result = Vec::new();
61 while let Some(chunk) = self.inner.next().await {
62 result.extend_from_slice(&chunk.map_err(ApiError::Network)?);
63 }
64 Ok(result)
65 }
66
67 pub async fn try_next(&mut self) -> Result<Option<bytes::Bytes>, ApiError> {
80 match self.inner.next().await {
81 Some(Ok(bytes)) => Ok(Some(bytes)),
82 Some(Err(e)) => Err(ApiError::Network(e)),
83 None => Ok(None),
84 }
85 }
86
87 pub fn content_length(&self) -> Option<u64> {
89 self.content_length
90 }
91}
92
93impl Stream for ByteStream {
94 type Item = Result<bytes::Bytes, ApiError>;
95
96 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
97 match self.inner.as_mut().poll_next(cx) {
98 Poll::Ready(Some(Ok(bytes))) => Poll::Ready(Some(Ok(bytes))),
99 Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(ApiError::Network(e)))),
100 Poll::Ready(None) => Poll::Ready(None),
101 Poll::Pending => Poll::Pending,
102 }
103 }
104}
105
106fn merge_additional_body_params(
108 body: Option<serde_json::Value>,
109 options: &Option<RequestOptions>,
110) -> Option<serde_json::Value> {
111 match options {
112 Some(opts) => opts.merge_additional_body_params(body),
113 None => body,
114 }
115}
116
117#[doc(hidden)]
126pub trait RequestExecutor: Send + Sync {
127 fn execute(
128 &self,
129 request: Request,
130 ) -> BoxFuture<'_, Result<Response, Box<dyn std::error::Error + Send + Sync>>>;
131}
132
133#[derive(Debug, Clone)]
140pub struct OAuthTokenExchangeConfig {
141 pub client_id_property: String,
143 pub client_secret_property: String,
145 pub extra_request_properties: HashMap<String, String>,
148 pub access_token_property: String,
150 pub expires_in_property: String,
152 pub form_encoded: bool,
156}
157
158impl Default for OAuthTokenExchangeConfig {
159 fn default() -> Self {
160 Self {
161 client_id_property: "client_id".to_string(),
162 client_secret_property: "client_secret".to_string(),
163 extra_request_properties: HashMap::from([(
164 "grant_type".to_string(),
165 "client_credentials".to_string(),
166 )]),
167 access_token_property: "access_token".to_string(),
168 expires_in_property: "expires_in".to_string(),
169 form_encoded: false,
170 }
171 }
172}
173
174#[derive(Clone)]
179pub struct OAuthConfig {
180 pub token_provider: Arc<OAuthTokenProvider>,
182 pub token_endpoint: String,
184 pub exchange: OAuthTokenExchangeConfig,
186}
187
188#[derive(Clone)]
190pub struct HttpClient {
191 client: Client,
192 executor: Option<Arc<dyn RequestExecutor>>,
193 config: ClientConfig,
194 oauth_config: Option<OAuthConfig>,
196}
197
198impl HttpClient {
199 pub fn new(config: ClientConfig) -> Result<Self, ApiError> {
202 let oauth_config = match (
203 config.oauth_token_endpoint.as_ref(),
204 config.client_id.as_ref(),
205 config.client_secret.as_ref(),
206 ) {
207 (Some(token_endpoint), Some(client_id), Some(client_secret)) => Some(OAuthConfig {
208 token_provider: Arc::new(OAuthTokenProvider::new(
209 client_id.clone(),
210 client_secret.clone(),
211 )),
212 token_endpoint: token_endpoint.clone(),
213 exchange: config.oauth_token_exchange.clone().unwrap_or_default(),
214 }),
215 _ => None,
216 };
217 Self::new_with_oauth(config, oauth_config)
218 }
219
220 pub fn new_with_oauth(
229 config: ClientConfig,
230 oauth_config: Option<OAuthConfig>,
231 ) -> Result<Self, ApiError> {
232 let client = match config.reqwest_client.clone() {
233 Some(client) => client,
234 None => Client::builder()
235 .timeout(config.timeout)
236 .user_agent(&config.user_agent)
237 .build()
238 .map_err(ApiError::Network)?,
239 };
240
241 Ok(Self {
242 client,
243 executor: None,
244 config,
245 oauth_config,
246 })
247 }
248
249 #[doc(hidden)]
259 pub fn with_executor(executor: Arc<dyn RequestExecutor>, config: ClientConfig) -> Self {
260 let client = Client::new();
261 Self {
262 client,
263 executor: Some(executor),
264 config,
265 oauth_config: None,
266 }
267 }
268
269 pub fn base_url(&self) -> &str {
271 &self.config.base_url
272 }
273
274 pub fn config(&self) -> &ClientConfig {
276 &self.config
277 }
278
279 pub async fn execute_request_raw<T>(
285 &self,
286 method: Method,
287 path: &str,
288 body: Option<serde_json::Value>,
289 query_params: Option<Vec<(String, String)>>,
290 options: Option<RequestOptions>,
291 ) -> Result<RawResponse<T>, ApiError>
292 where
293 T: DeserializeOwned,
294 {
295 let url = join_url(&self.config.base_url, path);
296 let mut request = self.client.request(method, &url);
297
298 if let Some(params) = query_params {
299 request = request.query(¶ms);
300 }
301
302 if let Some(opts) = &options {
303 if !opts.additional_query_params.is_empty() {
304 request = request.query(&opts.additional_query_params);
305 }
306 }
307
308 if let Some(body) = merge_additional_body_params(body, &options) {
309 request = request.json(&body);
310 }
311
312 let req = request.build().map_err(|e| ApiError::Network(e))?;
313
314 let response = self.send_request(req, &options).await?;
315 self.parse_response_raw(response).await
316 }
317
318 pub async fn execute_request<T>(
320 &self,
321 method: Method,
322 path: &str,
323 body: Option<serde_json::Value>,
324 query_params: Option<Vec<(String, String)>>,
325 options: Option<RequestOptions>,
326 ) -> Result<T, ApiError>
327 where
328 T: DeserializeOwned,
329 {
330 let url = join_url(&self.config.base_url, path);
331 let mut request = self.client.request(method, &url);
332
333 if let Some(params) = query_params {
334 request = request.query(¶ms);
335 }
336
337 if let Some(opts) = &options {
338 if !opts.additional_query_params.is_empty() {
339 request = request.query(&opts.additional_query_params);
340 }
341 }
342
343 if let Some(body) = merge_additional_body_params(body, &options) {
344 request = request.json(&body);
345 }
346
347 let req = request.build().map_err(|e| ApiError::Network(e))?;
348
349 let response = self.send_request(req, &options).await?;
350 self.parse_response(response).await
351 }
352
353 pub async fn execute_request_with_base_url<T>(
358 &self,
359 base_url: &str,
360 method: Method,
361 path: &str,
362 body: Option<serde_json::Value>,
363 query_params: Option<Vec<(String, String)>>,
364 options: Option<RequestOptions>,
365 ) -> Result<T, ApiError>
366 where
367 T: DeserializeOwned,
368 {
369 let url = join_url(base_url, path);
370 let mut request = self.client.request(method, &url);
371
372 if let Some(params) = query_params {
373 request = request.query(¶ms);
374 }
375
376 if let Some(opts) = &options {
377 if !opts.additional_query_params.is_empty() {
378 request = request.query(&opts.additional_query_params);
379 }
380 }
381
382 if let Some(body) = merge_additional_body_params(body, &options) {
383 request = request.json(&body);
384 }
385
386 let req = request.build().map_err(|e| ApiError::Network(e))?;
387
388 let response = self.send_request(req, &options).await?;
389 self.parse_response(response).await
390 }
391
392 #[cfg(feature = "multipart")]
412 pub async fn execute_multipart_request<T>(
413 &self,
414 method: Method,
415 path: &str,
416 form: reqwest::multipart::Form,
417 query_params: Option<Vec<(String, String)>>,
418 options: Option<RequestOptions>,
419 ) -> Result<T, ApiError>
420 where
421 T: DeserializeOwned,
422 {
423 let url = join_url(&self.config.base_url, path);
424 let mut request = self.client.request(method, &url);
425
426 if let Some(params) = query_params {
428 request = request.query(¶ms);
429 }
430
431 if let Some(opts) = &options {
433 if !opts.additional_query_params.is_empty() {
434 request = request.query(&opts.additional_query_params);
435 }
436 }
437
438 request = request.multipart(form);
440
441 let req = request.build().map_err(|e| ApiError::Network(e))?;
443
444 let response = if let Some(executor) = &self.executor {
449 let mut req = req;
450 self.apply_custom_headers(&mut req, &options)?;
451 executor.execute(req).await.map_err(ApiError::Executor)?
452 } else {
453 let mut req = req;
454 self.apply_auth_headers(&mut req, &options).await?;
455 self.apply_custom_headers(&mut req, &options)?;
456 let response = self.client.execute(req).await.map_err(ApiError::Network)?;
457 if !response.status().is_success() {
458 let status_code = response.status().as_u16();
459 let body = response.text().await.ok();
460 return Err(ApiError::from_response(status_code, body.as_deref()));
461 }
462 response
463 };
464
465 self.parse_response(response).await
466 }
467
468 #[cfg(feature = "multipart")]
474 pub async fn execute_multipart_stream_request(
475 &self,
476 method: Method,
477 path: &str,
478 form: reqwest::multipart::Form,
479 query_params: Option<Vec<(String, String)>>,
480 options: Option<RequestOptions>,
481 ) -> Result<ByteStream, ApiError> {
482 let url = join_url(&self.config.base_url, path);
483 let mut request = self.client.request(method, &url);
484
485 if let Some(params) = query_params {
487 request = request.query(¶ms);
488 }
489
490 if let Some(opts) = &options {
492 if !opts.additional_query_params.is_empty() {
493 request = request.query(&opts.additional_query_params);
494 }
495 }
496
497 request = request.multipart(form);
499
500 let req = request.build().map_err(|e| ApiError::Network(e))?;
502
503 let response = if let Some(executor) = &self.executor {
505 let mut req = req;
506 self.apply_custom_headers(&mut req, &options)?;
507 executor.execute(req).await.map_err(ApiError::Executor)?
508 } else {
509 let mut req = req;
510 self.apply_auth_headers(&mut req, &options).await?;
511 self.apply_custom_headers(&mut req, &options)?;
512 let response = self.client.execute(req).await.map_err(ApiError::Network)?;
513 if !response.status().is_success() {
514 let status_code = response.status().as_u16();
515 let body = response.text().await.ok();
516 return Err(ApiError::from_response(status_code, body.as_deref()));
517 }
518 response
519 };
520
521 Ok(ByteStream::new(response))
522 }
523
524 pub async fn execute_form_request<T>(
531 &self,
532 method: Method,
533 path: &str,
534 body: Option<serde_json::Value>,
535 query_params: Option<Vec<(String, String)>>,
536 options: Option<RequestOptions>,
537 ) -> Result<T, ApiError>
538 where
539 T: DeserializeOwned,
540 {
541 let url = join_url(&self.config.base_url, path);
542 let mut request = self.client.request(method, &url);
543
544 if let Some(params) = query_params {
545 request = request.query(¶ms);
546 }
547
548 if let Some(opts) = &options {
549 if !opts.additional_query_params.is_empty() {
550 request = request.query(&opts.additional_query_params);
551 }
552 }
553
554 if let Some(body) = merge_additional_body_params(body, &options) {
555 request = request.form(&body);
556 }
557
558 let req = request.build().map_err(|e| ApiError::Network(e))?;
559
560 let response = self.send_request(req, &options).await?;
561 self.parse_response(response).await
562 }
563
564 async fn send_request(
568 &self,
569 req: Request,
570 options: &Option<RequestOptions>,
571 ) -> Result<Response, ApiError> {
572 if let Some(executor) = &self.executor {
573 let mut req = req;
574 self.apply_custom_headers(&mut req, options)?;
575 executor.execute(req).await.map_err(ApiError::Executor)
576 } else {
577 let mut req = req;
578 self.apply_auth_headers(&mut req, options).await?;
579 self.apply_custom_headers(&mut req, options)?;
580 self.execute_with_retries(req, options).await
581 }
582 }
583
584 async fn apply_auth_headers(
585 &self,
586 request: &mut Request,
587 options: &Option<RequestOptions>,
588 ) -> Result<(), ApiError> {
589 let headers = request.headers_mut();
590
591 let api_key = options
593 .as_ref()
594 .and_then(|opts| opts.api_key.as_ref())
595 .or(self.config.api_key.as_ref());
596
597 if let Some(key) = api_key {
598 let header_value = key.to_string();
599 headers.insert(
600 "api-key",
601 header_value.parse().map_err(|_| ApiError::InvalidHeader)?,
602 );
603 }
604
605 let token = if let Some(opts) = options.as_ref() {
607 if opts.token.is_some() {
608 opts.token.clone()
609 } else {
610 None
611 }
612 } else {
613 None
614 };
615
616 let token = match token {
617 Some(t) => Some(t),
618 None => {
619 if let Some(oauth_config) = &self.oauth_config {
621 Some(self.get_oauth_token(oauth_config).await?)
622 } else {
623 self.config.token.clone()
625 }
626 }
627 };
628
629 if let Some(token) = token {
630 let auth_value = format!("Bearer {}", token);
631 headers.insert(
632 "Authorization",
633 auth_value.parse().map_err(|_| ApiError::InvalidHeader)?,
634 );
635 }
636
637 Ok(())
638 }
639
640 async fn get_oauth_token(&self, oauth_config: &OAuthConfig) -> Result<String, ApiError> {
642 let token_provider = &oauth_config.token_provider;
643 let token_endpoint = &oauth_config.token_endpoint;
644 let client_id = token_provider.client_id().to_string();
645 let client_secret = token_provider.client_secret().to_string();
646 let base_url = self.config.base_url.clone();
647
648 let exchange = &oauth_config.exchange;
649
650 token_provider
652 .get_or_fetch_async(|| async {
653 self.fetch_oauth_token(
654 &base_url,
655 token_endpoint,
656 &client_id,
657 &client_secret,
658 exchange,
659 )
660 .await
661 })
662 .await
663 }
664
665 async fn fetch_oauth_token(
681 &self,
682 base_url: &str,
683 token_endpoint: &str,
684 client_id: &str,
685 client_secret: &str,
686 exchange: &OAuthTokenExchangeConfig,
687 ) -> Result<(String, u64), ApiError> {
688 let url = join_url(base_url, token_endpoint);
689
690 let mut params: Vec<(String, String)> = Vec::new();
693 params.push((exchange.client_id_property.clone(), client_id.to_string()));
694 params.push((
695 exchange.client_secret_property.clone(),
696 client_secret.to_string(),
697 ));
698 for (name, value) in &exchange.extra_request_properties {
699 params.push((name.clone(), value.clone()));
700 }
701
702 let builder = self.client.request(Method::POST, &url);
703 let builder = if exchange.form_encoded {
704 builder.form(¶ms)
705 } else {
706 let body = params
707 .into_iter()
708 .map(|(name, value)| (name, serde_json::Value::String(value)))
709 .collect::<serde_json::Map<String, serde_json::Value>>();
710 builder.json(&serde_json::Value::Object(body))
711 };
712 let mut request = builder.build().map_err(ApiError::Network)?;
713 self.apply_custom_headers(&mut request, &None)?;
714
715 let response = self
716 .client
717 .execute(request)
718 .await
719 .map_err(ApiError::Network)?;
720
721 let status_code = response.status().as_u16();
722 if !response.status().is_success() {
723 let body = response.text().await.ok();
724 return Err(ApiError::from_response(status_code, body.as_deref()));
725 }
726
727 let token_response: serde_json::Value = response.json().await.map_err(ApiError::Network)?;
729
730 let access_token = token_response
731 .get(&exchange.access_token_property)
732 .and_then(|value| value.as_str())
733 .ok_or_else(|| ApiError::Http {
734 status: status_code,
735 message: "OAuth token response is missing the access token".to_string(),
736 })?
737 .to_string();
738
739 let expires_in = token_response
740 .get(&exchange.expires_in_property)
741 .and_then(|value| value.as_i64())
742 .unwrap_or(3600) as u64;
743
744 Ok((access_token, expires_in))
745 }
746
747 fn apply_custom_headers(
748 &self,
749 request: &mut Request,
750 options: &Option<RequestOptions>,
751 ) -> Result<(), ApiError> {
752 let headers = request.headers_mut();
753
754 for (key, value) in &self.config.custom_headers {
756 headers.insert(
757 HeaderName::from_str(key).map_err(|_| ApiError::InvalidHeader)?,
758 HeaderValue::from_str(value).map_err(|_| ApiError::InvalidHeader)?,
759 );
760 }
761
762 if let Some(options) = options {
764 for (key, value) in &options.additional_headers {
765 headers.insert(
766 HeaderName::from_str(key).map_err(|_| ApiError::InvalidHeader)?,
767 HeaderValue::from_str(value).map_err(|_| ApiError::InvalidHeader)?,
768 );
769 }
770 }
771
772 Ok(())
773 }
774
775 async fn execute_with_retries(
776 &self,
777 request: Request,
778 options: &Option<RequestOptions>,
779 ) -> Result<Response, ApiError> {
780 let max_retries = options
781 .as_ref()
782 .and_then(|opts| opts.max_retries)
783 .unwrap_or(self.config.max_retries);
784
785 let mut last_error = None;
786
787 for attempt in 0..=max_retries {
788 let cloned_request = request.try_clone().ok_or(ApiError::RequestClone)?;
789
790 match self.client.execute(cloned_request).await {
791 Ok(response) if response.status().is_success() => return Ok(response),
792 Ok(response)
793 if attempt < max_retries
794 && Self::is_retryable_status(response.status().as_u16()) =>
795 {
796 let delay = std::time::Duration::from_millis(100 * 2_u64.pow(attempt));
798 tokio::time::sleep(delay).await;
799 }
800 Ok(response) => {
801 let status_code = response.status().as_u16();
802 let body = response.text().await.ok();
803 return Err(ApiError::from_response(status_code, body.as_deref()));
804 }
805 Err(e) if attempt < max_retries => {
806 last_error = Some(e);
807 let delay = std::time::Duration::from_millis(100 * 2_u64.pow(attempt));
809 tokio::time::sleep(delay).await;
810 }
811 Err(e) => return Err(ApiError::Network(e)),
812 }
813 }
814
815 Err(ApiError::Network(last_error.unwrap()))
816 }
817
818 fn is_retryable_status(status_code: u16) -> bool {
819 [408, 429].contains(&status_code) || status_code >= 500
820 }
821
822 async fn parse_response<T>(&self, response: Response) -> Result<T, ApiError>
823 where
824 T: DeserializeOwned,
825 {
826 let status = response.status().as_u16();
827 let text = response.text().await.map_err(ApiError::Network)?;
828
829 if status >= 400 {
837 return Err(ApiError::Http {
838 status,
839 message: text,
840 });
841 }
842
843 if text.is_empty() {
844 return serde_json::from_value(serde_json::Value::Null).map_err(|_| ApiError::Http {
845 status,
846 message: String::new(),
847 });
848 }
849
850 serde_json::from_str(&text).map_err(ApiError::Serialization)
851 }
852
853 async fn parse_response_raw<T>(&self, response: Response) -> Result<RawResponse<T>, ApiError>
854 where
855 T: DeserializeOwned,
856 {
857 let status_code = response.status().as_u16();
858 let headers = response.headers().clone();
859 let text = response.text().await.map_err(ApiError::Network)?;
860
861 if status_code >= 400 {
866 return Err(ApiError::Http {
867 status: status_code,
868 message: text,
869 });
870 }
871
872 if text.is_empty() {
873 return serde_json::from_value(serde_json::Value::Null)
874 .map(|body| RawResponse {
875 body,
876 status_code,
877 headers,
878 })
879 .map_err(|_| ApiError::Http {
880 status: status_code,
881 message: String::new(),
882 });
883 }
884
885 let body: T = serde_json::from_str(&text).map_err(ApiError::Serialization)?;
886 Ok(RawResponse {
887 body,
888 status_code,
889 headers,
890 })
891 }
892
893 pub async fn execute_request_base64(
899 &self,
900 method: Method,
901 path: &str,
902 body: Option<serde_json::Value>,
903 query_params: Option<Vec<(String, String)>>,
904 options: Option<RequestOptions>,
905 ) -> Result<Vec<u8>, ApiError> {
906 let url = join_url(&self.config.base_url, path);
907 let mut request = self.client.request(method, &url);
908
909 if let Some(params) = query_params {
911 request = request.query(¶ms);
912 }
913
914 if let Some(opts) = &options {
916 if !opts.additional_query_params.is_empty() {
917 request = request.query(&opts.additional_query_params);
918 }
919 }
920
921 if let Some(body) = merge_additional_body_params(body, &options) {
923 request = request.json(&body);
924 }
925
926 let req = request.build().map_err(|e| ApiError::Network(e))?;
928
929 let response = self.send_request(req, &options).await?;
930
931 let text = response.text().await.map_err(ApiError::Network)?;
933 let base64_string: String = serde_json::from_str(&text).map_err(ApiError::Serialization)?;
934 base64::engine::general_purpose::STANDARD
935 .decode(&base64_string)
936 .map_err(|e| {
937 ApiError::Serialization(SerdeError::custom(format!("base64 decode error: {}", e)))
938 })
939 }
940
941 pub async fn execute_stream_request(
997 &self,
998 method: Method,
999 path: &str,
1000 body: Option<serde_json::Value>,
1001 query_params: Option<Vec<(String, String)>>,
1002 options: Option<RequestOptions>,
1003 ) -> Result<ByteStream, ApiError> {
1004 let url = join_url(&self.config.base_url, path);
1005 let mut request = self.client.request(method, &url);
1006
1007 if let Some(params) = query_params {
1009 request = request.query(¶ms);
1010 }
1011
1012 if let Some(opts) = &options {
1014 if !opts.additional_query_params.is_empty() {
1015 request = request.query(&opts.additional_query_params);
1016 }
1017 }
1018
1019 if let Some(body) = merge_additional_body_params(body, &options) {
1021 request = request.json(&body);
1022 }
1023
1024 let req = request.build().map_err(|e| ApiError::Network(e))?;
1026
1027 let response = self.send_request(req, &options).await?;
1028
1029 Ok(ByteStream::new(response))
1031 }
1032
1033 pub async fn execute_stream_request_with_base_url(
1035 &self,
1036 base_url: &str,
1037 method: Method,
1038 path: &str,
1039 body: Option<serde_json::Value>,
1040 query_params: Option<Vec<(String, String)>>,
1041 options: Option<RequestOptions>,
1042 ) -> Result<ByteStream, ApiError> {
1043 let url = join_url(base_url, path);
1044 let mut request = self.client.request(method, &url);
1045
1046 if let Some(params) = query_params {
1047 request = request.query(¶ms);
1048 }
1049
1050 if let Some(opts) = &options {
1051 if !opts.additional_query_params.is_empty() {
1052 request = request.query(&opts.additional_query_params);
1053 }
1054 }
1055
1056 if let Some(body) = merge_additional_body_params(body, &options) {
1057 request = request.json(&body);
1058 }
1059
1060 let req = request.build().map_err(|e| ApiError::Network(e))?;
1061
1062 let response = self.send_request(req, &options).await?;
1063
1064 Ok(ByteStream::new(response))
1065 }
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070 use super::*;
1071
1072 #[test]
1073 fn test_is_retryable_status() {
1074 assert!(HttpClient::is_retryable_status(408));
1076 assert!(HttpClient::is_retryable_status(429));
1077
1078 assert!(HttpClient::is_retryable_status(500));
1080 assert!(HttpClient::is_retryable_status(501));
1081 assert!(HttpClient::is_retryable_status(502));
1082 assert!(HttpClient::is_retryable_status(503));
1083 assert!(HttpClient::is_retryable_status(504));
1084 assert!(HttpClient::is_retryable_status(599));
1085
1086 assert!(!HttpClient::is_retryable_status(200));
1088 assert!(!HttpClient::is_retryable_status(400));
1089 assert!(!HttpClient::is_retryable_status(401));
1090 assert!(!HttpClient::is_retryable_status(404));
1091 }
1092
1093 #[derive(Debug, Default, serde::Deserialize)]
1098 struct PermissivePayload {
1099 #[serde(default)]
1100 agents: Vec<String>,
1101 }
1102
1103 async fn serve_once(status_line: &'static str, body: &'static str) -> String {
1108 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
1109 .await
1110 .expect("bind ephemeral port");
1111 let url = format!("http://{}/", listener.local_addr().expect("local addr"));
1112 tokio::spawn(async move {
1113 if let Ok((mut socket, _)) = listener.accept().await {
1114 use tokio::io::{AsyncReadExt, AsyncWriteExt};
1115 let mut discard = [0u8; 1024];
1116 let _ = socket.read(&mut discard).await;
1117 let response = format!(
1118 "HTTP/1.1 {status_line}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
1119 body.len()
1120 );
1121 let _ = socket.write_all(response.as_bytes()).await;
1122 let _ = socket.flush().await;
1123 }
1124 });
1125 url
1126 }
1127
1128 fn test_client() -> HttpClient {
1129 HttpClient::new(ClientConfig::default()).expect("construct client")
1130 }
1131
1132 #[tokio::test]
1133 async fn test_parse_response_errors_on_non_2xx_with_a_deserializable_body() {
1134 let url = serve_once("401 Unauthorized", r#"{"detail":"invalid api key"}"#).await;
1140 let response = reqwest::get(&url).await.expect("request completes");
1141
1142 let result: Result<PermissivePayload, ApiError> =
1143 test_client().parse_response(response).await;
1144
1145 match result {
1146 Err(ApiError::Http { status, message }) => {
1147 assert_eq!(status, 401);
1148 assert!(
1149 message.contains("invalid api key"),
1150 "the server's error detail must reach the caller, got: {message}"
1151 );
1152 }
1153 Err(other) => panic!("expected ApiError::Http, got {other:?}"),
1154 Ok(_) => panic!("a 401 with a body must not be reported as success"),
1155 }
1156 }
1157
1158 #[tokio::test]
1159 async fn test_parse_response_raw_errors_on_non_2xx_with_a_deserializable_body() {
1160 let url = serve_once("500 Internal Server Error", r#"{"agents":[]}"#).await;
1161 let response = reqwest::get(&url).await.expect("request completes");
1162
1163 let result: Result<RawResponse<PermissivePayload>, ApiError> =
1164 test_client().parse_response_raw(response).await;
1165
1166 match result {
1167 Err(ApiError::Http { status, .. }) => assert_eq!(status, 500),
1168 Err(other) => panic!("expected ApiError::Http, got {other:?}"),
1169 Ok(_) => panic!("a 500 with a body must not be reported as success"),
1170 }
1171 }
1172
1173 #[tokio::test]
1174 async fn test_parse_response_still_succeeds_on_2xx() {
1175 let url = serve_once("200 OK", r#"{"agents":["one","two"]}"#).await;
1177 let response = reqwest::get(&url).await.expect("request completes");
1178
1179 let parsed: PermissivePayload = test_client()
1180 .parse_response(response)
1181 .await
1182 .expect("a 200 must deserialize");
1183
1184 assert_eq!(parsed.agents, vec!["one", "two"]);
1185 }
1186
1187 #[tokio::test]
1188 async fn test_parse_response_raw_still_exposes_status_on_2xx() {
1189 let url = serve_once("201 Created", r#"{"agents":["one"]}"#).await;
1190 let response = reqwest::get(&url).await.expect("request completes");
1191
1192 let raw: RawResponse<PermissivePayload> = test_client()
1193 .parse_response_raw(response)
1194 .await
1195 .expect("a 201 must deserialize");
1196
1197 assert_eq!(raw.status_code, 201);
1198 assert_eq!(raw.body.agents, vec!["one"]);
1199 }
1200
1201 async fn serve_one_token_request(listener: tokio::net::TcpListener) -> String {
1203 use tokio::io::{AsyncReadExt, AsyncWriteExt};
1204
1205 let (mut socket, _) = listener.accept().await.expect("accept");
1206 let mut raw = Vec::new();
1207 let mut buffer = [0u8; 1024];
1208 loop {
1209 let read = socket.read(&mut buffer).await.expect("read");
1210 raw.extend_from_slice(&buffer[..read]);
1211 if read == 0 || String::from_utf8_lossy(&raw).contains("\r\n\r\n") {
1212 break;
1213 }
1214 }
1215
1216 let body = r#"{"access_token":"token-from-server","expires_in":3600}"#;
1217 let response = format!(
1218 "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}",
1219 body.len(),
1220 body
1221 );
1222 socket.write_all(response.as_bytes()).await.expect("write");
1223 socket.flush().await.expect("flush");
1224
1225 String::from_utf8_lossy(&raw).to_string()
1226 }
1227
1228 #[tokio::test]
1229 async fn test_oauth_token_request_sends_custom_headers() {
1230 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
1231 .await
1232 .expect("bind");
1233 let base_url = format!("http://{}", listener.local_addr().expect("addr"));
1234 let server = tokio::spawn(serve_one_token_request(listener));
1235
1236 let mut config = ClientConfig::default();
1237 config.base_url = base_url;
1238 config
1239 .custom_headers
1240 .insert("X-Gateway-Token".to_string(), "sunflower".to_string());
1241 let client = HttpClient::new(config).expect("client");
1242
1243 let (access_token, _) = client
1244 .fetch_oauth_token(
1245 &client.config.base_url.clone(),
1246 "/token",
1247 "client-id",
1248 "client-secret",
1249 &OAuthTokenExchangeConfig::default(),
1250 )
1251 .await
1252 .expect("token");
1253
1254 let raw_request = server.await.expect("server");
1255 assert_eq!(access_token, "token-from-server");
1256 assert!(
1257 raw_request.contains("x-gateway-token: sunflower"),
1258 "token request is missing the client's custom headers: {raw_request}"
1259 );
1260 }
1261
1262 #[tokio::test]
1263 async fn test_supplied_reqwest_client_is_used_and_keeps_sdk_headers() {
1264 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
1265 .await
1266 .expect("bind");
1267 let base_url = format!("http://{}", listener.local_addr().expect("addr"));
1268 let server = tokio::spawn(serve_one_token_request(listener));
1271
1272 let config = ClientConfig {
1273 base_url,
1274 reqwest_client: Some(
1275 Client::builder()
1276 .user_agent("custom-transport/1.0")
1277 .build()
1278 .expect("build custom client"),
1279 ),
1280 ..Default::default()
1281 };
1282 let client = HttpClient::new(config).expect("client");
1283
1284 let _: Result<serde_json::Value, ApiError> = client
1285 .execute_request(Method::GET, "/ping", None, None, None)
1286 .await;
1287
1288 let raw_request = server.await.expect("server");
1289 assert!(
1290 raw_request.contains("user-agent: custom-transport/1.0"),
1291 "the supplied reqwest client must execute the request: {raw_request}"
1292 );
1293 assert!(
1294 raw_request.contains("x-fern-language: Rust"),
1295 "SDK-level headers must still be applied to a custom client: {raw_request}"
1296 );
1297 }
1298
1299 #[tokio::test]
1300 async fn test_oauth_token_request_form_encodes_when_configured() {
1301 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
1302 .await
1303 .expect("bind");
1304 let base_url = format!("http://{}", listener.local_addr().expect("addr"));
1305 let server = tokio::spawn(serve_one_token_request(listener));
1306
1307 let mut config = ClientConfig::default();
1308 config.base_url = base_url;
1309 let client = HttpClient::new(config).expect("client");
1310
1311 let exchange = OAuthTokenExchangeConfig {
1312 form_encoded: true,
1313 ..OAuthTokenExchangeConfig::default()
1314 };
1315 let (access_token, _) = client
1316 .fetch_oauth_token(
1317 &client.config.base_url.clone(),
1318 "/token",
1319 "client-id",
1320 "client-secret",
1321 &exchange,
1322 )
1323 .await
1324 .expect("token");
1325
1326 let raw_request = server.await.expect("server");
1327 assert_eq!(access_token, "token-from-server");
1328 assert!(
1329 raw_request.contains("content-type: application/x-www-form-urlencoded"),
1330 "token request should be form-encoded when the endpoint declares it: {raw_request}"
1331 );
1332 assert!(
1333 !raw_request.contains("content-type: application/json"),
1334 "token request should not send a JSON content type when form-encoded: {raw_request}"
1335 );
1336 }
1337
1338 struct RecordingExecutor {
1341 seen: std::sync::Mutex<Option<HeaderMap>>,
1342 }
1343
1344 impl RequestExecutor for RecordingExecutor {
1345 fn execute(
1346 &self,
1347 request: Request,
1348 ) -> BoxFuture<'_, Result<Response, Box<dyn std::error::Error + Send + Sync>>> {
1349 *self.seen.lock().expect("lock") = Some(request.headers().clone());
1350 Box::pin(async { Err("not sent".into()) })
1351 }
1352 }
1353
1354 struct BodyRecordingExecutor {
1356 seen: std::sync::Mutex<Option<Vec<u8>>>,
1357 }
1358
1359 impl RequestExecutor for BodyRecordingExecutor {
1360 fn execute(
1361 &self,
1362 request: Request,
1363 ) -> BoxFuture<'_, Result<Response, Box<dyn std::error::Error + Send + Sync>>> {
1364 *self.seen.lock().expect("lock") = request
1365 .body()
1366 .and_then(|body| body.as_bytes())
1367 .map(|bytes| bytes.to_vec());
1368 Box::pin(async { Err("not sent".into()) })
1369 }
1370 }
1371
1372 async fn sent_body(
1373 body: Option<serde_json::Value>,
1374 options: Option<RequestOptions>,
1375 ) -> Option<serde_json::Value> {
1376 let executor = Arc::new(BodyRecordingExecutor {
1377 seen: std::sync::Mutex::new(None),
1378 });
1379 let config = ClientConfig {
1380 base_url: "http://127.0.0.1:1".to_string(),
1381 ..Default::default()
1382 };
1383 let client = HttpClient::with_executor(executor.clone(), config);
1384 let _: Result<serde_json::Value, ApiError> = client
1385 .execute_request(Method::POST, "/items", body, None, options)
1386 .await;
1387 let seen = executor.seen.lock().expect("lock").clone();
1388 seen.map(|bytes| serde_json::from_slice(&bytes).expect("JSON body"))
1389 }
1390
1391 #[tokio::test]
1392 async fn test_execute_request_merges_additional_body_params() {
1393 let options = RequestOptions::new()
1394 .additional_body_param("name", "override")
1395 .additional_body_param("beta", serde_json::json!({"enabled": true}));
1396 let body = sent_body(
1397 Some(serde_json::json!({"name": "fern", "count": 1})),
1398 Some(options),
1399 )
1400 .await;
1401 assert_eq!(
1402 body,
1403 Some(serde_json::json!({
1404 "name": "override",
1405 "count": 1,
1406 "beta": {"enabled": true}
1407 }))
1408 );
1409 }
1410
1411 #[tokio::test]
1412 async fn test_execute_request_creates_body_from_additional_body_params() {
1413 let options = RequestOptions::new().additional_body_param("beta", true);
1414 let body = sent_body(None, Some(options)).await;
1415 assert_eq!(body, Some(serde_json::json!({"beta": true})));
1416 }
1417
1418 #[tokio::test]
1419 async fn test_execute_request_without_body_or_additional_body_params_sends_no_body() {
1420 assert_eq!(sent_body(None, None).await, None);
1421 assert_eq!(sent_body(None, Some(RequestOptions::new())).await, None);
1422 }
1423
1424 #[tokio::test]
1425 async fn test_executor_path_applies_custom_headers() {
1426 let executor = Arc::new(RecordingExecutor {
1433 seen: std::sync::Mutex::new(None),
1434 });
1435 let mut config = ClientConfig::default();
1436 config
1437 .custom_headers
1438 .insert("X-Source".to_string(), "custom-command".to_string());
1439 let client = HttpClient::with_executor(executor.clone(), config);
1440
1441 let request = Client::new()
1442 .get("http://127.0.0.1:1/ping")
1443 .build()
1444 .expect("build request");
1445 let options = RequestOptions::new().additional_header("X-Request-Level", "sunflower");
1446 let _: Result<Response, ApiError> = client.send_request(request, &Some(options)).await;
1447
1448 let seen = executor
1449 .seen
1450 .lock()
1451 .expect("lock")
1452 .clone()
1453 .expect("executor received the request");
1454 assert_eq!(
1455 seen.get("x-source").map(|v| v.to_str().expect("utf-8")),
1456 Some("custom-command"),
1457 "client-level custom headers must survive the executor path: {seen:?}"
1458 );
1459 assert_eq!(
1460 seen.get("x-request-level")
1461 .map(|v| v.to_str().expect("utf-8")),
1462 Some("sunflower"),
1463 "request-level headers must survive the executor path: {seen:?}"
1464 );
1465 assert_eq!(
1466 seen.get("x-fern-language")
1467 .map(|v| v.to_str().expect("utf-8")),
1468 Some("Rust"),
1469 "SDK platform headers must survive the executor path: {seen:?}"
1470 );
1471 }
1472}