client.rs

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