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