http_client.rs

  1mod async_body;
  2pub mod github;
  3pub mod github_download;
  4
  5pub use anyhow::{Result, anyhow};
  6pub use async_body::{AsyncBody, Inner};
  7use derive_more::Deref;
  8use http::HeaderValue;
  9pub use http::{self, Method, Request, Response, StatusCode, Uri};
 10
 11use futures::{
 12    FutureExt as _,
 13    future::{self, BoxFuture},
 14};
 15use http::request::Builder;
 16use parking_lot::Mutex;
 17#[cfg(feature = "test-support")]
 18use std::fmt;
 19use std::{any::type_name, sync::Arc};
 20pub use url::Url;
 21
 22#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
 23pub enum RedirectPolicy {
 24    #[default]
 25    NoFollow,
 26    FollowLimit(u32),
 27    FollowAll,
 28}
 29pub struct FollowRedirects(pub bool);
 30
 31pub trait HttpRequestExt {
 32    /// Conditionally modify self with the given closure.
 33    fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
 34    where
 35        Self: Sized,
 36    {
 37        if condition { then(self) } else { self }
 38    }
 39
 40    /// Conditionally unwrap and modify self with the given closure, if the given option is Some.
 41    fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
 42    where
 43        Self: Sized,
 44    {
 45        match option {
 46            Some(value) => then(self, value),
 47            None => self,
 48        }
 49    }
 50
 51    /// Whether or not to follow redirects
 52    fn follow_redirects(self, follow: RedirectPolicy) -> Self;
 53}
 54
 55impl HttpRequestExt for http::request::Builder {
 56    fn follow_redirects(self, follow: RedirectPolicy) -> Self {
 57        self.extension(follow)
 58    }
 59}
 60
 61pub trait HttpClient: 'static + Send + Sync {
 62    fn type_name(&self) -> &'static str;
 63
 64    fn user_agent(&self) -> Option<&HeaderValue>;
 65
 66    fn send(
 67        &self,
 68        req: http::Request<AsyncBody>,
 69    ) -> BoxFuture<'static, anyhow::Result<Response<AsyncBody>>>;
 70
 71    fn get(
 72        &self,
 73        uri: &str,
 74        body: AsyncBody,
 75        follow_redirects: bool,
 76    ) -> BoxFuture<'static, anyhow::Result<Response<AsyncBody>>> {
 77        let request = Builder::new()
 78            .uri(uri)
 79            .follow_redirects(if follow_redirects {
 80                RedirectPolicy::FollowAll
 81            } else {
 82                RedirectPolicy::NoFollow
 83            })
 84            .body(body);
 85
 86        match request {
 87            Ok(request) => self.send(request),
 88            Err(e) => Box::pin(async move { Err(e.into()) }),
 89        }
 90    }
 91
 92    fn post_json(
 93        &self,
 94        uri: &str,
 95        body: AsyncBody,
 96    ) -> BoxFuture<'static, anyhow::Result<Response<AsyncBody>>> {
 97        let request = Builder::new()
 98            .uri(uri)
 99            .method(Method::POST)
