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