Skip to main content

brevo_rust/core/
http_client.rs

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/// A parsed HTTP response that includes the deserialized body along with
20/// the HTTP status code and response headers.
21#[derive(Debug)]
22pub struct RawResponse<T> {
23    /// The deserialized response body.
24    pub body: T,
25    /// The HTTP status code of the response.
26    pub status_code: u16,
27    /// The HTTP response headers.
28    pub headers: HeaderMap,
29}
30
31/// A streaming byte stream for downloading files efficiently
32pub 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    /// Create a new ByteStream from a Response
39    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    /// Collect the entire stream into a `Vec<u8>`
50    ///
51    /// This consumes the stream and buffers all data into memory.
52    /// For large files, prefer using `try_next()` to process chunks incrementally.
53    ///
54    /// # Example
55    /// ```no_run
56    /// let stream = client.download_file().await?;
57    /// let bytes = stream.collect().await?;
58    /// ```
59    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    /// Get the next chunk from the stream
68    ///
69    /// Returns `Ok(Some(bytes))` if a chunk is available,
70    /// `Ok(None)` if the stream is finished, or an error.
71    ///
72    /// # Example
73    /// ```no_run
74    /// let mut stream = client.download_file().await?;
75    /// while let Some(chunk) = stream.try_next().await? {
76    ///     process_chunk(&chunk);
77    /// }
78    /// ```
79    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    /// Get the content length from response headers if available
88    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
106/// Merges `RequestOptions::additional_body_params` (if any) into a serialized request body.
107fn 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/// Trait for executing HTTP requests, enabling injection of custom
118/// transport implementations (e.g., for CLI execution-sharing).
119///
120/// When an external executor is provided, the SDK delegates raw HTTP
121/// execution to it, allowing the caller's transport stack to handle
122/// auth, retries, and TLS configuration. Custom headers configured on
123/// the client or on the request options are still applied by the SDK
124/// before the request reaches the executor.
125#[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/// Wire-level property-name mapping for the OAuth token exchange.
134///
135/// The token endpoint's request/response contract varies between APIs (e.g. camelCase
136/// `clientId`/`clientSecret`, an absent `grant_type`, or a non-standard `access_token`
137/// field name). These names are resolved from the API's OAuth scheme in the IR so the
138/// generated token fetch matches the endpoint's contract instead of hardcoding a shape.
139#[derive(Debug, Clone)]
140pub struct OAuthTokenExchangeConfig {
141    /// Request body field name carrying the client id (e.g. `"client_id"` or `"clientId"`).
142    pub client_id_property: String,
143    /// Request body field name carrying the client secret.
144    pub client_secret_property: String,
145    /// Additional static request body properties sent verbatim (e.g.
146    /// `{"grant_type": "client_credentials"}`). Empty when the token contract has none.
147    pub extra_request_properties: HashMap<String, String>,
148    /// Response field name that holds the access token (e.g. `"access_token"`).
149    pub access_token_property: String,
150    /// Response field name that holds the token lifetime in seconds (e.g. `"expires_in"`).
151    pub expires_in_property: String,
152    /// Whether the token request body is `application/x-www-form-urlencoded` (per RFC 6749
153    /// §4.4.2) instead of JSON. Resolved from the token endpoint's declared content type in
154    /// the API definition, so JSON token endpoints keep sending a JSON body.
155    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/// Configuration for OAuth token fetching.
175///
176/// This struct contains all the information needed to automatically fetch
177/// and refresh OAuth tokens.
178#[derive(Clone)]
179pub struct OAuthConfig {
180    /// The OAuth token provider that manages token caching and refresh
181    pub token_provider: Arc<OAuthTokenProvider>,
182    /// The token endpoint path (e.g., "/token")
183    pub token_endpoint: String,
184    /// The request/response property-name mapping for the token exchange.
185    pub exchange: OAuthTokenExchangeConfig,
186}
187
188/// Internal HTTP client that handles requests with authentication and retries
189#[derive(Clone)]
190pub struct HttpClient {
191    client: Client,
192    executor: Option<Arc<dyn RequestExecutor>>,
193    config: ClientConfig,
194    /// Optional OAuth configuration for automatic token management
195    oauth_config: Option<OAuthConfig>,
196}
197
198impl HttpClient {
199    /// Creates a new HttpClient, enabling OAuth automatically when the configuration
200    /// provides an OAuth token endpoint together with client credentials.
201    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    /// Creates a new HttpClient with optional OAuth support.
221    ///
222    /// When `oauth_config` is provided, the client will automatically fetch and refresh
223    /// OAuth tokens before making requests.
224    ///
225    /// When `config.reqwest_client` is set, that client is used as-is and owns all
226    /// transport-level settings (TLS, proxies, timeout, user agent); SDK-level auth,
227    /// custom headers and retries are still applied on top of it.
228    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    /// Creates an HttpClient with an injected request executor.
250    ///
251    /// When using an injected executor, the client delegates HTTP execution
252    /// entirely to the executor. Auth headers and retry logic are NOT applied
253    /// by this client — the executor's transport stack is expected to handle
254    /// them. This prevents double-retry and double-auth when the SDK is
255    /// embedded inside a CLI. Custom headers (from `ClientConfig` and from
256    /// `RequestOptions`) are still applied, since the executor has no way to
257    /// know about them.
258    #[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    /// Returns the configured base URL.
270    pub fn base_url(&self) -> &str {
271        &self.config.base_url
272    }
273
274    /// Returns a reference to the client configuration.
275    pub fn config(&self) -> &ClientConfig {
276        &self.config
277    }
278
279    /// Execute a request and return the parsed body along with HTTP status code and headers.
280    ///
281    /// Unlike `execute_request`, this method preserves the HTTP metadata from the response,
282    /// which is useful for paginated endpoints where callers need access to status codes
283    /// and headers alongside the deserialized body.
284    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(&params);
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    /// Execute a request with the given method, path, and options
319    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(&params);
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    /// Execute a request with an explicit base URL override.
354    ///
355    /// Used for multi-URL environments where different endpoints
356    /// resolve to different base URLs.
357    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(&params);
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    /// Execute a multipart/form-data request with the given method, path, and options
393    ///
394    /// This method is used for file uploads using reqwest's built-in multipart support.
395    /// Note: Multipart requests are not retried because they cannot be cloned.
396    /// `RequestOptions::additional_body_params` are not applied to multipart bodies.
397    ///
398    /// # Example
399    /// ```no_run
400    /// let form = reqwest::multipart::Form::new()
401    ///     .part("file", reqwest::multipart::Part::bytes(vec![1, 2, 3]));
402    ///
403    /// let response: MyResponse = client.execute_multipart_request(
404    ///     Method::POST,
405    ///     "/upload",
406    ///     form,
407    ///     None,
408    ///     None,
409    /// ).await?;
410    /// ```
411    #[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        // Apply query parameters if provided
427        if let Some(params) = query_params {
428            request = request.query(&params);
429        }
430
431        // Apply additional query parameters from options
432        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        // Use reqwest's built-in multipart support
439        request = request.multipart(form);
440
441        // Build the request
442        let req = request.build().map_err(|e| ApiError::Network(e))?;
443
444        // Multipart requests cannot be cloned, so they skip retries
445        // even in the default path. With an injected executor, delegate
446        // transport to the executor, applying custom headers first since
447        // the executor has no knowledge of them.
448        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    /// Execute a multipart/form-data request and return a streaming response (ByteStream).
469    ///
470    /// This method is used for file uploads that return binary data (e.g., audio conversion).
471    /// Note: Multipart requests are not retried because they cannot be cloned.
472    /// `RequestOptions::additional_body_params` are not applied to multipart bodies.
473    #[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        // Apply query parameters if provided
486        if let Some(params) = query_params {
487            request = request.query(&params);
488        }
489
490        // Apply additional query parameters from options
491        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        // Use reqwest's built-in multipart support
498        request = request.multipart(form);
499
500        // Build the request
501        let req = request.build().map_err(|e| ApiError::Network(e))?;
502
503        // Multipart requests cannot be cloned, so they skip retries
504        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    /// Execute a request whose body is `application/x-www-form-urlencoded`.
525    ///
526    /// The body is FORM-encoded, not JSON under a form label: `.form()` both serializes the
527    /// pairs and sets the header, where `.json()` would send a JSON document and stamp
528    /// `application/json` over the declared type. That is why this needs its own method rather
529    /// than the header override `execute_request_with_content_type` provides.
530    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(&params);
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    /// Applies auth/headers and executes the request, choosing between
565    /// the injected executor path (custom headers only, no SDK-level
566    /// auth/retries) and the default path (full SDK behavior).
567    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        // Apply API key (request options override config)
592        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        // Apply bearer token - priority: request options > OAuth > config
606        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                // Try OAuth token provider if configured
620                if let Some(oauth_config) = &self.oauth_config {
621                    Some(self.get_oauth_token(oauth_config).await?)
622                } else {
623                    // Fall back to static token from config
624                    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    /// Fetches an OAuth token, using the cached token if valid or fetching a new one.
641    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        // Use the async get_or_fetch method with a closure that fetches the token
651        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    /// Makes an HTTP request to the OAuth token endpoint to fetch a new token.
666    ///
667    /// The request body and response are keyed by the property names configured on the
668    /// API's OAuth scheme (via `exchange`), so non-standard token contracts (e.g. camelCase
669    /// field names or an absent `grant_type`) are honored instead of a hardcoded shape.
670    ///
671    /// Config-level custom headers are applied to the token request, since gateways often
672    /// require them on the token endpoint too. Request-level headers are deliberately not
673    /// applied: the token is cached and shared across requests, so it must not depend on the
674    /// options of whichever request happens to trigger the fetch. Auth headers are also not
675    /// applied, as this request is what produces the credential they would carry.
676    ///
677    /// The body is encoded to match the token endpoint's declared content type: form-encoded
678    /// (`application/x-www-form-urlencoded`, per RFC 6749 §4.4.2) when `exchange.form_encoded`
679    /// is set, otherwise JSON.
680    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        // Collect the token request properties (keyed by the configured names) as ordered
691        // key/value pairs, then encode them as form or JSON depending on the endpoint.
692        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(&params)
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        // Parse the token response using the configured property names.
728        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        // Apply config-level custom headers
755        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        // Apply request-level custom headers (override config)
763        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                    // Exponential backoff for retryable HTTP status codes
797                    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                    // Exponential backoff
808                    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        // The status is authoritative, and it must be consulted *before* the
830        // body is deserialized. An error payload that happens to fit `T` —
831        // all-optional fields, a bare `Value`, an empty collection — would
832        // otherwise be returned as a successful call, so a 401 surfaces as
833        // "no results" and the caller has no way to tell: `T` carries no
834        // status. The body is preserved as the error message so the server's
835        // own detail reaches the caller.
836        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        // Same contract as `parse_response`: a non-2xx is an error even though
862        // `RawResponse` could carry the status, because the success type `T`
863        // would still have to absorb an error payload. Callers that need the
864        // raw status of a failure read it off `ApiError::Http`.
865        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    /// Execute a request that returns a base64-encoded string and decode it to bytes
894    ///
895    /// This method is used for endpoints that return raw base64-encoded data as a JSON string.
896    /// The response is expected to be a JSON string (e.g., `"SGVsbG8gd29ybGQh"`) which is
897    /// decoded from base64 to raw bytes.
898    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        // Apply query parameters if provided
910        if let Some(params) = query_params {
911            request = request.query(&params);
912        }
913
914        // Apply additional query parameters from options
915        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        // Apply body if provided
922        if let Some(body) = merge_additional_body_params(body, &options) {
923            request = request.json(&body);
924        }
925
926        // Build the request
927        let req = request.build().map_err(|e| ApiError::Network(e))?;
928
929        let response = self.send_request(req, &options).await?;
930
931        // Parse response as JSON string and decode base64
932        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    /// Execute a request and return a streaming response (for large file downloads)
942    ///
943    /// This method returns a `ByteStream` that can be used to download large files
944    /// efficiently without loading the entire content into memory. The stream can be
945    /// consumed chunk by chunk, written directly to disk, or collected into bytes.
946    ///
947    /// # Examples
948    ///
949    /// **Option 1: Collect all bytes into memory**
950    /// ```no_run
951    /// let stream = client.execute_stream_request(
952    ///     Method::GET,
953    ///     "/file",
954    ///     None,
955    ///     None,
956    ///     None,
957    /// ).await?;
958    ///
959    /// let bytes = stream.collect().await?;
960    /// ```
961    ///
962    /// **Option 2: Process chunks with try_next()**
963    /// ```no_run
964    /// let mut stream = client.execute_stream_request(
965    ///     Method::GET,
966    ///     "/large-file",
967    ///     None,
968    ///     None,
969    ///     None,
970    /// ).await?;
971    ///
972    /// while let Some(chunk) = stream.try_next().await? {
973    ///     process_chunk(&chunk);
974    /// }
975    /// ```
976    ///
977    /// **Option 3: Stream with futures::Stream trait**
978    /// ```no_run
979    /// use futures::StreamExt;
980    ///
981    /// let stream = client.execute_stream_request(
982    ///     Method::GET,
983    ///     "/large-file",
984    ///     None,
985    ///     None,
986    ///     None,
987    /// ).await?;
988    ///
989    /// let mut file = tokio::fs::File::create("output.mp4").await?;
990    /// let mut stream = std::pin::pin!(stream);
991    /// while let Some(chunk) = stream.next().await {
992    ///     let chunk = chunk?;
993    ///     tokio::io::AsyncWriteExt::write_all(&mut file, &chunk).await?;
994    /// }
995    /// ```
996    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        // Apply query parameters if provided
1008        if let Some(params) = query_params {
1009            request = request.query(&params);
1010        }
1011
1012        // Apply additional query parameters from options
1013        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        // Apply body if provided
1020        if let Some(body) = merge_additional_body_params(body, &options) {
1021            request = request.json(&body);
1022        }
1023
1024        // Build the request
1025        let req = request.build().map_err(|e| ApiError::Network(e))?;
1026
1027        let response = self.send_request(req, &options).await?;
1028
1029        // Return streaming response
1030        Ok(ByteStream::new(response))
1031    }
1032
1033    /// Execute a streaming request with an explicit base URL override.
1034    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(&params);
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        // Retryable 4xx
1075        assert!(HttpClient::is_retryable_status(408));
1076        assert!(HttpClient::is_retryable_status(429));
1077
1078        // Retryable 5xx (>= 500)
1079        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        // Success and other 4xx codes are NOT retryable
1087        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    /// A payload shaped so that it deserializes cleanly from *any* JSON object,
1094    /// including an error body. This is what makes the status check load-bearing:
1095    /// with an all-optional success type, deserialization alone cannot tell a
1096    /// result from an error.
1097    #[derive(Debug, Default, serde::Deserialize)]
1098    struct PermissivePayload {
1099        #[serde(default)]
1100        agents: Vec<String>,
1101    }
1102
1103    /// Serve one raw HTTP response on an ephemeral port and return its URL.
1104    /// Avoids a dev-dependency on a mock-server crate: the point is to obtain a
1105    /// genuine `reqwest::Response` so the parsers are exercised on the real path
1106    /// rather than through a hand-built stand-in.
1107    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        // Regression: the status check used to live inside the `text.is_empty()`
1135        // branch, so a non-2xx carrying a body was deserialized and returned
1136        // `Ok`. With a permissive success type the call then looked like an
1137        // empty-but-successful result — a 401 reported as "no agents found",
1138        // exit code 0, which a script reads as "nothing to do".
1139        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        // The status gate must not swallow the happy path.
1176        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    /// Accepts a single connection, returns the raw request text and replies with a token.
1202    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        // Reuses the raw-capture server above; its token-shaped body is irrelevant here,
1269        // only the request it echoes back matters.
1270        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    /// Captures the request it is handed and refuses to send it, so the
1339    /// headers the SDK applied before delegating are observable.
1340    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    /// Captures the request body it is handed and refuses to send it.
1355    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        // Regression: the executor branch delegated the request untouched, so
1427        // headers only the SDK knows about — `ClientConfig::custom_headers`
1428        // (e.g. an `X-Source` override, plus the X-Fern-* platform headers)
1429        // and `RequestOptions::additional_headers` — never reached the wire.
1430        // An injected executor (the generated CLI's custom-command path)
1431        // cannot recover them on its own.
1432        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}