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