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