100            .header("Content-Type", "application/json")
101            .body(body);
102
103        match request {
104            Ok(request) => self.send(request),
105            Err(e) => Box::pin(async move { Err(e.into()) }),
106        }
107    }
108
109    fn proxy(&self) -> Option<&Url>;
110
111    #[cfg(feature = "test-support")]
112    fn as_fake(&self) -> &FakeHttpClient {
113        panic!("called as_fake on {}", type_name::<Self>())
114    }
115
116    fn send_multipart_form<'a>(
117        &'a self,
118        _url: &str,
119        _request: reqwest::multipart::Form,
120    ) -> BoxFuture<'a, anyhow::Result<Response<AsyncBody>>> {
121        future::ready(Err(anyhow!("not implemented"))).boxed()
122    }
123}
124
125/// An [`HttpClient`] that may have a proxy.
126#[derive(Deref)]
127pub struct HttpClientWithProxy {
128    #[deref]
129    client: Arc<dyn HttpClient>,
130    proxy: Option<Url>,
131}
132
133impl HttpClientWithProxy {
134    /// Returns a new [`HttpClientWithProxy`] with the given proxy URL.
135    pub fn new(client: Arc<dyn HttpClient>, proxy_url: Option<String>) -> Self {
136        let proxy_url = proxy_url
137            .and_then(|proxy| proxy.parse().ok())
138            .or_else(read_proxy_from_env);
139
140        Self::new_url(client, proxy_url)
141    }
142    pub fn new_url(client: Arc<dyn HttpClient>, proxy_url: Option<Url>) -> Self {
143        Self {
144            client,
145            proxy: proxy_url,
146        }
147    }
148}
149
150impl HttpClient for HttpClientWithProxy {
151    fn send(
152        &self,
153        req: Request<AsyncBody>,
154    ) -> BoxFuture<'static, anyhow::Result<Response<AsyncBody>>> {
155        self.client.send(req)
156    }
157
158    fn user_agent(&self) -> Option<&HeaderValue> {
159        self.client.user_agent()
160    }
161
162    fn proxy(&self) -> Option<&Url> {
163        self.proxy.as_ref()
164    }
165
166    fn type_name(&self) -> &'static str {
167        self.client.type_name()
168    }
169
170    #[cfg(feature = "test-support")]
171    fn as_fake(&self) -> &FakeHttpClient {
172        self.client.as_fake()
173    }
174
175    fn send_multipart_form<'a>(
176        &'a self,
177        url: &str,
178        form: reqwest::multipart::Form,
179    ) -> BoxFuture<'a, anyhow::Result<Response<AsyncBody>>> {
180        self.client.send_multipart_form(url, form)
181    }
182}
183
184/// An [`HttpClient`] that has a base URL.
185pub struct HttpClientWithUrl {
186    base_url: Mutex<String>,
187    client: HttpClientWithProxy,
188}
189
190impl std::ops::Deref for HttpClientWithUrl {
191    type Target = HttpClientWithProxy;
192
193    fn deref(&self) -> &Self::Target {
194        &self.client
195    }
196}
197
198impl HttpClientWithUrl {
199    /// Returns a new [`HttpClientWithUrl`] with the given base URL.
200    pub fn new(
201        client: Arc<dyn HttpClient>,
202        base_url: impl Into<String>,
203        proxy_url: Option<String>,
204    ) -> Self {
205        let client = HttpClientWithProxy::new(client, proxy_url);
206
207        Self {
208            base_url: Mutex::new(base_url.into()),
209            client,
210        }
211    }
212
213    pub fn new_url(
214        client: Arc<dyn HttpClient>,
215        base_url: impl Into<String>,
216        proxy_url: Option<Url>,
217    ) -> Self {
218        let client = HttpClientWithProxy::new_url(client, proxy_url);
219
220        Self {
221            base_url: Mutex::new(base_url.into()),
222            client,
223        }
224    }
225
226    /// Returns the base URL.
227    pub fn base_url(&self) -> String {
228        self.base_url.lock().clone()
229    }
230
231    /// Sets the base URL.
232    pub fn set_base_url(&self, base_url: impl Into<String>) {
233        let base_url = base_url.into();
234        *self.base_url.lock() = base_url;
235    }
236
237    /// Builds a URL using the given path.
238    pub fn build_url(&self, path: &str) -> String {
239        format!("{}{}", self.base_url(), path)
240    }
241
242    /// Builds a Zed API URL using the given path.
243    pub fn build_zed_api_url(&self, path: &str, query: &[(&str, &str)]) -> Result<Url> {
244        let base_url = self.base_url();
245        let base_api_url = match base_url.as_ref() {
246            "https://zed.dev" => "https://api.zed.dev",
247            "https://staging.zed.dev" => "https://api-staging.zed.dev",
248            "http://localhost:3000" => "http://localhost:8080",
249            other => other,
250        };
251
252        Ok(Url::parse_with_params(
253            &format!("{}{}", base_api_url, path),
254            query,
255        )?)
256    }
257
258    /// Builds a Zed Cloud URL using the given path.
259    pub fn build_zed_cloud_url(&self, path: &str, query: &[(&str, &str)]) -> Result<Url> {
260        let base_url = self.base_url();
261        let base_api_url = match base_url.as_ref() {
262            "https://zed.dev" => "https://cloud.zed.dev",
263            "https://staging.zed.dev" => "https://cloud.zed.dev",
264            "http://localhost:3000" => "http://localhost:8787",
265            other => other,
266        };
267
268        Ok(Url::parse_with_params(
269            &format!("{}{}", base_api_url, path),
270            query,
271        )?)
272    }
273
274    /// Builds a Zed LLM URL using the given path.
275    pub fn build_zed_llm_url(&self, path: &str, query: &[(&str, &str)]) -> Result<Url> {
276        let base_url = self.base_url();
277        let base_api_url = match base_url.as_ref() {
278            "https://zed.dev" => "https://cloud.zed.dev",
279            "https://staging.zed.dev" => "https://llm-staging.zed.dev",
280            "http://localhost:3000" => "http://localhost:8787",
281            other => other,
282        };
283
284        Ok(Url::parse_with_params(
285            &format!("{}{}", base_api_url, path),
286            query,
287        )?)
288    }
289}
290
291impl HttpClient for HttpClientWithUrl {
292    fn send(
293        &self,
294        req: Request<AsyncBody>,
295    ) -> BoxFuture<'static, anyhow::Result<Response<AsyncBody>>> {
296        self.client.send(req)
297    }
298
299    fn user_agent(&self) -> Option<&HeaderValue> {
300        self.client.user_agent()
301    }
302
303    fn proxy(&self) -> Option<&Url> {
304        self.client.proxy.as_ref()
305    }
306
307    fn type_name(&self) -> &'static str {
308        self.client.type_name()
309    }
310
311    #[cfg(feature = "test-support")]
312    fn as_fake(&self) -> &FakeHttpClient {
313        self.client.as_fake()
314    }
315
316    fn send_multipart_form<'a>(
317        &'a self,
318        url: &str,
319        request: reqwest::multipart::Form,
320    ) -> BoxFuture<'a, anyhow::Result<Response<AsyncBody>>> {
321        self.client.send_multipart_form(url, request)
322    }
323}
324
325pub fn read_proxy_from_env() -> Option<Url> {
326    const ENV_VARS: &[&str] = &[
327        "ALL_PROXY",
328        "all_proxy",
329        "HTTPS_PROXY",
330        "https_proxy",
331        "HTTP_PROXY",
332        "http_proxy",
333    ];
334
335    ENV_VARS
336        .iter()
337        .find_map(|var| std::env::var(var).ok())
338        .and_then(|env| env.parse().ok())
339}
340
341pub fn read_no_proxy_from_env() -> Option<String> {
342    const ENV_VARS: &[&str] = &["NO_PROXY", "no_proxy"];
343
344    ENV_VARS.iter().find_map(|var| std::env::var(var).ok())
345}
346
347pub struct BlockedHttpClient;
348
349impl BlockedHttpClient {
350    pub fn new() -> Self {
351        BlockedHttpClient
352    }
353}
354
355impl HttpClient for BlockedHttpClient {
356    fn send(
357        &self,
358        _req: Request<AsyncBody>,
359    ) -> BoxFuture<'static, anyhow::Result<Response<AsyncBody>>> {
360        Box::pin(async {
361            Err(std::io::Error::new(
362                std::io::ErrorKind::PermissionDenied,
363                "BlockedHttpClient disallowed request",
364            )
365            .into())
366        })
367    }
368
369    fn user_agent(&self) -> Option<&HeaderValue> {
370        None
371    }
372
373    fn proxy(&self) -> Option<&Url> {
374        None
375    }
376
377    fn type_name(&self) -> &'static str {
378        type_name::<Self>()
379    }
380
381    #[cfg(feature = "test-support")]
382    fn as_fake(&self) -> &FakeHttpClient {
383        panic!("called as_fake on {}", type_name::<Self>())
384    }
385}
386
387#[cfg(feature = "test-support")]
388type FakeHttpHandler = Arc<
389    dyn Fn(Request<AsyncBody>) -> BoxFuture<'static, anyhow::Result<Response<AsyncBody>>>
390        + Send
391        + Sync
392        + 'static,
393>;
394
395#[cfg(feature = "test-support")]
396pub struct FakeHttpClient {
397    handler: Mutex<Option<FakeHttpHandler>>,
398    user_agent: HeaderValue,
399}
400
401#[cfg(feature = "test-support")]
402impl FakeHttpClient {
403    pub fn create<Fut, F>(handler: F) -> Arc<HttpClientWithUrl>
404    where
405        Fut: futures::Future<Output = anyhow::Result<Response<AsyncBody>>> + Send + 'static,
406        F: Fn(Request<AsyncBody>) -> Fut + Send + Sync + 'static,
407    {
408        Arc::new(HttpClientWithUrl {
409            base_url: Mutex::new("http://test.example".into()),
410            client: HttpClientWithProxy {
411                client: Arc::new(Self {
412                    handler: Mutex::new(Some(Arc::new(move |req| Box::pin(handler(req))))),
413                    user_agent: HeaderValue::from_static(type_name::<Self>()),
414                }),
415                proxy: None,
416            },
417        })
418    }
419
420    pub fn with_404_response() -> Arc<HttpClientWithUrl> {
421        Self::create(|_| async move {
422            Ok(Response::builder()
423                .status(404)
424                .body(Default::default())
425                .unwrap())
426        })
427    }
428
429    pub fn with_200_response() -> Arc<HttpClientWithUrl> {
430        Self::create(|_| async move {
431            Ok(Response::builder()
432                .status(200)
433                .body(Default::default())
434                .unwrap())
435        })
436    }
437
438    pub fn replace_handler<Fut, F>(&self, new_handler: F)
439    where
440        Fut: futures::Future<Output = anyhow::Result<Response<AsyncBody>>> + Send + 'static,
441        F: Fn(FakeHttpHandler, Request<AsyncBody>) -> Fut + Send + Sync + 'static,
442    {
443        let mut handler = self.handler.lock();
444        let old_handler = handler.take().unwrap();
445        *handler = Some(Arc::new(move |req| {
446            Box::pin(new_handler(old_handler.clone(), req))
447        }));
448    }
449}
450
451#[cfg(feature = "test-support")]
452impl fmt::Debug for FakeHttpClient {
453    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454        f.debug_struct("FakeHttpClient").finish()
455    }
456}
457
458#[cfg(feature = "test-support")]
459impl HttpClient for FakeHttpClient {
460    fn send(
461        &self,
462        req: Request<AsyncBody>,
463    ) -> BoxFuture<'static, anyhow::Result<Response<AsyncBody>>> {
464        ((self.handler.lock().as_ref().unwrap())(req)) as _
465    }
466
467    fn user_agent(&self) -> Option<&HeaderValue> {
468        Some(&self.user_agent)
469    }
470
471    fn proxy(&self) -> Option<&Url> {
472        None
473    }
474
475    fn type_name(&self) -> &'static str {
476        type_name::<Self>()
477    }
478
479    fn as_fake(&self) -> &FakeHttpClient {
480        self
481    }
482}