Remove async-std and surf from client
Switch to isahc library. It's not as fancy, but it works and has a smaller footprint.
This commit is contained in:
@@ -14,10 +14,10 @@ settings = { path = "../settings" }
|
||||
theme = { path = "../theme" }
|
||||
workspace = { path = "../workspace" }
|
||||
anyhow = "1.0.38"
|
||||
isahc = "1.7"
|
||||
lazy_static = "1.4"
|
||||
log = "0.4"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = { version = "1.0.64", features = ["preserve_order"] }
|
||||
smol = "1.2.5"
|
||||
surf = "2.2"
|
||||
tempdir = "0.3.7"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use client::http::{self, HttpClient};
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use client::http::HttpClient;
|
||||
|
||||
use gpui::{
|
||||
actions,
|
||||
elements::{Empty, MouseEventHandler, Text},
|
||||
@@ -12,7 +13,6 @@ use serde::Deserialize;
|
||||
use settings::Settings;
|
||||
use smol::{fs::File, io::AsyncReadExt, process::Command};
|
||||
use std::{env, ffi::OsString, path::PathBuf, sync::Arc, time::Duration};
|
||||
use surf::Request;
|
||||
use workspace::{ItemHandle, StatusItemView};
|
||||
|
||||
const POLL_INTERVAL: Duration = Duration::from_secs(60 * 60);
|
||||
@@ -52,7 +52,7 @@ pub struct AutoUpdateIndicator {
|
||||
#[derive(Deserialize)]
|
||||
struct JsonRelease {
|
||||
version: String,
|
||||
url: http::Url,
|
||||
url: String,
|
||||
}
|
||||
|
||||
impl Entity for AutoUpdater {
|
||||
@@ -134,17 +134,21 @@ impl AutoUpdater {
|
||||
)
|
||||
});
|
||||
let mut response = client
|
||||
.send(Request::new(
|
||||
http::Method::Get,
|
||||
http::Url::parse(&format!(
|
||||
"{server_url}/api/releases/latest?token={ACCESS_TOKEN}&asset=Zed.dmg"
|
||||
))?,
|
||||
))
|
||||
.get(
|
||||
&format!("{server_url}/api/releases/latest?token={ACCESS_TOKEN}&asset=Zed.dmg"),
|
||||
Default::default(),
|
||||
)
|
||||
.await?;
|
||||
let release = response
|
||||
.body_json::<JsonRelease>()
|
||||
|
||||
let mut body = Vec::new();
|
||||
response
|
||||
.body_mut()
|
||||
.read_to_end(&mut body)
|
||||
.await
|
||||
.map_err(|err| anyhow!("error deserializing release {:?}", err))?;
|
||||
.context("error reading release")?;
|
||||
let release: JsonRelease =
|
||||
serde_json::from_slice(body.as_slice()).context("error deserializing release")?;
|
||||
|
||||
let latest_version = release.version.parse::<AppVersion>()?;
|
||||
if latest_version <= current_version {
|
||||
this.update(&mut cx, |this, cx| {
|
||||
@@ -169,10 +173,8 @@ impl AutoUpdater {
|
||||
.map_or_else(|| cx.platform().app_path(), Ok)?;
|
||||
|
||||
let mut dmg_file = File::create(&dmg_path).await?;
|
||||
let response = client
|
||||
.send(Request::new(http::Method::Get, release.url))
|
||||
.await?;
|
||||
smol::io::copy(response.bytes(), &mut dmg_file).await?;
|
||||
let mut response = client.get(&release.url, Default::default()).await?;
|
||||
smol::io::copy(response.body_mut(), &mut dmg_file).await?;
|
||||
log::info!("downloaded update. path:{:?}", dmg_path);
|
||||
|
||||
this.update(&mut cx, |this, cx| {
|
||||
|
||||
@@ -20,16 +20,17 @@ async-recursion = "0.3"
|
||||
async-tungstenite = { version = "0.16", features = ["async-tls"] }
|
||||
futures = "0.3"
|
||||
image = "0.23"
|
||||
isahc = "1.7"
|
||||
lazy_static = "1.4.0"
|
||||
log = { version = "0.4.16", features = ["kv_unstable_serde"] }
|
||||
parking_lot = "0.11.1"
|
||||
postage = { version = "0.4.1", features = ["futures-traits"] }
|
||||
rand = "0.8.3"
|
||||
smol = "1.2.5"
|
||||
surf = "2.2"
|
||||
thiserror = "1.0.29"
|
||||
time = "0.3"
|
||||
tiny_http = "0.8"
|
||||
url = "2.2"
|
||||
|
||||
[dev-dependencies]
|
||||
gpui = { path = "../gpui", features = ["test-support"] }
|
||||
|
||||
@@ -594,14 +594,13 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::test::{FakeHttpClient, FakeServer};
|
||||
use gpui::TestAppContext;
|
||||
use surf::http::Response;
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_channel_messages(cx: &mut TestAppContext) {
|
||||
cx.foreground().forbid_parking();
|
||||
|
||||
let user_id = 5;
|
||||
let http_client = FakeHttpClient::new(|_| async move { Ok(Response::new(404)) });
|
||||
let http_client = FakeHttpClient::with_404_response();
|
||||
let mut client = Client::new(http_client.clone());
|
||||
let server = FakeServer::for_client(user_id, &mut client, &cx).await;
|
||||
|
||||
|
||||
+11
-12
@@ -34,8 +34,8 @@ use std::{
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use surf::{http::Method, Url};
|
||||
use thiserror::Error;
|
||||
use url::Url;
|
||||
use util::{ResultExt, TryFutureExt};
|
||||
|
||||
pub use channel::*;
|
||||
@@ -89,9 +89,11 @@ pub enum EstablishConnectionError {
|
||||
#[error("{0}")]
|
||||
Other(#[from] anyhow::Error),
|
||||
#[error("{0}")]
|
||||
Http(#[from] http::Error),
|
||||
#[error("{0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("{0}")]
|
||||
Http(#[from] async_tungstenite::tungstenite::http::Error),
|
||||
Websocket(#[from] async_tungstenite::tungstenite::http::Error),
|
||||
}
|
||||
|
||||
impl From<WebsocketError> for EstablishConnectionError {
|
||||
@@ -779,30 +781,27 @@ impl Client {
|
||||
let http = self.http.clone();
|
||||
cx.background().spawn(async move {
|
||||
let mut rpc_url = format!("{}/rpc", *ZED_SERVER_URL);
|
||||
let rpc_request = surf::Request::new(
|
||||
Method::Get,
|
||||
surf::Url::parse(&rpc_url).context("invalid ZED_SERVER_URL")?,
|
||||
);
|
||||
let rpc_response = http.send(rpc_request).await?;
|
||||
|
||||
let rpc_response = http.get(&rpc_url, Default::default()).await?;
|
||||
if rpc_response.status().is_redirection() {
|
||||
rpc_url = rpc_response
|
||||
.header("Location")
|
||||
.headers()
|
||||
.get("Location")
|
||||
.ok_or_else(|| anyhow!("missing location header in /rpc response"))?
|
||||
.as_str()
|
||||
.to_str()
|
||||
.map_err(|error| EstablishConnectionError::other(error))?
|
||||
.to_string();
|
||||
}
|
||||
// Until we switch the zed.dev domain to point to the new Next.js app, there
|
||||
// will be no redirect required, and the app will connect directly to
|
||||
// wss://zed.dev/rpc.
|
||||
else if rpc_response.status() != surf::StatusCode::UpgradeRequired {
|
||||
else if rpc_response.status() != StatusCode::UPGRADE_REQUIRED {
|
||||
Err(anyhow!(
|
||||
"unexpected /rpc response status {}",
|
||||
rpc_response.status()
|
||||
))?
|
||||
}
|
||||
|
||||
let mut rpc_url = surf::Url::parse(&rpc_url).context("invalid rpc url")?;
|
||||
let mut rpc_url = Url::parse(&rpc_url).context("invalid rpc url")?;
|
||||
let rpc_host = rpc_url
|
||||
.host_str()
|
||||
.zip(rpc_url.port_or_known_default())
|
||||
|
||||
+34
-15
@@ -1,26 +1,45 @@
|
||||
pub use anyhow::{anyhow, Result};
|
||||
use futures::future::BoxFuture;
|
||||
use std::sync::Arc;
|
||||
pub use surf::{
|
||||
http::{Method, Response as ServerResponse},
|
||||
Request, Response, Url,
|
||||
use isahc::{
|
||||
config::{Configurable, RedirectPolicy},
|
||||
AsyncBody,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use anyhow::{anyhow, Result};
|
||||
pub use isahc::{
|
||||
http::{Method, Uri},
|
||||
Error,
|
||||
};
|
||||
pub use url::Url;
|
||||
|
||||
pub type Request = isahc::Request<AsyncBody>;
|
||||
pub type Response = isahc::Response<AsyncBody>;
|
||||
|
||||
pub trait HttpClient: Send + Sync {
|
||||
fn send<'a>(&'a self, req: Request) -> BoxFuture<'a, Result<Response>>;
|
||||
fn send<'a>(&'a self, req: Request) -> BoxFuture<'a, Result<Response, Error>>;
|
||||
|
||||
fn get<'a>(&'a self, uri: &str, body: AsyncBody) -> BoxFuture<'a, Result<Response, Error>> {
|
||||
self.send(
|
||||
isahc::Request::builder()
|
||||
.method(Method::GET)
|
||||
.uri(uri)
|
||||
.body(body)
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn client() -> Arc<dyn HttpClient> {
|
||||
Arc::new(surf::client())
|
||||
Arc::new(
|
||||
isahc::HttpClient::builder()
|
||||
.redirect_policy(RedirectPolicy::Follow)
|
||||
.build()
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
impl HttpClient for surf::Client {
|
||||
fn send<'a>(&'a self, req: Request) -> BoxFuture<'a, Result<Response>> {
|
||||
Box::pin(async move {
|
||||
Ok(self
|
||||
.send(req)
|
||||
.await
|
||||
.map_err(|e| anyhow!("http request failed: {}", e))?)
|
||||
})
|
||||
impl HttpClient for isahc::HttpClient {
|
||||
fn send<'a>(&'a self, req: Request) -> BoxFuture<'a, Result<Response, Error>> {
|
||||
Box::pin(async move { self.send_async(req).await })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{
|
||||
http::{HttpClient, Request, Response, ServerResponse},
|
||||
http::{self, HttpClient, Request, Response},
|
||||
Client, Connection, Credentials, EstablishConnectionError, UserStore,
|
||||
};
|
||||
use anyhow::{anyhow, Result};
|
||||
@@ -176,14 +176,18 @@ impl FakeServer {
|
||||
}
|
||||
|
||||
pub struct FakeHttpClient {
|
||||
handler:
|
||||
Box<dyn 'static + Send + Sync + Fn(Request) -> BoxFuture<'static, Result<ServerResponse>>>,
|
||||
handler: Box<
|
||||
dyn 'static
|
||||
+ Send
|
||||
+ Sync
|
||||
+ Fn(Request) -> BoxFuture<'static, Result<Response, http::Error>>,
|
||||
>,
|
||||
}
|
||||
|
||||
impl FakeHttpClient {
|
||||
pub fn new<Fut, F>(handler: F) -> Arc<dyn HttpClient>
|
||||
where
|
||||
Fut: 'static + Send + Future<Output = Result<ServerResponse>>,
|
||||
Fut: 'static + Send + Future<Output = Result<Response, http::Error>>,
|
||||
F: 'static + Send + Sync + Fn(Request) -> Fut,
|
||||
{
|
||||
Arc::new(Self {
|
||||
@@ -192,7 +196,12 @@ impl FakeHttpClient {
|
||||
}
|
||||
|
||||
pub fn with_404_response() -> Arc<dyn HttpClient> {
|
||||
Self::new(|_| async move { Ok(ServerResponse::new(404)) })
|
||||
Self::new(|_| async move {
|
||||
Ok(isahc::Response::builder()
|
||||
.status(404)
|
||||
.body(Default::default())
|
||||
.unwrap())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,7 +212,7 @@ impl fmt::Debug for FakeHttpClient {
|
||||
}
|
||||
|
||||
impl HttpClient for FakeHttpClient {
|
||||
fn send<'a>(&'a self, req: Request) -> BoxFuture<'a, Result<Response>> {
|
||||
fn send<'a>(&'a self, req: Request) -> BoxFuture<'a, Result<Response, crate::http::Error>> {
|
||||
let future = (self.handler)(req);
|
||||
Box::pin(async move { future.await.map(Into::into) })
|
||||
}
|
||||
|
||||
+12
-15
@@ -1,9 +1,6 @@
|
||||
use super::{
|
||||
http::{HttpClient, Method, Request, Url},
|
||||
proto, Client, Status, TypedEnvelope,
|
||||
};
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use futures::future;
|
||||
use super::{http::HttpClient, proto, Client, Status, TypedEnvelope};
|
||||
use anyhow::{anyhow, Result};
|
||||
use futures::{future, AsyncReadExt};
|
||||
use gpui::{AsyncAppContext, Entity, ImageData, ModelContext, ModelHandle, Task};
|
||||
use postage::{prelude::Stream, sink::Sink, watch};
|
||||
use std::{
|
||||
@@ -255,22 +252,22 @@ impl Contact {
|
||||
}
|
||||
|
||||
async fn fetch_avatar(http: &dyn HttpClient, url: &str) -> Result<Arc<ImageData>> {
|
||||
let url = Url::parse(url).with_context(|| format!("failed to parse avatar url {:?}", url))?;
|
||||
let mut request = Request::new(Method::Get, url);
|
||||
request.middleware(surf::middleware::Redirect::default());
|
||||
|
||||
let mut response = http
|
||||
.send(request)
|
||||
.get(url, Default::default())
|
||||
.await
|
||||
.map_err(|e| anyhow!("failed to send user avatar request: {}", e))?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(anyhow!("avatar request failed {:?}", response.status()));
|
||||
}
|
||||
let bytes = response
|
||||
.body_bytes()
|
||||
|
||||
let mut body = Vec::new();
|
||||
response
|
||||
.body_mut()
|
||||
.read_to_end(&mut body)
|
||||
.await
|
||||
.map_err(|e| anyhow!("failed to read user avatar response body: {}", e))?;
|
||||
let format = image::guess_format(&bytes)?;
|
||||
let image = image::load_from_memory_with_format(&bytes, format)?.into_bgra8();
|
||||
let format = image::guess_format(&body)?;
|
||||
let image = image::load_from_memory_with_format(&body, format)?.into_bgra8();
|
||||
Ok(ImageData::new(image))
|
||||
}
|
||||
|
||||
@@ -623,9 +623,7 @@ impl WorkspaceParams {
|
||||
|
||||
let fs = project::FakeFs::new(cx.background().clone());
|
||||
let languages = Arc::new(LanguageRegistry::test());
|
||||
let http_client = client::test::FakeHttpClient::new(|_| async move {
|
||||
Ok(client::http::ServerResponse::new(404))
|
||||
});
|
||||
let http_client = client::test::FakeHttpClient::with_404_response();
|
||||
let client = Client::new(http_client.clone());
|
||||
let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
|
||||
let project = Project::local(
|
||||
|
||||
@@ -62,6 +62,7 @@ http-auth-basic = "0.1.3"
|
||||
ignore = "0.4"
|
||||
image = "0.23"
|
||||
indexmap = "1.6.2"
|
||||
isahc = "1.7"
|
||||
lazy_static = "1.4.0"
|
||||
libc = "0.2"
|
||||
log = { version = "0.4.16", features = ["kv_unstable_serde"] }
|
||||
@@ -79,7 +80,6 @@ serde_path_to_error = "0.1.4"
|
||||
simplelog = "0.9"
|
||||
smallvec = { version = "1.6", features = ["union"] }
|
||||
smol = "1.2.5"
|
||||
surf = "2.2"
|
||||
tempdir = { version = "0.3.7" }
|
||||
thiserror = "1.0.29"
|
||||
tiny_http = "0.8"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::installation::{latest_github_release, GitHubLspBinaryVersion};
|
||||
use anyhow::{anyhow, Result};
|
||||
use client::http::{HttpClient, Method};
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use client::http::HttpClient;
|
||||
use futures::{future::BoxFuture, FutureExt, StreamExt};
|
||||
pub use language::*;
|
||||
use smol::fs::{self, File};
|
||||
@@ -41,14 +41,10 @@ impl super::LspAdapter for CLspAdapter {
|
||||
let binary_path = version_dir.join("bin/clangd");
|
||||
|
||||
if fs::metadata(&binary_path).await.is_err() {
|
||||
let response = http
|
||||
.send(
|
||||
surf::RequestBuilder::new(Method::Get, version.url)
|
||||
.middleware(surf::middleware::Redirect::default())
|
||||
.build(),
|
||||
)
|
||||
let mut response = http
|
||||
.get(&version.url, Default::default())
|
||||
.await
|
||||
.map_err(|err| anyhow!("error downloading release: {}", err))?;
|
||||
.context("error downloading release")?;
|
||||
let mut file = File::create(&zip_path).await?;
|
||||
if !response.status().is_success() {
|
||||
Err(anyhow!(
|
||||
@@ -56,7 +52,7 @@ impl super::LspAdapter for CLspAdapter {
|
||||
response.status().to_string()
|
||||
))?;
|
||||
}
|
||||
futures::io::copy(response, &mut file).await?;
|
||||
futures::io::copy(response.body_mut(), &mut file).await?;
|
||||
|
||||
let unzip_status = smol::process::Command::new("unzip")
|
||||
.current_dir(&container_dir)
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use client::http::{self, HttpClient, Method};
|
||||
use client::http::HttpClient;
|
||||
|
||||
use serde::Deserialize;
|
||||
use smol::io::AsyncReadExt;
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
pub struct GitHubLspBinaryVersion {
|
||||
pub name: String,
|
||||
pub url: http::Url,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -30,7 +32,7 @@ pub(crate) struct GithubRelease {
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct GithubReleaseAsset {
|
||||
name: String,
|
||||
browser_download_url: http::Url,
|
||||
browser_download_url: String,
|
||||
}
|
||||
|
||||
pub async fn npm_package_latest_version(name: &str) -> Result<String> {
|
||||
@@ -81,23 +83,23 @@ pub async fn latest_github_release(
|
||||
http: Arc<dyn HttpClient>,
|
||||
asset_name: impl Fn(&str) -> String,
|
||||
) -> Result<GitHubLspBinaryVersion> {
|
||||
let release = http
|
||||
.send(
|
||||
surf::RequestBuilder::new(
|
||||
Method::Get,
|
||||
http::Url::parse(&format!(
|
||||
"https://api.github.com/repos/{repo_name_with_owner}/releases/latest"
|
||||
))
|
||||
.unwrap(),
|
||||
)
|
||||
.middleware(surf::middleware::Redirect::default())
|
||||
.build(),
|
||||
let mut response = http
|
||||
.get(
|
||||
&format!("https://api.github.com/repos/{repo_name_with_owner}/releases/latest"),
|
||||
Default::default(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| anyhow!("error fetching latest release: {}", err))?
|
||||
.body_json::<GithubRelease>()
|
||||
.context("error fetching latest release")?;
|
||||
|
||||
let mut body = Vec::new();
|
||||
response
|
||||
.body_mut()
|
||||
.read_to_end(&mut body)
|
||||
.await
|
||||
.map_err(|err| anyhow!("error parsing latest release: {}", err))?;
|
||||
.context("error reading latest release")?;
|
||||
|
||||
let release: GithubRelease =
|
||||
serde_json::from_slice(body.as_slice()).context("error deserializing latest release")?;
|
||||
let asset_name = asset_name(&release.name);
|
||||
let asset = release
|
||||
.assets
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::installation::{latest_github_release, GitHubLspBinaryVersion};
|
||||
use anyhow::{anyhow, Result};
|
||||
use async_compression::futures::bufread::GzipDecoder;
|
||||
use client::http::{HttpClient, Method};
|
||||
use futures::{future::BoxFuture, FutureExt, StreamExt};
|
||||
use client::http::HttpClient;
|
||||
use futures::{future::BoxFuture, io::BufReader, FutureExt, StreamExt};
|
||||
pub use language::*;
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
@@ -42,15 +42,11 @@ impl LspAdapter for RustLspAdapter {
|
||||
let destination_path = container_dir.join(format!("rust-analyzer-{}", version.name));
|
||||
|
||||
if fs::metadata(&destination_path).await.is_err() {
|
||||
let response = http
|
||||
.send(
|
||||
surf::RequestBuilder::new(Method::Get, version.url)
|
||||
.middleware(surf::middleware::Redirect::default())
|
||||
.build(),
|
||||
)
|
||||
let mut response = http
|
||||
.get(&version.url, Default::default())
|
||||
.await
|
||||
.map_err(|err| anyhow!("error downloading release: {}", err))?;
|
||||
let decompressed_bytes = GzipDecoder::new(response);
|
||||
let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
|
||||
let mut file = File::create(&destination_path).await?;
|
||||
futures::io::copy(decompressed_bytes, &mut file).await?;
|
||||
fs::set_permissions(
|
||||
|
||||
Reference in New Issue
Block a user