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