Start work on connecting to RPC endpoint

Co-Authored-By: Antonio Scandurra <me@as-cii.com>
This commit is contained in:
Max Brunsfeld 2021-06-10 22:12:04 -07:00
parent e897d1c98e
commit 20542f54ef
9 changed files with 1118 additions and 90 deletions

969
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -2,7 +2,7 @@ use crate::{
elements::ElementBox,
executor,
keymap::{self, Keystroke},
platform::{self, PromptLevel, WindowOptions},
platform::{self, Platform, PromptLevel, WindowOptions},
presenter::Presenter,
util::{post_inc, timeout},
AssetCache, AssetSource, ClipboardItem, FontCache, PathPromptOptions, TextLayoutCache,
@ -412,6 +412,10 @@ impl AsyncAppContext {
self.update(|cx| cx.add_model(build_model))
}
pub fn platform(&self) -> Arc<dyn Platform> {
self.0.borrow().platform()
}
pub fn background_executor(&self) -> Arc<executor::Background> {
self.0.borrow().cx.background.clone()
}

View file

@ -12,6 +12,7 @@ futures-lite = "1"
prost = "0.7"
rsa = "0.4"
rand = "0.8"
serde = { version = "1", features = ["derive"] }
[build-dependencies]
prost-build = { git = "https://github.com/sfackler/prost", rev = "082f3e65874fe91382e72482863896b7b4db3728" }

View file

@ -1,2 +1,3 @@
pub mod auth;
pub mod proto;
pub mod rest;

7
zed-rpc/src/rest.rs Normal file
View file

@ -0,0 +1,7 @@
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct CreateWorktreeResponse {
pub worktree_id: u64,
pub rpc_address: String,
}

View file

@ -23,6 +23,7 @@ easy-parallel = "3.1.0"
fsevent = { path = "../fsevent" }
futures-core = "0.3"
gpui = { path = "../gpui" }
http-auth-basic = "0.1.3"
ignore = "0.4"
lazy_static = "1.4.0"
libc = "0.2"
@ -39,6 +40,7 @@ similar = "1.3"
simplelog = "0.9"
smallvec = { version = "1.6", features = ["union"] }
smol = "1.2.5"
surf = "2.2"
toml = "0.5"
tree-sitter = "0.19.5"
tree-sitter-rust = "0.19.0"

View file

@ -1,8 +1,9 @@
use anyhow::{anyhow, Context};
use gpui::MutableAppContext;
use anyhow::{anyhow, Context, Result};
use gpui::{AsyncAppContext, MutableAppContext, Task};
use smol::io::{AsyncBufReadExt, AsyncWriteExt};
use std::convert::TryFrom;
use url::Url;
use util::SurfResultExt;
pub mod assets;
pub mod editor;
@ -26,16 +27,52 @@ pub struct AppState {
}
pub fn init(cx: &mut MutableAppContext) {
cx.add_global_action("app:authenticate", authenticate);
cx.add_global_action("app:share_worktree", share_worktree);
cx.add_global_action("app:quit", quit);
}
fn authenticate(_: &(), cx: &mut MutableAppContext) {
fn share_worktree(_: &(), cx: &mut MutableAppContext) {
let zed_url = std::env::var("ZED_SERVER_URL").unwrap_or("https://zed.dev".to_string());
let platform = cx.platform().clone();
cx.spawn::<_, _, surf::Result<()>>(|cx| async move {
let (user_id, access_token) = login(zed_url.clone(), cx).await?;
cx.background_executor()
.spawn(async move {
let mut response = surf::post(format!("{}/api/worktrees", &zed_url))
.header(
"Authorization",
http_auth_basic::Credentials::new(&user_id, &access_token).as_http_header(),
)
.await
.context("")?;
let body = response
.body_json::<zed_rpc::rest::CreateWorktreeResponse>()
.await?;
// TODO - If the `ZED_SERVER_URL` uses https, then wrap this stream in
// a TLS stream using `native-tls`.
let stream = smol::net::TcpStream::connect(body.rpc_address).await?;
let mut message_stream = zed_rpc::proto::MessageStream::new(stream);
message_stream
.write_message(&zed_rpc::proto::FromClient {
id: 0,
variant: Some(zed_rpc::proto::from_client::Variant::Auth(
zed_rpc::proto::from_client::Auth {
user_id: user_id.parse::<i32>()?,
access_token,
},
)),
})
.await?;
Ok(())
})
.detach();
}
fn login(zed_url: String, cx: AsyncAppContext) -> Task<Result<(String, String)>> {
let platform = cx.platform();
cx.background_executor().spawn(async move {
if let Some((user_id, access_token)) = platform.read_credentials(&zed_url) {
log::info!("already signed in. user_id: {}", user_id);
return Ok((user_id, String::from_utf8(access_token).unwrap()));
@ -113,7 +150,6 @@ fn authenticate(_: &(), cx: &mut MutableAppContext) {
Ok((user_id.to_string(), access_token))
})
.detach();
}
fn quit(_: &(), cx: &mut MutableAppContext) {

View file

@ -15,9 +15,9 @@ pub fn menus(state: AppState) -> Vec<Menu<'static>> {
},
MenuItem::Separator,
MenuItem::Action {
name: "Log In",
name: "Share",
keystroke: None,
action: "app:authenticate",
action: "app:share_worktree",
arg: None,
},
MenuItem::Action {

View file

@ -106,3 +106,33 @@ mod tests {
assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
}
}
// Allow surf Results to accept context like other Results do when
// using anyhow.
pub trait SurfResultExt {
fn context<C>(self, cx: C) -> Self
where
C: std::fmt::Display + Send + Sync + 'static;
fn with_context<C, F>(self, f: F) -> Self
where
C: std::fmt::Display + Send + Sync + 'static,
F: FnOnce() -> C;
}
impl<T> SurfResultExt for surf::Result<T> {
fn context<C>(self, cx: C) -> Self
where
C: std::fmt::Display + Send + Sync + 'static,
{
self.map_err(|e| surf::Error::new(e.status(), e.into_inner().context(cx)))
}
fn with_context<C, F>(self, f: F) -> Self
where
C: std::fmt::Display + Send + Sync + 'static,
F: FnOnce() -> C,
{
self.map_err(|e| surf::Error::new(e.status(), e.into_inner().context(f())))
}
}