1mod async_body;
2pub mod github;
3
4pub use anyhow::{anyhow, Result};
5pub use async_body::{AsyncBody, Inner};
6use derive_more::Deref;
7pub use http::{self, Method, Request, Response, StatusCode, Uri};
8
9use futures::future::BoxFuture;
10use http::request::Builder;
11#[cfg(feature = "test-support")]
12use std::fmt;
13use std::sync::{Arc, Mutex};
14pub use url::Url;
15
16pub trait HttpClient: 'static + Send + Sync {
17 fn send(
18 &self,
19 req: http::Request<AsyncBody>,
20 ) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>> {
21 self.send_with_redirect_policy(req, false)
22 }
23
24 // TODO: Make a better API for this
25 fn send_with_redirect_policy(
26 &self,
27 req: Request<AsyncBody>,
28 follow_redirects: bool,
29 ) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>>;
30
31 fn get<'a>(
32 &'a self,
33 uri: &str,
34 body: AsyncBody,
35 follow_redirects: bool,
36 ) -> BoxFuture<'a, Result<Response<AsyncBody>, anyhow::Error>> {
37 let request = Builder::new().uri(uri).body(body);
38
39 match request {
40 Ok(request) => Box::pin(async move {
41 self.send_with_redirect_policy(request, follow_redirects)
42 .await
43 .map_err(Into::into)
44 }),
45 Err(e) => Box::pin(async move { Err(e.into()) }),
46 }
47 }
48
49 fn post_json<'a>(
50 &'a self,
51 uri: &str,
52 body: AsyncBody,
53 ) -> BoxFuture<'a, Result<Response<AsyncBody>, anyhow::Error>> {
54 let request = Builder::new()
55 .uri(uri)
56 .method(Method::POST)
57 .header("Content-Type", "application/json")
58 .body(body);
59
60 match request {
61 Ok(request) => Box::pin(async move { self.send(request).await.map_err(Into::into) }),
62 Err(e) => Box::pin(async move { Err(e.into()) }),
63 }
64 }
65
66 fn proxy(&self) -> Option<&Uri>;
67}
68
69/// An [`HttpClient`] that may have a proxy.
70#[derive(Deref)]
71pub struct HttpClientWithProxy {
72 #[deref]
73 client: Arc<dyn HttpClient>,
74 proxy: Option<Uri>,
75}
76
77impl HttpClientWithProxy {
78 /// Returns a new [`HttpClientWithProxy`] with the given proxy URL.
79 pub fn new(client: Arc<dyn HttpClient>, proxy_url: Option<String>) -> Self {
80 let proxy_uri = proxy_url
81 .and_then(|proxy| proxy.parse().ok())
82 .or_else(read_proxy_from_env);
83
84 Self::new_uri(client, proxy_uri)
85 }
86 pub fn new_uri(client: Arc<dyn HttpClient>, proxy_uri: Option<Uri>) -> Self {
87 Self {
88 client,
89 proxy: proxy_uri,
90 }
91 }
92}
93
94impl HttpClient for HttpClientWithProxy {
95 fn send_with_redirect_policy(
96 &self,
97 req: Request<AsyncBody>,
98 follow_redirects: bool,
99 ) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>> {
100 self.client.send_with_redirect_policy(req, follow_redirects)
101 }
102
103 fn proxy(&self) -> Option<&Uri> {
104 self.proxy.as_ref()
105 }
106}
107
108impl HttpClient for Arc<HttpClientWithProxy> {
109 fn send_with_redirect_policy(
110 &self,
111 req: Request<AsyncBody>,
112 follow_redirects: bool,
113 ) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>> {
114 self.client.send_with_redirect_policy(req, follow_redirects)
115 }
116
117 fn proxy(&self) -> Option<&Uri> {
118 self.proxy.as_ref()
119 }
120}
121
122/// An [`HttpClient`] that has a base URL.
123pub struct HttpClientWithUrl {
124 base_url: Mutex<String>,
125 client: HttpClientWithProxy,
126}
127
128impl std::ops::Deref for HttpClientWithUrl {
129 type Target = HttpClientWithProxy;
130
131 fn deref(&self) -> &Self::Target {
132 &self.client
133 }
134}
135
136impl HttpClientWithUrl {
137 /// Returns a new [`HttpClientWithUrl`] with the given base URL.
138 pub fn new(
139 client: Arc<dyn HttpClient>,
140 base_url: impl Into<String>,
141 proxy_url: Option<String>,
142 ) -> Self {
143 let client = HttpClientWithProxy::new(client, proxy_url);
144
145 Self {
146 base_url: Mutex::new(base_url.into()),
147 client,
148 }
149 }
150
151 pub fn new_uri(
152 client: Arc<dyn HttpClient>,
153 base_url: impl Into<String>,
154 proxy_uri: Option<Uri>,
155 ) -> Self {
156 let client = HttpClientWithProxy::new_uri(client, proxy_uri);
157
158 Self {
159 base_url: Mutex::new(base_url.into()),
160 client,
161 }
162 }
163
164 /// Returns the base URL.
165 pub fn base_url(&self) -> String {
166 self.base_url
167 .lock()
168 .map_or_else(|_| Default::default(), |url| url.clone())
169 }
170
171 /// Sets the base URL.
172 pub fn set_base_url(&self, base_url: impl Into<String>) {
173 let base_url = base_url.into();
174 self.base_url
175 .lock()
176 .map(|mut url| {
177 *url = base_url;
178 })
179 .ok();
180 }
181
182 /// Builds a URL using the given path.
183 pub fn build_url(&self, path: &str) -> String {
184 format!("{}{}", self.base_url(), path)
185 }
186
187 /// Builds a Zed API URL using the given path.
188 pub fn build_zed_api_url(&self, path: &str, query: &[(&str, &str)]) -> Result<Url> {
189 let base_url = self.base_url();
190 let base_api_url = match base_url.as_ref() {
191 "https://zed.dev" => "https://api.zed.dev",
192 "https://staging.zed.dev" => "https://api-staging.zed.dev",
193 "http://localhost:3000" => "http://localhost:8080",
194 other => other,
195 };
196
197 Ok(Url::parse_with_params(
198 &format!("{}{}", base_api_url, path),
199 query,
200 )?)
201 }
202
203 /// Builds a Zed LLM URL using the given path.
204 pub fn build_zed_llm_url(&self, path: &str, query: &[(&str, &str)]) -> Result<Url> {
205 let base_url = self.base_url();
206 let base_api_url = match base_url.as_ref() {
207 "https://zed.dev" => "https://llm.zed.dev",
208 "https://staging.zed.dev" => "https://llm-staging.zed.dev",
209 "http://localhost:3000" => "http://localhost:8080",
210 other => other,
211 };
212
213 Ok(Url::parse_with_params(
214 &format!("{}{}", base_api_url, path),
215 query,
216 )?)
217 }
218}
219
220impl HttpClient for Arc<HttpClientWithUrl> {
221 fn send_with_redirect_policy(
222 &self,
223 req: Request<AsyncBody>,
224 follow_redirects: bool,
225 ) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>> {
226 self.client.send_with_redirect_policy(req, follow_redirects)
227 }
228
229 fn proxy(&self) -> Option<&Uri> {
230 self.client.proxy.as_ref()
231 }
232}
233
234impl HttpClient for HttpClientWithUrl {
235 fn send_with_redirect_policy(
236 &self,
237 req: Request<AsyncBody>,
238 follow_redirects: bool,
239 ) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>> {
240 self.client.send_with_redirect_policy(req, follow_redirects)
241 }
242
243 fn proxy(&self) -> Option<&Uri> {
244 self.client.proxy.as_ref()
245 }
246}
247
248pub fn read_proxy_from_env() -> Option<Uri> {
249 const ENV_VARS: &[&str] = &[
250 "ALL_PROXY",
251 "all_proxy",
252 "HTTPS_PROXY",
253 "https_proxy",
254 "HTTP_PROXY",
255 "http_proxy",
256 ];
257
258 for var in ENV_VARS {
259 if let Ok(env) = std::env::var(var) {
260 return env.parse::<Uri>().ok();
261 }
262 }
263
264 None
265}
266
267#[cfg(feature = "test-support")]
268type FakeHttpHandler = Box<
269 dyn Fn(Request<AsyncBody>) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>>
270 + Send
271 + Sync
272 + 'static,
273>;
274
275#[cfg(feature = "test-support")]
276pub struct FakeHttpClient {
277 handler: FakeHttpHandler,
278}
279
280#[cfg(feature = "test-support")]
281impl FakeHttpClient {
282 pub fn create<Fut, F>(handler: F) -> Arc<HttpClientWithUrl>
283 where
284 Fut: futures::Future<Output = Result<Response<AsyncBody>, anyhow::Error>> + Send + 'static,
285 F: Fn(Request<AsyncBody>) -> Fut + Send + Sync + 'static,
286 {
287 Arc::new(HttpClientWithUrl {
288 base_url: Mutex::new("http://test.example".into()),
289 client: HttpClientWithProxy {
290 client: Arc::new(Self {
291 handler: Box::new(move |req| Box::pin(handler(req))),
292 }),
293 proxy: None,
294 },
295 })
296 }
297
298 pub fn with_404_response() -> Arc<HttpClientWithUrl> {
299 Self::create(|_| async move {
300 Ok(Response::builder()
301 .status(404)
302 .body(Default::default())
303 .unwrap())
304 })
305 }
306
307 pub fn with_200_response() -> Arc<HttpClientWithUrl> {
308 Self::create(|_| async move {
309 Ok(Response::builder()
310 .status(200)
311 .body(Default::default())
312 .unwrap())
313 })
314 }
315}
316
317#[cfg(feature = "test-support")]
318impl fmt::Debug for FakeHttpClient {
319 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320 f.debug_struct("FakeHttpClient").finish()
321 }
322}
323
324#[cfg(feature = "test-support")]
325impl HttpClient for FakeHttpClient {
326 fn send_with_redirect_policy(
327 &self,
328 req: Request<AsyncBody>,
329 _follow_redirects: bool,
330 ) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>> {
331 let future = (self.handler)(req);
332 future
333 }
334
335 fn proxy(&self) -> Option<&Uri> {
336 None
337 }
338}