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