client.rs

   1#[cfg(any(test, feature = "test-support"))]
   2pub mod test;
   3
   4pub mod channel;
   5pub mod http;
   6pub mod user;
   7
   8use anyhow::{anyhow, Context, Result};
   9use async_recursion::async_recursion;
  10use async_tungstenite::tungstenite::{
  11    error::Error as WebsocketError,
  12    http::{Request, StatusCode},
  13};
  14use futures::{future::LocalBoxFuture, FutureExt, StreamExt};
  15use gpui::{
  16    action, AnyModelHandle, AnyWeakModelHandle, AsyncAppContext, Entity, ModelContext, ModelHandle,
  17    MutableAppContext, Task,
  18};
  19use http::HttpClient;
  20use lazy_static::lazy_static;
  21use parking_lot::RwLock;
  22use postage::watch;
  23use rand::prelude::*;
  24use rpc::proto::{AnyTypedEnvelope, EntityMessage, EnvelopedMessage, RequestMessage};
  25use std::{
  26    any::TypeId,
  27    collections::HashMap,
  28    convert::TryFrom,
  29    fmt::Write as _,
  30    future::Future,
  31    sync::{
  32        atomic::{AtomicUsize, Ordering},
  33        Arc, Weak,
  34    },
  35    time::{Duration, Instant},
  36};
  37use surf::{http::Method, Url};
  38use thiserror::Error;
  39use util::{ResultExt, TryFutureExt};
  40
  41pub use channel::*;
  42pub use rpc::*;
  43pub use user::*;
  44
  45lazy_static! {
  46    static ref ZED_SERVER_URL: String =
  47        std::env::var("ZED_SERVER_URL").unwrap_or("https://zed.dev".to_string());
  48    static ref IMPERSONATE_LOGIN: Option<String> = std::env::var("ZED_IMPERSONATE")
  49        .ok()
  50        .and_then(|s| if s.is_empty() { None } else { Some(s) });
  51}
  52
  53action!(Authenticate);
  54
  55pub fn init(rpc: Arc<Client>, cx: &mut MutableAppContext) {
  56    cx.add_global_action(move |_: &Authenticate, cx| {
  57        let rpc = rpc.clone();
  58        cx.spawn(|cx| async move { rpc.authenticate_and_connect(&cx).log_err().await })
  59            .detach();
  60    });
  61}
  62
  63pub struct Client {
  64    id: usize,
  65    peer: Arc<Peer>,
  66    http: Arc<dyn HttpClient>,
  67    state: RwLock<ClientState>,
  68    authenticate:
  69        Option<Box<dyn 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>>>,
  70    establish_connection: Option<
  71        Box<
  72            dyn 'static
  73                + Send
  74                + Sync
  75                + Fn(
  76                    &Credentials,
  77                    &AsyncAppContext,
  78                ) -> Task<Result<Connection, EstablishConnectionError>>,
  79        >,
  80    >,
  81}
  82
  83#[derive(Error, Debug)]
  84pub enum EstablishConnectionError {
  85    #[error("upgrade required")]
  86    UpgradeRequired,
  87    #[error("unauthorized")]
  88    Unauthorized,
  89    #[error("{0}")]
  90    Other(#[from] anyhow::Error),
  91    #[error("{0}")]
  92    Io(#[from] std::io::Error),
  93    #[error("{0}")]
  94    Http(#[from] async_tungstenite::tungstenite::http::Error),
  95}
  96
  97impl From<WebsocketError> for EstablishConnectionError {
  98    fn from(error: WebsocketError) -> Self {
  99        if let WebsocketError::Http(response) = &error {
 100            match response.status() {
 101                StatusCode::UNAUTHORIZED => return EstablishConnectionError::Unauthorized,
 102                StatusCode::UPGRADE_REQUIRED => return EstablishConnectionError::UpgradeRequired,
 103                _ => {}
 104            }
 105        }
 106        EstablishConnectionError::Other(error.into())
 107    }
 108}
 109
 110impl EstablishConnectionError {
 111    pub fn other(error: impl Into<anyhow::Error> + Send + Sync) -> Self {
 112        Self::Other(error.into())
 113    }
 114}
 115
 116#[derive(Copy, Clone, Debug)]
 117pub enum Status {
 118    SignedOut,
 119    UpgradeRequired,
 120    Authenticating,
 121    Connecting,
 122    ConnectionError,
 123    Connected { connection_id: ConnectionId },
 124    ConnectionLost,
 125    Reauthenticating,
 126    Reconnecting,
 127    ReconnectionError { next_reconnection: Instant },
 128}
 129
 130struct ClientState {
 131    credentials: Option<Credentials>,
 132    status: (watch::Sender<Status>, watch::Receiver<Status>),
 133    entity_id_extractors: HashMap<TypeId, Box<dyn Send + Sync + Fn(&dyn AnyTypedEnvelope) -> u64>>,
 134    _maintain_connection: Option<Task<()>>,
 135    heartbeat_interval: Duration,
 136
 137    models_by_entity_type_and_remote_id: HashMap<(TypeId, u64), AnyWeakModelHandle>,
 138    models_by_message_type: HashMap<TypeId, AnyModelHandle>,
 139    model_types_by_message_type: HashMap<TypeId, TypeId>,
 140    message_handlers: HashMap<
 141        TypeId,
 142        Arc<
 143            dyn Send
 144                + Sync
 145                + Fn(
 146                    AnyModelHandle,
 147                    Box<dyn AnyTypedEnvelope>,
 148                    AsyncAppContext,
 149                ) -> LocalBoxFuture<'static, Result<()>>,
 150        >,
 151    >,
 152}
 153
 154#[derive(Clone, Debug)]
 155pub struct Credentials {
 156    pub user_id: u64,
 157    pub access_token: String,
 158}
 159
 160impl Default for ClientState {
 161    fn default() -> Self {
 162        Self {
 163            credentials: None,
 164            status: watch::channel_with(Status::SignedOut),
 165            entity_id_extractors: Default::default(),
 166            _maintain_connection: None,
 167            heartbeat_interval: Duration::from_secs(5),
 168            models_by_message_type: Default::default(),
 169            models_by_entity_type_and_remote_id: Default::default(),
 170            model_types_by_message_type: Default::default(),
 171            message_handlers: Default::default(),
 172        }
 173    }
 174}
 175
 176pub enum Subscription {
 177    Entity {
 178        client: Weak<Client>,
 179        id: (TypeId, u64),
 180    },
 181    Message {
 182        client: Weak<Client>,
 183        id: TypeId,
 184    },
 185}
 186
 187impl Drop for Subscription {
 188    fn drop(&mut self) {
 189        match self {
 190            Subscription::Entity { client, id } => {
 191                if let Some(client) = client.upgrade() {
 192                    let mut state = client.state.write();
 193                    let _ = state.models_by_entity_type_and_remote_id.remove(id);
 194                }
 195            }
 196            Subscription::Message { client, id } => {
 197                if let Some(client) = client.upgrade() {
 198                    let mut state = client.state.write();
 199                    let _ = state.model_types_by_message_type.remove(id);
 200                    let _ = state.message_handlers.remove(id);
 201                }
 202            }
 203        }
 204    }
 205}
 206
 207impl Client {
 208    pub fn new(http: Arc<dyn HttpClient>) -> Arc<Self> {
 209        lazy_static! {
 210            static ref NEXT_CLIENT_ID: AtomicUsize = AtomicUsize::default();
 211        }
 212
 213        Arc::new(Self {
 214            id: NEXT_CLIENT_ID.fetch_add(1, Ordering::SeqCst),
 215            peer: Peer::new(),
 216            http,
 217            state: Default::default(),
 218            authenticate: None,
 219            establish_connection: None,
 220        })
 221    }
 222
 223    #[cfg(any(test, feature = "test-support"))]
 224    pub fn override_authenticate<F>(&mut self, authenticate: F) -> &mut Self
 225    where
 226        F: 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>,
 227    {
 228        self.authenticate = Some(Box::new(authenticate));
 229        self
 230    }
 231
 232    #[cfg(any(test, feature = "test-support"))]
 233    pub fn override_establish_connection<F>(&mut self, connect: F) -> &mut Self
 234    where
 235        F: 'static
 236            + Send
 237            + Sync
 238            + Fn(&Credentials, &AsyncAppContext) -> Task<Result<Connection, EstablishConnectionError>>,
 239    {
 240        self.establish_connection = Some(Box::new(connect));
 241        self
 242    }
 243
 244    pub fn user_id(&self) -> Option<u64> {
 245        self.state
 246            .read()
 247            .credentials
 248            .as_ref()
 249            .map(|credentials| credentials.user_id)
 250    }
 251
 252    pub fn status(&self) -> watch::Receiver<Status> {
 253        self.state.read().status.1.clone()
 254    }
 255
 256    fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncAppContext) {
 257        let mut state = self.state.write();
 258        *state.status.0.borrow_mut() = status;
 259
 260        match status {
 261            Status::Connected { .. } => {
 262                let heartbeat_interval = state.heartbeat_interval;
 263                let this = self.clone();
 264                let foreground = cx.foreground();
 265                state._maintain_connection = Some(cx.foreground().spawn(async move {
 266                    loop {
 267                        foreground.timer(heartbeat_interval).await;
 268                        let _ = this.request(proto::Ping {}).await;
 269                    }
 270                }));
 271            }
 272            Status::ConnectionLost => {
 273                let this = self.clone();
 274                let foreground = cx.foreground();
 275                let heartbeat_interval = state.heartbeat_interval;
 276                state._maintain_connection = Some(cx.spawn(|cx| async move {
 277                    let mut rng = StdRng::from_entropy();
 278                    let mut delay = Duration::from_millis(100);
 279                    while let Err(error) = this.authenticate_and_connect(&cx).await {
 280                        log::error!("failed to connect {}", error);
 281                        this.set_status(
 282                            Status::ReconnectionError {
 283                                next_reconnection: Instant::now() + delay,
 284                            },
 285                            &cx,
 286                        );
 287                        foreground.timer(delay).await;
 288                        delay = delay
 289                            .mul_f32(rng.gen_range(1.0..=2.0))
 290                            .min(heartbeat_interval);
 291                    }
 292                }));
 293            }
 294            Status::SignedOut | Status::UpgradeRequired => {
 295                state._maintain_connection.take();
 296            }
 297            _ => {}
 298        }
 299    }
 300
 301    pub fn add_model_for_remote_entity<T: Entity>(
 302        self: &Arc<Self>,
 303        remote_id: u64,
 304        cx: &mut ModelContext<T>,
 305    ) -> Subscription {
 306        let handle = AnyModelHandle::from(cx.handle());
 307        let mut state = self.state.write();
 308        let id = (TypeId::of::<T>(), remote_id);
 309        state
 310            .models_by_entity_type_and_remote_id
 311            .insert(id, handle.downgrade());
 312        Subscription::Entity {
 313            client: Arc::downgrade(self),
 314            id,
 315        }
 316    }
 317
 318    pub fn add_message_handler<M, E, H, F>(
 319        self: &Arc<Self>,
 320        model: ModelHandle<E>,
 321        handler: H,
 322    ) -> Subscription
 323    where
 324        M: EnvelopedMessage,
 325        E: Entity,
 326        H: 'static
 327            + Send
 328            + Sync
 329            + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 330        F: 'static + Future<Output = Result<()>>,
 331    {
 332        let message_type_id = TypeId::of::<M>();
 333
 334        let client = self.clone();
 335        let mut state = self.state.write();
 336        state
 337            .models_by_message_type
 338            .insert(message_type_id, model.into());
 339
 340        let prev_handler = state.message_handlers.insert(
 341            message_type_id,
 342            Arc::new(move |handle, envelope, cx| {
 343                let model = handle.downcast::<E>().unwrap();
 344                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 345                handler(model, *envelope, client.clone(), cx).boxed_local()
 346            }),
 347        );
 348        if prev_handler.is_some() {
 349            panic!("registered handler for the same message twice");
 350        }
 351
 352        Subscription::Message {
 353            client: Arc::downgrade(self),
 354            id: message_type_id,
 355        }
 356    }
 357
 358    pub fn add_entity_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
 359    where
 360        M: EntityMessage,
 361        E: Entity,
 362        H: 'static
 363            + Send
 364            + Sync
 365            + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 366        F: 'static + Future<Output = Result<()>>,
 367    {
 368        let model_type_id = TypeId::of::<E>();
 369        let message_type_id = TypeId::of::<M>();
 370
 371        let client = self.clone();
 372        let mut state = self.state.write();
 373        state
 374            .model_types_by_message_type
 375            .insert(message_type_id, model_type_id);
 376        state
 377            .entity_id_extractors
 378            .entry(message_type_id)
 379            .or_insert_with(|| {
 380                Box::new(|envelope| {
 381                    let envelope = envelope
 382                        .as_any()
 383                        .downcast_ref::<TypedEnvelope<M>>()
 384                        .unwrap();
 385                    envelope.payload.remote_entity_id()
 386                })
 387            });
 388
 389        let prev_handler = state.message_handlers.insert(
 390            message_type_id,
 391            Arc::new(move |handle, envelope, cx| {
 392                let model = handle.downcast::<E>().unwrap();
 393                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 394                handler(model, *envelope, client.clone(), cx).boxed_local()
 395            }),
 396        );
 397        if prev_handler.is_some() {
 398            panic!("registered handler for the same message twice");
 399        }
 400    }
 401
 402    pub fn add_entity_request_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
 403    where
 404        M: EntityMessage + RequestMessage,
 405        E: Entity,
 406        H: 'static
 407            + Send
 408            + Sync
 409            + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 410        F: 'static + Future<Output = Result<M::Response>>,
 411    {
 412        self.add_entity_message_handler(move |model, envelope, client, cx| {
 413            let receipt = envelope.receipt();
 414            let response = handler(model, envelope, client.clone(), cx);
 415            async move {
 416                match response.await {
 417                    Ok(response) => {
 418                        client.respond(receipt, response)?;
 419                        Ok(())
 420                    }
 421                    Err(error) => {
 422                        client.respond_with_error(
 423                            receipt,
 424                            proto::Error {
 425                                message: error.to_string(),
 426                            },
 427                        )?;
 428                        Err(error)
 429                    }
 430                }
 431            }
 432        })
 433    }
 434
 435    pub fn has_keychain_credentials(&self, cx: &AsyncAppContext) -> bool {
 436        read_credentials_from_keychain(cx).is_some()
 437    }
 438
 439    #[async_recursion(?Send)]
 440    pub async fn authenticate_and_connect(
 441        self: &Arc<Self>,
 442        cx: &AsyncAppContext,
 443    ) -> anyhow::Result<()> {
 444        let was_disconnected = match *self.status().borrow() {
 445            Status::SignedOut => true,
 446            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 447                false
 448            }
 449            Status::Connected { .. }
 450            | Status::Connecting { .. }
 451            | Status::Reconnecting { .. }
 452            | Status::Authenticating
 453            | Status::Reauthenticating => return Ok(()),
 454            Status::UpgradeRequired => return Err(EstablishConnectionError::UpgradeRequired)?,
 455        };
 456
 457        if was_disconnected {
 458            self.set_status(Status::Authenticating, cx);
 459        } else {
 460            self.set_status(Status::Reauthenticating, cx)
 461        }
 462
 463        let mut used_keychain = false;
 464        let credentials = self.state.read().credentials.clone();
 465        let credentials = if let Some(credentials) = credentials {
 466            credentials
 467        } else if let Some(credentials) = read_credentials_from_keychain(cx) {
 468            used_keychain = true;
 469            credentials
 470        } else {
 471            let credentials = match self.authenticate(&cx).await {
 472                Ok(credentials) => credentials,
 473                Err(err) => {
 474                    self.set_status(Status::ConnectionError, cx);
 475                    return Err(err);
 476                }
 477            };
 478            credentials
 479        };
 480
 481        if was_disconnected {
 482            self.set_status(Status::Connecting, cx);
 483        } else {
 484            self.set_status(Status::Reconnecting, cx);
 485        }
 486
 487        match self.establish_connection(&credentials, cx).await {
 488            Ok(conn) => {
 489                self.state.write().credentials = Some(credentials.clone());
 490                if !used_keychain && IMPERSONATE_LOGIN.is_none() {
 491                    write_credentials_to_keychain(&credentials, cx).log_err();
 492                }
 493                self.set_connection(conn, cx).await;
 494                Ok(())
 495            }
 496            Err(EstablishConnectionError::Unauthorized) => {
 497                self.state.write().credentials.take();
 498                if used_keychain {
 499                    cx.platform().delete_credentials(&ZED_SERVER_URL).log_err();
 500                    self.set_status(Status::SignedOut, cx);
 501                    self.authenticate_and_connect(cx).await
 502                } else {
 503                    self.set_status(Status::ConnectionError, cx);
 504                    Err(EstablishConnectionError::Unauthorized)?
 505                }
 506            }
 507            Err(EstablishConnectionError::UpgradeRequired) => {
 508                self.set_status(Status::UpgradeRequired, cx);
 509                Err(EstablishConnectionError::UpgradeRequired)?
 510            }
 511            Err(error) => {
 512                self.set_status(Status::ConnectionError, cx);
 513                Err(error)?
 514            }
 515        }
 516    }
 517
 518    async fn set_connection(self: &Arc<Self>, conn: Connection, cx: &AsyncAppContext) {
 519        let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn).await;
 520        cx.foreground()
 521            .spawn({
 522                let cx = cx.clone();
 523                let this = self.clone();
 524                async move {
 525                    while let Some(message) = incoming.next().await {
 526                        let mut state = this.state.write();
 527                        let payload_type_id = message.payload_type_id();
 528                        let type_name = message.payload_type_name();
 529
 530                        let model = state
 531                            .models_by_message_type
 532                            .get(&payload_type_id)
 533                            .cloned()
 534                            .or_else(|| {
 535                                let model_type_id =
 536                                    *state.model_types_by_message_type.get(&payload_type_id)?;
 537                                let entity_id = state
 538                                    .entity_id_extractors
 539                                    .get(&message.payload_type_id())
 540                                    .map(|extract_entity_id| {
 541                                        (extract_entity_id)(message.as_ref())
 542                                    })?;
 543                                let model = state
 544                                    .models_by_entity_type_and_remote_id
 545                                    .get(&(model_type_id, entity_id))?;
 546                                if let Some(model) = model.upgrade(&cx) {
 547                                    Some(model)
 548                                } else {
 549                                    state
 550                                        .models_by_entity_type_and_remote_id
 551                                        .remove(&(model_type_id, entity_id));
 552                                    None
 553                                }
 554                            });
 555
 556                        let model = if let Some(model) = model {
 557                            model
 558                        } else {
 559                            log::info!("unhandled message {}", type_name);
 560                            continue;
 561                        };
 562
 563                        if let Some(handler) = state.message_handlers.get(&payload_type_id).cloned()
 564                        {
 565                            drop(state); // Avoid deadlocks if the handler interacts with rpc::Client
 566                            let future = handler(model, message, cx.clone());
 567
 568                            let client_id = this.id;
 569                            log::debug!(
 570                                "rpc message received. client_id:{}, name:{}",
 571                                client_id,
 572                                type_name
 573                            );
 574                            cx.foreground()
 575                                .spawn(async move {
 576                                    match future.await {
 577                                        Ok(()) => {
 578                                            log::debug!(
 579                                                "rpc message handled. client_id:{}, name:{}",
 580                                                client_id,
 581                                                type_name
 582                                            );
 583                                        }
 584                                        Err(error) => {
 585                                            log::error!(
 586                                                "error handling message. client_id:{}, name:{}, {}",
 587                                                client_id,
 588                                                type_name,
 589                                                error
 590                                            );
 591                                        }
 592                                    }
 593                                })
 594                                .detach();
 595                        } else {
 596                            log::info!("unhandled message {}", type_name);
 597                        }
 598                    }
 599                }
 600            })
 601            .detach();
 602
 603        self.set_status(Status::Connected { connection_id }, cx);
 604
 605        let handle_io = cx.background().spawn(handle_io);
 606        let this = self.clone();
 607        let cx = cx.clone();
 608        cx.foreground()
 609            .spawn(async move {
 610                match handle_io.await {
 611                    Ok(()) => this.set_status(Status::SignedOut, &cx),
 612                    Err(err) => {
 613                        log::error!("connection error: {:?}", err);
 614                        this.set_status(Status::ConnectionLost, &cx);
 615                    }
 616                }
 617            })
 618            .detach();
 619    }
 620
 621    fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
 622        if let Some(callback) = self.authenticate.as_ref() {
 623            callback(cx)
 624        } else {
 625            self.authenticate_with_browser(cx)
 626        }
 627    }
 628
 629    fn establish_connection(
 630        self: &Arc<Self>,
 631        credentials: &Credentials,
 632        cx: &AsyncAppContext,
 633    ) -> Task<Result<Connection, EstablishConnectionError>> {
 634        if let Some(callback) = self.establish_connection.as_ref() {
 635            callback(credentials, cx)
 636        } else {
 637            self.establish_websocket_connection(credentials, cx)
 638        }
 639    }
 640
 641    fn establish_websocket_connection(
 642        self: &Arc<Self>,
 643        credentials: &Credentials,
 644        cx: &AsyncAppContext,
 645    ) -> Task<Result<Connection, EstablishConnectionError>> {
 646        let request = Request::builder()
 647            .header(
 648                "Authorization",
 649                format!("{} {}", credentials.user_id, credentials.access_token),
 650            )
 651            .header("X-Zed-Protocol-Version", rpc::PROTOCOL_VERSION);
 652
 653        let http = self.http.clone();
 654        cx.background().spawn(async move {
 655            let mut rpc_url = format!("{}/rpc", *ZED_SERVER_URL);
 656            let rpc_request = surf::Request::new(
 657                Method::Get,
 658                surf::Url::parse(&rpc_url).context("invalid ZED_SERVER_URL")?,
 659            );
 660            let rpc_response = http.send(rpc_request).await?;
 661
 662            if rpc_response.status().is_redirection() {
 663                rpc_url = rpc_response
 664                    .header("Location")
 665                    .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
 666                    .as_str()
 667                    .to_string();
 668            }
 669            // Until we switch the zed.dev domain to point to the new Next.js app, there
 670            // will be no redirect required, and the app will connect directly to
 671            // wss://zed.dev/rpc.
 672            else if rpc_response.status() != surf::StatusCode::UpgradeRequired {
 673                Err(anyhow!(
 674                    "unexpected /rpc response status {}",
 675                    rpc_response.status()
 676                ))?
 677            }
 678
 679            let mut rpc_url = surf::Url::parse(&rpc_url).context("invalid rpc url")?;
 680            let rpc_host = rpc_url
 681                .host_str()
 682                .zip(rpc_url.port_or_known_default())
 683                .ok_or_else(|| anyhow!("missing host in rpc url"))?;
 684            let stream = smol::net::TcpStream::connect(rpc_host).await?;
 685
 686            log::info!("connected to rpc endpoint {}", rpc_url);
 687
 688            match rpc_url.scheme() {
 689                "https" => {
 690                    rpc_url.set_scheme("wss").unwrap();
 691                    let request = request.uri(rpc_url.as_str()).body(())?;
 692                    let (stream, _) =
 693                        async_tungstenite::async_tls::client_async_tls(request, stream).await?;
 694                    Ok(Connection::new(stream))
 695                }
 696                "http" => {
 697                    rpc_url.set_scheme("ws").unwrap();
 698                    let request = request.uri(rpc_url.as_str()).body(())?;
 699                    let (stream, _) = async_tungstenite::client_async(request, stream).await?;
 700                    Ok(Connection::new(stream))
 701                }
 702                _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
 703            }
 704        })
 705    }
 706
 707    pub fn authenticate_with_browser(
 708        self: &Arc<Self>,
 709        cx: &AsyncAppContext,
 710    ) -> Task<Result<Credentials>> {
 711        let platform = cx.platform();
 712        let executor = cx.background();
 713        executor.clone().spawn(async move {
 714            // Generate a pair of asymmetric encryption keys. The public key will be used by the
 715            // zed server to encrypt the user's access token, so that it can'be intercepted by
 716            // any other app running on the user's device.
 717            let (public_key, private_key) =
 718                rpc::auth::keypair().expect("failed to generate keypair for auth");
 719            let public_key_string =
 720                String::try_from(public_key).expect("failed to serialize public key for auth");
 721
 722            // Start an HTTP server to receive the redirect from Zed's sign-in page.
 723            let server = tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
 724            let port = server.server_addr().port();
 725
 726            // Open the Zed sign-in page in the user's browser, with query parameters that indicate
 727            // that the user is signing in from a Zed app running on the same device.
 728            let mut url = format!(
 729                "{}/native_app_signin?native_app_port={}&native_app_public_key={}",
 730                *ZED_SERVER_URL, port, public_key_string
 731            );
 732
 733            if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
 734                log::info!("impersonating user @{}", impersonate_login);
 735                write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
 736            }
 737
 738            platform.open_url(&url);
 739
 740            // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
 741            // access token from the query params.
 742            //
 743            // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
 744            // custom URL scheme instead of this local HTTP server.
 745            let (user_id, access_token) = executor
 746                .spawn(async move {
 747                    if let Some(req) = server.recv_timeout(Duration::from_secs(10 * 60))? {
 748                        let path = req.url();
 749                        let mut user_id = None;
 750                        let mut access_token = None;
 751                        let url = Url::parse(&format!("http://example.com{}", path))
 752                            .context("failed to parse login notification url")?;
 753                        for (key, value) in url.query_pairs() {
 754                            if key == "access_token" {
 755                                access_token = Some(value.to_string());
 756                            } else if key == "user_id" {
 757                                user_id = Some(value.to_string());
 758                            }
 759                        }
 760
 761                        let post_auth_url =
 762                            format!("{}/native_app_signin_succeeded", *ZED_SERVER_URL);
 763                        req.respond(
 764                            tiny_http::Response::empty(302).with_header(
 765                                tiny_http::Header::from_bytes(
 766                                    &b"Location"[..],
 767                                    post_auth_url.as_bytes(),
 768                                )
 769                                .unwrap(),
 770                            ),
 771                        )
 772                        .context("failed to respond to login http request")?;
 773                        Ok((
 774                            user_id.ok_or_else(|| anyhow!("missing user_id parameter"))?,
 775                            access_token
 776                                .ok_or_else(|| anyhow!("missing access_token parameter"))?,
 777                        ))
 778                    } else {
 779                        Err(anyhow!("didn't receive login redirect"))
 780                    }
 781                })
 782                .await?;
 783
 784            let access_token = private_key
 785                .decrypt_string(&access_token)
 786                .context("failed to decrypt access token")?;
 787            platform.activate(true);
 788
 789            Ok(Credentials {
 790                user_id: user_id.parse()?,
 791                access_token,
 792            })
 793        })
 794    }
 795
 796    pub fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) -> Result<()> {
 797        let conn_id = self.connection_id()?;
 798        self.peer.disconnect(conn_id);
 799        self.set_status(Status::SignedOut, cx);
 800        Ok(())
 801    }
 802
 803    fn connection_id(&self) -> Result<ConnectionId> {
 804        if let Status::Connected { connection_id, .. } = *self.status().borrow() {
 805            Ok(connection_id)
 806        } else {
 807            Err(anyhow!("not connected"))
 808        }
 809    }
 810
 811    pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
 812        log::debug!("rpc send. client_id:{}, name:{}", self.id, T::NAME);
 813        self.peer.send(self.connection_id()?, message)
 814    }
 815
 816    pub async fn request<T: RequestMessage>(&self, request: T) -> Result<T::Response> {
 817        log::debug!(
 818            "rpc request start. client_id: {}. name:{}",
 819            self.id,
 820            T::NAME
 821        );
 822        let response = self.peer.request(self.connection_id()?, request).await;
 823        log::debug!(
 824            "rpc request finish. client_id: {}. name:{}",
 825            self.id,
 826            T::NAME
 827        );
 828        response
 829    }
 830
 831    fn respond<T: RequestMessage>(&self, receipt: Receipt<T>, response: T::Response) -> Result<()> {
 832        log::debug!("rpc respond. client_id: {}. name:{}", self.id, T::NAME);
 833        self.peer.respond(receipt, response)
 834    }
 835
 836    fn respond_with_error<T: RequestMessage>(
 837        &self,
 838        receipt: Receipt<T>,
 839        error: proto::Error,
 840    ) -> Result<()> {
 841        log::debug!("rpc respond. client_id: {}. name:{}", self.id, T::NAME);
 842        self.peer.respond_with_error(receipt, error)
 843    }
 844}
 845
 846fn read_credentials_from_keychain(cx: &AsyncAppContext) -> Option<Credentials> {
 847    if IMPERSONATE_LOGIN.is_some() {
 848        return None;
 849    }
 850
 851    let (user_id, access_token) = cx
 852        .platform()
 853        .read_credentials(&ZED_SERVER_URL)
 854        .log_err()
 855        .flatten()?;
 856    Some(Credentials {
 857        user_id: user_id.parse().ok()?,
 858        access_token: String::from_utf8(access_token).ok()?,
 859    })
 860}
 861
 862fn write_credentials_to_keychain(credentials: &Credentials, cx: &AsyncAppContext) -> Result<()> {
 863    cx.platform().write_credentials(
 864        &ZED_SERVER_URL,
 865        &credentials.user_id.to_string(),
 866        credentials.access_token.as_bytes(),
 867    )
 868}
 869
 870const WORKTREE_URL_PREFIX: &'static str = "zed://worktrees/";
 871
 872pub fn encode_worktree_url(id: u64, access_token: &str) -> String {
 873    format!("{}{}/{}", WORKTREE_URL_PREFIX, id, access_token)
 874}
 875
 876pub fn decode_worktree_url(url: &str) -> Option<(u64, String)> {
 877    let path = url.trim().strip_prefix(WORKTREE_URL_PREFIX)?;
 878    let mut parts = path.split('/');
 879    let id = parts.next()?.parse::<u64>().ok()?;
 880    let access_token = parts.next()?;
 881    if access_token.is_empty() {
 882        return None;
 883    }
 884    Some((id, access_token.to_string()))
 885}
 886
 887#[cfg(test)]
 888mod tests {
 889    use super::*;
 890    use crate::test::{FakeHttpClient, FakeServer};
 891    use gpui::TestAppContext;
 892
 893    #[gpui::test(iterations = 10)]
 894    async fn test_heartbeat(cx: TestAppContext) {
 895        cx.foreground().forbid_parking();
 896
 897        let user_id = 5;
 898        let mut client = Client::new(FakeHttpClient::with_404_response());
 899        let server = FakeServer::for_client(user_id, &mut client, &cx).await;
 900
 901        cx.foreground().advance_clock(Duration::from_secs(10));
 902        let ping = server.receive::<proto::Ping>().await.unwrap();
 903        server.respond(ping.receipt(), proto::Ack {}).await;
 904
 905        cx.foreground().advance_clock(Duration::from_secs(10));
 906        let ping = server.receive::<proto::Ping>().await.unwrap();
 907        server.respond(ping.receipt(), proto::Ack {}).await;
 908
 909        client.disconnect(&cx.to_async()).unwrap();
 910        assert!(server.receive::<proto::Ping>().await.is_err());
 911    }
 912
 913    #[gpui::test(iterations = 10)]
 914    async fn test_reconnection(cx: TestAppContext) {
 915        cx.foreground().forbid_parking();
 916
 917        let user_id = 5;
 918        let mut client = Client::new(FakeHttpClient::with_404_response());
 919        let server = FakeServer::for_client(user_id, &mut client, &cx).await;
 920        let mut status = client.status();
 921        assert!(matches!(
 922            status.next().await,
 923            Some(Status::Connected { .. })
 924        ));
 925        assert_eq!(server.auth_count(), 1);
 926
 927        server.forbid_connections();
 928        server.disconnect();
 929        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
 930
 931        server.allow_connections();
 932        cx.foreground().advance_clock(Duration::from_secs(10));
 933        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
 934        assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
 935
 936        server.forbid_connections();
 937        server.disconnect();
 938        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
 939
 940        // Clear cached credentials after authentication fails
 941        server.roll_access_token();
 942        server.allow_connections();
 943        cx.foreground().advance_clock(Duration::from_secs(10));
 944        assert_eq!(server.auth_count(), 1);
 945        cx.foreground().advance_clock(Duration::from_secs(10));
 946        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
 947        assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
 948    }
 949
 950    #[test]
 951    fn test_encode_and_decode_worktree_url() {
 952        let url = encode_worktree_url(5, "deadbeef");
 953        assert_eq!(decode_worktree_url(&url), Some((5, "deadbeef".to_string())));
 954        assert_eq!(
 955            decode_worktree_url(&format!("\n {}\t", url)),
 956            Some((5, "deadbeef".to_string()))
 957        );
 958        assert_eq!(decode_worktree_url("not://the-right-format"), None);
 959    }
 960
 961    #[gpui::test]
 962    async fn test_subscribing_to_entity(mut cx: TestAppContext) {
 963        cx.foreground().forbid_parking();
 964
 965        let user_id = 5;
 966        let mut client = Client::new(FakeHttpClient::with_404_response());
 967        let server = FakeServer::for_client(user_id, &mut client, &cx).await;
 968
 969        let (done_tx1, mut done_rx1) = smol::channel::unbounded();
 970        let (done_tx2, mut done_rx2) = smol::channel::unbounded();
 971        client.add_entity_message_handler(
 972            move |model: ModelHandle<Model>, _: TypedEnvelope<proto::UnshareProject>, _, cx| {
 973                match model.read_with(&cx, |model, _| model.id) {
 974                    1 => done_tx1.try_send(()).unwrap(),
 975                    2 => done_tx2.try_send(()).unwrap(),
 976                    _ => unreachable!(),
 977                }
 978                async { Ok(()) }
 979            },
 980        );
 981        let model1 = cx.add_model(|_| Model {
 982            id: 1,
 983            subscription: None,
 984        });
 985        let model2 = cx.add_model(|_| Model {
 986            id: 2,
 987            subscription: None,
 988        });
 989        let model3 = cx.add_model(|_| Model {
 990            id: 3,
 991            subscription: None,
 992        });
 993
 994        let _subscription1 =
 995            model1.update(&mut cx, |_, cx| client.add_model_for_remote_entity(1, cx));
 996        let _subscription2 =
 997            model2.update(&mut cx, |_, cx| client.add_model_for_remote_entity(2, cx));
 998        // Ensure dropping a subscription for the same entity type still allows receiving of
 999        // messages for other entity IDs of the same type.
1000        let subscription3 =
1001            model3.update(&mut cx, |_, cx| client.add_model_for_remote_entity(3, cx));
1002        drop(subscription3);
1003
1004        server.send(proto::UnshareProject { project_id: 1 });
1005        server.send(proto::UnshareProject { project_id: 2 });
1006        done_rx1.next().await.unwrap();
1007        done_rx2.next().await.unwrap();
1008    }
1009
1010    #[gpui::test]
1011    async fn test_subscribing_after_dropping_subscription(mut cx: TestAppContext) {
1012        cx.foreground().forbid_parking();
1013
1014        let user_id = 5;
1015        let mut client = Client::new(FakeHttpClient::with_404_response());
1016        let server = FakeServer::for_client(user_id, &mut client, &cx).await;
1017
1018        let model = cx.add_model(|_| Model::default());
1019        let (done_tx1, _done_rx1) = smol::channel::unbounded();
1020        let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1021        let subscription1 = client.add_message_handler(
1022            model.clone(),
1023            move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1024                done_tx1.try_send(()).unwrap();
1025                async { Ok(()) }
1026            },
1027        );
1028        drop(subscription1);
1029        let _subscription2 =
1030            client.add_message_handler(model, move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1031                done_tx2.try_send(()).unwrap();
1032                async { Ok(()) }
1033            });
1034        server.send(proto::Ping {});
1035        done_rx2.next().await.unwrap();
1036    }
1037
1038    #[gpui::test]
1039    async fn test_dropping_subscription_in_handler(mut cx: TestAppContext) {
1040        cx.foreground().forbid_parking();
1041
1042        let user_id = 5;
1043        let mut client = Client::new(FakeHttpClient::with_404_response());
1044        let server = FakeServer::for_client(user_id, &mut client, &cx).await;
1045
1046        let model = cx.add_model(|_| Model::default());
1047        let (done_tx, mut done_rx) = smol::channel::unbounded();
1048        let subscription = client.add_message_handler(
1049            model.clone(),
1050            move |model, _: TypedEnvelope<proto::Ping>, _, mut cx| {
1051                model.update(&mut cx, |model, _| model.subscription.take());
1052                done_tx.try_send(()).unwrap();
1053                async { Ok(()) }
1054            },
1055        );
1056        model.update(&mut cx, |model, _| {
1057            model.subscription = Some(subscription);
1058        });
1059        server.send(proto::Ping {});
1060        done_rx.next().await.unwrap();
1061    }
1062
1063    #[derive(Default)]
1064    struct Model {
1065        id: usize,
1066        subscription: Option<Subscription>,
1067    }
1068
1069    impl Entity for Model {
1070        type Event = ();
1071    }
1072}