Skip to main content

fc_ui/capabilities/foundation/
http.rs

1#[cfg(feature = "http")]
2use futures::{future::BoxFuture, AsyncReadExt, FutureExt};
3#[cfg(feature = "http")]
4use gpui::http_client::{AsyncBody, HttpClient, Request, Response};
5#[cfg(feature = "http")]
6use std::{fmt, sync::Arc};
7
8/// User agent used by the built-in HTTP client.
9pub const DEFAULT_USER_AGENT: &str = concat!("fc-ui/", env!("CARGO_PKG_VERSION"));
10
11/// Controls how root initialization handles GPUI's application-wide HTTP client.
12#[cfg(feature = "http")]
13#[derive(Clone, Debug, Default, Eq, PartialEq)]
14pub enum HttpSetup {
15    /// Install the built-in client with [`DEFAULT_USER_AGENT`].
16    #[default]
17    Default,
18    /// Install the built-in client with the supplied user agent.
19    UserAgent(String),
20    /// Leave GPUI's current HTTP client unchanged.
21    PreserveExisting,
22}
23
24/// Error returned when the built-in HTTP client cannot be constructed.
25#[cfg(feature = "http")]
26#[derive(Debug)]
27pub struct HttpInitError {
28    source: reqwest::Error,
29}
30
31#[cfg(feature = "http")]
32impl fmt::Display for HttpInitError {
33    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
34        write!(
35            formatter,
36            "failed to initialize HTTP client: {}",
37            self.source
38        )
39    }
40}
41
42#[cfg(feature = "http")]
43impl std::error::Error for HttpInitError {
44    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
45        Some(&self.source)
46    }
47}
48
49#[cfg(feature = "http")]
50impl From<reqwest::Error> for HttpInitError {
51    fn from(source: reqwest::Error) -> Self {
52        Self { source }
53    }
54}
55
56#[cfg(feature = "http")]
57pub struct SimpleHttpClient {
58    client: reqwest::blocking::Client,
59    user_agent: gpui::http_client::http::HeaderValue,
60}
61
62#[cfg(feature = "http")]
63impl SimpleHttpClient {
64    pub fn new(user_agent: &str) -> Result<Arc<Self>, HttpInitError> {
65        let client = reqwest::blocking::Client::builder()
66            .user_agent(user_agent)
67            .build()
68            .map_err(HttpInitError::from)?;
69
70        let user_agent_header = gpui::http_client::http::HeaderValue::from_str(user_agent)
71            .unwrap_or_else(|_| gpui::http_client::http::HeaderValue::from_static("fc-ui"));
72
73        Ok(Arc::new(Self {
74            client,
75            user_agent: user_agent_header,
76        }))
77    }
78
79    pub fn with_default_user_agent() -> Result<Arc<Self>, HttpInitError> {
80        Self::new(DEFAULT_USER_AGENT)
81    }
82}
83
84#[cfg(feature = "http")]
85async fn read_request_body(mut body: AsyncBody) -> gpui::http_client::Result<Vec<u8>> {
86    let mut bytes = Vec::new();
87    body.read_to_end(&mut bytes)
88        .await
89        .map_err(|e| gpui::http_client::anyhow!("Failed to read request body: {}", e))?;
90    Ok(bytes)
91}
92
93#[cfg(feature = "http")]
94impl HttpClient for SimpleHttpClient {
95    fn type_name(&self) -> &'static str {
96        "SimpleHttpClient"
97    }
98
99    fn user_agent(&self) -> Option<&gpui::http_client::http::HeaderValue> {
100        Some(&self.user_agent)
101    }
102
103    fn proxy(&self) -> Option<&gpui::http_client::Url> {
104        None
105    }
106
107    fn send(
108        &self,
109        req: Request<AsyncBody>,
110    ) -> BoxFuture<'static, gpui::http_client::Result<Response<AsyncBody>>> {
111        let client = self.client.clone();
112        let (parts, body) = req.into_parts();
113
114        async move {
115            let body_bytes = read_request_body(body).await?;
116            let method = reqwest::Method::from_bytes(parts.method.as_str().as_bytes())
117                .map_err(|e| gpui::http_client::anyhow!("Unsupported HTTP method: {}", e))?;
118            let uri_str = parts.uri.to_string();
119            let headers: Vec<_> = parts
120                .headers
121                .iter()
122                .map(|(key, value)| (key.clone(), value.clone()))
123                .collect();
124
125            smol::unblock(move || {
126                let mut request_builder = client.request(method, &uri_str);
127
128                for (key, value) in headers {
129                    request_builder = request_builder.header(key, value);
130                }
131
132                if !body_bytes.is_empty() {
133                    request_builder = request_builder.body(body_bytes);
134                }
135
136                let response = request_builder
137                    .send()
138                    .map_err(|e| gpui::http_client::anyhow!("HTTP request failed: {}", e))?;
139
140                let status = response.status();
141                let headers = response.headers().clone();
142                let bytes = response.bytes().map_err(|e| {
143                    gpui::http_client::anyhow!("Failed to read response body: {}", e)
144                })?;
145
146                let mut builder = gpui::http_client::http::Response::builder().status(
147                    gpui::http_client::http::StatusCode::from_u16(status.as_u16())
148                        .map_err(|e| gpui::http_client::anyhow!("Invalid status code: {}", e))?,
149                );
150
151                for (key, value) in headers.iter() {
152                    builder = builder.header(key.as_str(), value.as_bytes());
153                }
154
155                let async_body = AsyncBody::from_bytes(bytes);
156                let response = builder
157                    .body(async_body)
158                    .map_err(|e| gpui::http_client::anyhow!("Failed to build response: {}", e))?;
159
160                Ok(response)
161            })
162            .await
163        }
164        .boxed()
165    }
166}
167
168#[cfg(feature = "http")]
169pub(crate) fn try_init_http_with_setup(
170    cx: &mut gpui::App,
171    setup: HttpSetup,
172) -> Result<(), HttpInitError> {
173    let client = match setup {
174        HttpSetup::Default => SimpleHttpClient::with_default_user_agent()?,
175        HttpSetup::UserAgent(user_agent) => SimpleHttpClient::new(&user_agent)?,
176        HttpSetup::PreserveExisting => return Ok(()),
177    };
178
179    cx.set_http_client(client);
180    Ok(())
181}
182
183#[cfg(feature = "http")]
184/// Install the built-in HTTP client with [`DEFAULT_USER_AGENT`].
185pub fn try_init_http(cx: &mut gpui::App) -> Result<(), HttpInitError> {
186    try_init_http_with_setup(cx, HttpSetup::Default)
187}
188
189#[cfg(feature = "http")]
190/// Install the built-in HTTP client with a caller-supplied user agent.
191pub fn try_init_http_with_user_agent(
192    cx: &mut gpui::App,
193    user_agent: &str,
194) -> Result<(), HttpInitError> {
195    try_init_http_with_setup(cx, HttpSetup::UserAgent(user_agent.into()))
196}
197
198#[cfg(feature = "http")]
199fn report_initialization_error(error: &HttpInitError) {
200    eprintln!("fc-ui: {error}");
201}
202
203pub fn init_http(cx: &mut gpui::App) {
204    #[cfg(feature = "http")]
205    if let Err(error) = try_init_http(cx) {
206        report_initialization_error(&error);
207    }
208    #[cfg(not(feature = "http"))]
209    let _ = cx;
210}
211
212pub fn init_http_with_user_agent(cx: &mut gpui::App, user_agent: &str) {
213    #[cfg(feature = "http")]
214    if let Err(error) = try_init_http_with_user_agent(cx, user_agent) {
215        report_initialization_error(&error);
216    }
217    #[cfg(not(feature = "http"))]
218    {
219        let _ = cx;
220        let _ = user_agent;
221    }
222}