client.rs

   1#[cfg(any(test, feature = "test-support"))]
   2pub mod test;
   3
   4mod socks;
   5pub mod telemetry;
   6pub mod user;
   7pub mod zed_urls;
   8
   9use anyhow::{anyhow, bail, Context as _, Result};
  10use async_recursion::async_recursion;
  11use async_tungstenite::tungstenite::{
  12    client::IntoClientRequest,
  13    error::Error as WebsocketError,
  14    http::{HeaderValue, Request, StatusCode},
  15};
  16use chrono::{DateTime, Utc};
  17use clock::SystemClock;
  18use futures::{
  19    channel::oneshot, future::BoxFuture, AsyncReadExt, FutureExt, SinkExt, Stream, StreamExt,
  20    TryFutureExt as _, TryStreamExt,
  21};
  22use gpui::{actions, App, AsyncApp, Entity, Global, Task, WeakEntity};
  23use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
  24use parking_lot::RwLock;
  25use postage::watch;
  26use rand::prelude::*;
  27use release_channel::{AppVersion, ReleaseChannel};
  28use rpc::proto::{AnyTypedEnvelope, EnvelopedMessage, PeerId, RequestMessage};
  29use schemars::JsonSchema;
  30use serde::{Deserialize, Serialize};
  31use settings::{Settings, SettingsSources};
  32use socks::connect_socks_proxy_stream;
  33use std::pin::Pin;
  34use std::{
  35    any::TypeId,
  36    convert::TryFrom,
  37    fmt::Write as _,
  38    future::Future,
  39    marker::PhantomData,
  40    path::PathBuf,
  41    sync::{
  42        atomic::{AtomicU64, Ordering},
  43        Arc, LazyLock, Weak,
  44    },
  45    time::{Duration, Instant},
  46};
  47use telemetry::Telemetry;
  48use thiserror::Error;
  49use url::Url;
  50use util::{ResultExt, TryFutureExt};
  51
  52pub use rpc::*;
  53pub use telemetry_events::Event;
  54pub use user::*;
  55
  56static ZED_SERVER_URL: LazyLock<Option<String>> =
  57    LazyLock::new(|| std::env::var("ZED_SERVER_URL").ok());
  58static ZED_RPC_URL: LazyLock<Option<String>> = LazyLock::new(|| std::env::var("ZED_RPC_URL").ok());
  59
  60/// An environment variable whose presence indicates that the development auth
  61/// provider should be used.
  62///
  63/// Only works in development. Setting this environment variable in other release
  64/// channels is a no-op.
  65pub static ZED_DEVELOPMENT_AUTH: LazyLock<bool> = LazyLock::new(|| {
  66    std::env::var("ZED_DEVELOPMENT_AUTH").map_or(false, |value| !value.is_empty())
  67});
  68pub static IMPERSONATE_LOGIN: LazyLock<Option<String>> = LazyLock::new(|| {
  69    std::env::var("ZED_IMPERSONATE")
  70        .ok()
  71        .and_then(|s| if s.is_empty() { None } else { Some(s) })
  72});
  73
  74pub static ADMIN_API_TOKEN: LazyLock<Option<String>> = LazyLock::new(|| {
  75    std::env::var("ZED_ADMIN_API_TOKEN")
  76        .ok()
  77        .and_then(|s| if s.is_empty() { None } else { Some(s) })
  78});
  79
  80pub static ZED_APP_PATH: LazyLock<Option<PathBuf>> =
  81    LazyLock::new(|| std::env::var("ZED_APP_PATH").ok().map(PathBuf::from));
  82
  83pub static ZED_ALWAYS_ACTIVE: LazyLock<bool> =
  84    LazyLock::new(|| std::env::var("ZED_ALWAYS_ACTIVE").map_or(false, |e| !e.is_empty()));
  85
  86pub const INITIAL_RECONNECTION_DELAY: Duration = Duration::from_millis(500);
  87pub const MAX_RECONNECTION_DELAY: Duration = Duration::from_secs(10);
  88pub const CONNECTION_TIMEOUT: Duration = Duration::from_secs(20);
  89
  90actions!(client, [SignIn, SignOut, Reconnect]);
  91
  92#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  93pub struct ClientSettingsContent {
  94    server_url: Option<String>,
  95}
  96
  97#[derive(Deserialize)]
  98pub struct ClientSettings {
  99    pub server_url: String,
 100}
 101
 102impl Settings for ClientSettings {
 103    const KEY: Option<&'static str> = None;
 104
 105    type FileContent = ClientSettingsContent;
 106
 107    fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
 108        let mut result = sources.json_merge::<Self>()?;
 109        if let Some(server_url) = &*ZED_SERVER_URL {
 110            result.server_url.clone_from(server_url)
 111        }
 112        Ok(result)
 113    }
 114}
 115
 116#[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
 117pub struct ProxySettingsContent {
 118    proxy: Option<String>,
 119}
 120
 121#[derive(Deserialize, Default)]
 122pub struct ProxySettings {
 123    pub proxy: Option<String>,
 124}
 125
 126impl Settings for ProxySettings {
 127    const KEY: Option<&'static str> = None;
 128
 129    type FileContent = ProxySettingsContent;
 130
 131    fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
 132        Ok(Self {
 133            proxy: sources
 134                .user
 135                .or(sources.server)
 136                .and_then(|value| value.proxy.clone())
 137                .or(sources.default.proxy.clone()),
 138        })
 139    }
 140}
 141
 142pub fn init_settings(cx: &mut App) {
 143    TelemetrySettings::register(cx);
 144    ClientSettings::register(cx);
 145    ProxySettings::register(cx);
 146}
 147
 148pub fn init(client: &Arc<Client>, cx: &mut App) {
 149    let client = Arc::downgrade(client);
 150    cx.on_action({
 151        let client = client.clone();
 152        move |_: &SignIn, cx| {
 153            if let Some(client) = client.upgrade() {
 154                cx.spawn(
 155                    |cx| async move { client.authenticate_and_connect(true, &cx).log_err().await },
 156                )
 157                .detach();
 158            }
 159        }
 160    });
 161
 162    cx.on_action({
 163        let client = client.clone();
 164        move |_: &SignOut, cx| {
 165            if let Some(client) = client.upgrade() {
 166                cx.spawn(|cx| async move {
 167                    client.sign_out(&cx).await;
 168                })
 169                .detach();
 170            }
 171        }
 172    });
 173
 174    cx.on_action({
 175        let client = client.clone();
 176        move |_: &Reconnect, cx| {
 177            if let Some(client) = client.upgrade() {
 178                cx.spawn(|cx| async move {
 179                    client.reconnect(&cx);
 180                })
 181                .detach();
 182            }
 183        }
 184    });
 185}
 186
 187struct GlobalClient(Arc<Client>);
 188
 189impl Global for GlobalClient {}
 190
 191pub struct Client {
 192    id: AtomicU64,
 193    peer: Arc<Peer>,
 194    http: Arc<HttpClientWithUrl>,
 195    telemetry: Arc<Telemetry>,
 196    credentials_provider: Arc<dyn CredentialsProvider + Send + Sync + 'static>,
 197    state: RwLock<ClientState>,
 198    handler_set: parking_lot::Mutex<ProtoMessageHandlerSet>,
 199
 200    #[allow(clippy::type_complexity)]
 201    #[cfg(any(test, feature = "test-support"))]
 202    authenticate:
 203        RwLock<Option<Box<dyn 'static + Send + Sync + Fn(&AsyncApp) -> Task<Result<Credentials>>>>>,
 204
 205    #[allow(clippy::type_complexity)]
 206    #[cfg(any(test, feature = "test-support"))]
 207    establish_connection: RwLock<
 208        Option<
 209            Box<
 210                dyn 'static
 211                    + Send
 212                    + Sync
 213                    + Fn(
 214                        &Credentials,
 215                        &AsyncApp,
 216                    ) -> Task<Result<Connection, EstablishConnectionError>>,
 217            >,
 218        >,
 219    >,
 220
 221    #[cfg(any(test, feature = "test-support"))]
 222    rpc_url: RwLock<Option<Url>>,
 223}
 224
 225#[derive(Error, Debug)]
 226pub enum EstablishConnectionError {
 227    #[error("upgrade required")]
 228    UpgradeRequired,
 229    #[error("unauthorized")]
 230    Unauthorized,
 231    #[error("{0}")]
 232    Other(#[from] anyhow::Error),
 233    #[error("{0}")]
 234    InvalidHeaderValue(#[from] async_tungstenite::tungstenite::http::header::InvalidHeaderValue),
 235    #[error("{0}")]
 236    Io(#[from] std::io::Error),
 237    #[error("{0}")]
 238    Websocket(#[from] async_tungstenite::tungstenite::http::Error),
 239}
 240
 241impl From<WebsocketError> for EstablishConnectionError {
 242    fn from(error: WebsocketError) -> Self {
 243        if let WebsocketError::Http(response) = &error {
 244            match response.status() {
 245                StatusCode::UNAUTHORIZED => return EstablishConnectionError::Unauthorized,
 246                StatusCode::UPGRADE_REQUIRED => return EstablishConnectionError::UpgradeRequired,
 247                _ => {}
 248            }
 249        }
 250        EstablishConnectionError::Other(error.into())
 251    }
 252}
 253
 254impl EstablishConnectionError {
 255    pub fn other(error: impl Into<anyhow::Error> + Send + Sync) -> Self {
 256        Self::Other(error.into())
 257    }
 258}
 259
 260#[derive(Copy, Clone, Debug, PartialEq)]
 261pub enum Status {
 262    SignedOut,
 263    UpgradeRequired,
 264    Authenticating,
 265    Connecting,
 266    ConnectionError,
 267    Connected {
 268        peer_id: PeerId,
 269        connection_id: ConnectionId,
 270    },
 271    ConnectionLost,
 272    Reauthenticating,
 273    Reconnecting,
 274    ReconnectionError {
 275        next_reconnection: Instant,
 276    },
 277}
 278
 279impl Status {
 280    pub fn is_connected(&self) -> bool {
 281        matches!(self, Self::Connected { .. })
 282    }
 283
 284    pub fn is_signed_out(&self) -> bool {
 285        matches!(self, Self::SignedOut | Self::UpgradeRequired)
 286    }
 287}
 288
 289struct ClientState {
 290    credentials: Option<Credentials>,
 291    status: (watch::Sender<Status>, watch::Receiver<Status>),
 292    _reconnect_task: Option<Task<()>>,
 293}
 294
 295#[derive(Clone, Debug, Eq, PartialEq)]
 296pub struct Credentials {
 297    pub user_id: u64,
 298    pub access_token: String,
 299}
 300
 301impl Credentials {
 302    pub fn authorization_header(&self) -> String {
 303        format!("{} {}", self.user_id, self.access_token)
 304    }
 305}
 306
 307/// A provider for [`Credentials`].
 308///
 309/// Used to abstract over reading and writing credentials to some form of
 310/// persistence (like the system keychain).
 311trait CredentialsProvider {
 312    /// Reads the credentials from the provider.
 313    fn read_credentials<'a>(
 314        &'a self,
 315        cx: &'a AsyncApp,
 316    ) -> Pin<Box<dyn Future<Output = Option<Credentials>> + 'a>>;
 317
 318    /// Writes the credentials to the provider.
 319    fn write_credentials<'a>(
 320        &'a self,
 321        user_id: u64,
 322        access_token: String,
 323        cx: &'a AsyncApp,
 324    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>>;
 325
 326    /// Deletes the credentials from the provider.
 327    fn delete_credentials<'a>(
 328        &'a self,
 329        cx: &'a AsyncApp,
 330    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>>;
 331}
 332
 333impl Default for ClientState {
 334    fn default() -> Self {
 335        Self {
 336            credentials: None,
 337            status: watch::channel_with(Status::SignedOut),
 338            _reconnect_task: None,
 339        }
 340    }
 341}
 342
 343pub enum Subscription {
 344    Entity {
 345        client: Weak<Client>,
 346        id: (TypeId, u64),
 347    },
 348    Message {
 349        client: Weak<Client>,
 350        id: TypeId,
 351    },
 352}
 353
 354impl Drop for Subscription {
 355    fn drop(&mut self) {
 356        match self {
 357            Subscription::Entity { client, id } => {
 358                if let Some(client) = client.upgrade() {
 359                    let mut state = client.handler_set.lock();
 360                    let _ = state.entities_by_type_and_remote_id.remove(id);
 361                }
 362            }
 363            Subscription::Message { client, id } => {
 364                if let Some(client) = client.upgrade() {
 365                    let mut state = client.handler_set.lock();
 366                    let _ = state.entity_types_by_message_type.remove(id);
 367                    let _ = state.message_handlers.remove(id);
 368                }
 369            }
 370        }
 371    }
 372}
 373
 374pub struct PendingEntitySubscription<T: 'static> {
 375    client: Arc<Client>,
 376    remote_id: u64,
 377    _entity_type: PhantomData<T>,
 378    consumed: bool,
 379}
 380
 381impl<T: 'static> PendingEntitySubscription<T> {
 382    pub fn set_entity(mut self, entity: &Entity<T>, cx: &AsyncApp) -> Subscription {
 383        self.consumed = true;
 384        let mut handlers = self.client.handler_set.lock();
 385        let id = (TypeId::of::<T>(), self.remote_id);
 386        let Some(EntityMessageSubscriber::Pending(messages)) =
 387            handlers.entities_by_type_and_remote_id.remove(&id)
 388        else {
 389            unreachable!()
 390        };
 391
 392        handlers.entities_by_type_and_remote_id.insert(
 393            id,
 394            EntityMessageSubscriber::Entity {
 395                handle: entity.downgrade().into(),
 396            },
 397        );
 398        drop(handlers);
 399        for message in messages {
 400            let client_id = self.client.id();
 401            let type_name = message.payload_type_name();
 402            let sender_id = message.original_sender_id();
 403            log::debug!(
 404                "handling queued rpc message. client_id:{}, sender_id:{:?}, type:{}",
 405                client_id,
 406                sender_id,
 407                type_name
 408            );
 409            self.client.handle_message(message, cx);
 410        }
 411        Subscription::Entity {
 412            client: Arc::downgrade(&self.client),
 413            id,
 414        }
 415    }
 416}
 417
 418impl<T: 'static> Drop for PendingEntitySubscription<T> {
 419    fn drop(&mut self) {
 420        if !self.consumed {
 421            let mut state = self.client.handler_set.lock();
 422            if let Some(EntityMessageSubscriber::Pending(messages)) = state
 423                .entities_by_type_and_remote_id
 424                .remove(&(TypeId::of::<T>(), self.remote_id))
 425            {
 426                for message in messages {
 427                    log::info!("unhandled message {}", message.payload_type_name());
 428                }
 429            }
 430        }
 431    }
 432}
 433
 434#[derive(Copy, Clone)]
 435pub struct TelemetrySettings {
 436    pub diagnostics: bool,
 437    pub metrics: bool,
 438}
 439
 440/// Control what info is collected by Zed.
 441#[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
 442pub struct TelemetrySettingsContent {
 443    /// Send debug info like crash reports.
 444    ///
 445    /// Default: true
 446    pub diagnostics: Option<bool>,
 447    /// Send anonymized usage data like what languages you're using Zed with.
 448    ///
 449    /// Default: true
 450    pub metrics: Option<bool>,
 451}
 452
 453impl settings::Settings for TelemetrySettings {
 454    const KEY: Option<&'static str> = Some("telemetry");
 455
 456    type FileContent = TelemetrySettingsContent;
 457
 458    fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
 459        Ok(Self {
 460            diagnostics: sources
 461                .user
 462                .as_ref()
 463                .or(sources.server.as_ref())
 464                .and_then(|v| v.diagnostics)
 465                .unwrap_or(
 466                    sources
 467                        .default
 468                        .diagnostics
 469                        .ok_or_else(Self::missing_default)?,
 470                ),
 471            metrics: sources
 472                .user
 473                .as_ref()
 474                .or(sources.server.as_ref())
 475                .and_then(|v| v.metrics)
 476                .unwrap_or(sources.default.metrics.ok_or_else(Self::missing_default)?),
 477        })
 478    }
 479}
 480
 481impl Client {
 482    pub fn new(
 483        clock: Arc<dyn SystemClock>,
 484        http: Arc<HttpClientWithUrl>,
 485        cx: &mut App,
 486    ) -> Arc<Self> {
 487        let use_zed_development_auth = match ReleaseChannel::try_global(cx) {
 488            Some(ReleaseChannel::Dev) => *ZED_DEVELOPMENT_AUTH,
 489            Some(ReleaseChannel::Nightly | ReleaseChannel::Preview | ReleaseChannel::Stable)
 490            | None => false,
 491        };
 492
 493        let credentials_provider: Arc<dyn CredentialsProvider + Send + Sync + 'static> =
 494            if use_zed_development_auth {
 495                Arc::new(DevelopmentCredentialsProvider {
 496                    path: paths::config_dir().join("development_auth"),
 497                })
 498            } else {
 499                Arc::new(KeychainCredentialsProvider)
 500            };
 501
 502        Arc::new(Self {
 503            id: AtomicU64::new(0),
 504            peer: Peer::new(0),
 505            telemetry: Telemetry::new(clock, http.clone(), cx),
 506            http,
 507            credentials_provider,
 508            state: Default::default(),
 509            handler_set: Default::default(),
 510
 511            #[cfg(any(test, feature = "test-support"))]
 512            authenticate: Default::default(),
 513            #[cfg(any(test, feature = "test-support"))]
 514            establish_connection: Default::default(),
 515            #[cfg(any(test, feature = "test-support"))]
 516            rpc_url: RwLock::default(),
 517        })
 518    }
 519
 520    pub fn production(cx: &mut App) -> Arc<Self> {
 521        let clock = Arc::new(clock::RealSystemClock);
 522        let http = Arc::new(HttpClientWithUrl::new_uri(
 523            cx.http_client(),
 524            &ClientSettings::get_global(cx).server_url,
 525            cx.http_client().proxy().cloned(),
 526        ));
 527        Self::new(clock, http, cx)
 528    }
 529
 530    pub fn id(&self) -> u64 {
 531        self.id.load(Ordering::SeqCst)
 532    }
 533
 534    pub fn http_client(&self) -> Arc<HttpClientWithUrl> {
 535        self.http.clone()
 536    }
 537
 538    pub fn set_id(&self, id: u64) -> &Self {
 539        self.id.store(id, Ordering::SeqCst);
 540        self
 541    }
 542
 543    #[cfg(any(test, feature = "test-support"))]
 544    pub fn teardown(&self) {
 545        let mut state = self.state.write();
 546        state._reconnect_task.take();
 547        self.handler_set.lock().clear();
 548        self.peer.teardown();
 549    }
 550
 551    #[cfg(any(test, feature = "test-support"))]
 552    pub fn override_authenticate<F>(&self, authenticate: F) -> &Self
 553    where
 554        F: 'static + Send + Sync + Fn(&AsyncApp) -> Task<Result<Credentials>>,
 555    {
 556        *self.authenticate.write() = Some(Box::new(authenticate));
 557        self
 558    }
 559
 560    #[cfg(any(test, feature = "test-support"))]
 561    pub fn override_establish_connection<F>(&self, connect: F) -> &Self
 562    where
 563        F: 'static
 564            + Send
 565            + Sync
 566            + Fn(&Credentials, &AsyncApp) -> Task<Result<Connection, EstablishConnectionError>>,
 567    {
 568        *self.establish_connection.write() = Some(Box::new(connect));
 569        self
 570    }
 571
 572    #[cfg(any(test, feature = "test-support"))]
 573    pub fn override_rpc_url(&self, url: Url) -> &Self {
 574        *self.rpc_url.write() = Some(url);
 575        self
 576    }
 577
 578    pub fn global(cx: &App) -> Arc<Self> {
 579        cx.global::<GlobalClient>().0.clone()
 580    }
 581    pub fn set_global(client: Arc<Client>, cx: &mut App) {
 582        cx.set_global(GlobalClient(client))
 583    }
 584
 585    pub fn user_id(&self) -> Option<u64> {
 586        self.state
 587            .read()
 588            .credentials
 589            .as_ref()
 590            .map(|credentials| credentials.user_id)
 591    }
 592
 593    pub fn peer_id(&self) -> Option<PeerId> {
 594        if let Status::Connected { peer_id, .. } = &*self.status().borrow() {
 595            Some(*peer_id)
 596        } else {
 597            None
 598        }
 599    }
 600
 601    pub fn status(&self) -> watch::Receiver<Status> {
 602        self.state.read().status.1.clone()
 603    }
 604
 605    fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncApp) {
 606        log::info!("set status on client {}: {:?}", self.id(), status);
 607        let mut state = self.state.write();
 608        *state.status.0.borrow_mut() = status;
 609
 610        match status {
 611            Status::Connected { .. } => {
 612                state._reconnect_task = None;
 613            }
 614            Status::ConnectionLost => {
 615                let this = self.clone();
 616                state._reconnect_task = Some(cx.spawn(move |cx| async move {
 617                    #[cfg(any(test, feature = "test-support"))]
 618                    let mut rng = StdRng::seed_from_u64(0);
 619                    #[cfg(not(any(test, feature = "test-support")))]
 620                    let mut rng = StdRng::from_entropy();
 621
 622                    let mut delay = INITIAL_RECONNECTION_DELAY;
 623                    while let Err(error) = this.authenticate_and_connect(true, &cx).await {
 624                        log::error!("failed to connect {}", error);
 625                        if matches!(*this.status().borrow(), Status::ConnectionError) {
 626                            this.set_status(
 627                                Status::ReconnectionError {
 628                                    next_reconnection: Instant::now() + delay,
 629                                },
 630                                &cx,
 631                            );
 632                            cx.background_executor().timer(delay).await;
 633                            delay = delay
 634                                .mul_f32(rng.gen_range(0.5..=2.5))
 635                                .max(INITIAL_RECONNECTION_DELAY)
 636                                .min(MAX_RECONNECTION_DELAY);
 637                        } else {
 638                            break;
 639                        }
 640                    }
 641                }));
 642            }
 643            Status::SignedOut | Status::UpgradeRequired => {
 644                self.telemetry.set_authenticated_user_info(None, false);
 645                state._reconnect_task.take();
 646            }
 647            _ => {}
 648        }
 649    }
 650
 651    pub fn subscribe_to_entity<T>(
 652        self: &Arc<Self>,
 653        remote_id: u64,
 654    ) -> Result<PendingEntitySubscription<T>>
 655    where
 656        T: 'static,
 657    {
 658        let id = (TypeId::of::<T>(), remote_id);
 659
 660        let mut state = self.handler_set.lock();
 661        if state.entities_by_type_and_remote_id.contains_key(&id) {
 662            return Err(anyhow!("already subscribed to entity"));
 663        }
 664
 665        state
 666            .entities_by_type_and_remote_id
 667            .insert(id, EntityMessageSubscriber::Pending(Default::default()));
 668
 669        Ok(PendingEntitySubscription {
 670            client: self.clone(),
 671            remote_id,
 672            consumed: false,
 673            _entity_type: PhantomData,
 674        })
 675    }
 676
 677    #[track_caller]
 678    pub fn add_message_handler<M, E, H, F>(
 679        self: &Arc<Self>,
 680        entity: WeakEntity<E>,
 681        handler: H,
 682    ) -> Subscription
 683    where
 684        M: EnvelopedMessage,
 685        E: 'static,
 686        H: 'static + Sync + Fn(Entity<E>, TypedEnvelope<M>, AsyncApp) -> F + Send + Sync,
 687        F: 'static + Future<Output = Result<()>>,
 688    {
 689        self.add_message_handler_impl(entity, move |entity, message, _, cx| {
 690            handler(entity, message, cx)
 691        })
 692    }
 693
 694    fn add_message_handler_impl<M, E, H, F>(
 695        self: &Arc<Self>,
 696        entity: WeakEntity<E>,
 697        handler: H,
 698    ) -> Subscription
 699    where
 700        M: EnvelopedMessage,
 701        E: 'static,
 702        H: 'static
 703            + Sync
 704            + Fn(Entity<E>, TypedEnvelope<M>, AnyProtoClient, AsyncApp) -> F
 705            + Send
 706            + Sync,
 707        F: 'static + Future<Output = Result<()>>,
 708    {
 709        let message_type_id = TypeId::of::<M>();
 710        let mut state = self.handler_set.lock();
 711        state
 712            .entities_by_message_type
 713            .insert(message_type_id, entity.into());
 714
 715        let prev_handler = state.message_handlers.insert(
 716            message_type_id,
 717            Arc::new(move |subscriber, envelope, client, cx| {
 718                let subscriber = subscriber.downcast::<E>().unwrap();
 719                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 720                handler(subscriber, *envelope, client.clone(), cx).boxed_local()
 721            }),
 722        );
 723        if prev_handler.is_some() {
 724            let location = std::panic::Location::caller();
 725            panic!(
 726                "{}:{} registered handler for the same message {} twice",
 727                location.file(),
 728                location.line(),
 729                std::any::type_name::<M>()
 730            );
 731        }
 732
 733        Subscription::Message {
 734            client: Arc::downgrade(self),
 735            id: message_type_id,
 736        }
 737    }
 738
 739    pub fn add_request_handler<M, E, H, F>(
 740        self: &Arc<Self>,
 741        entity: WeakEntity<E>,
 742        handler: H,
 743    ) -> Subscription
 744    where
 745        M: RequestMessage,
 746        E: 'static,
 747        H: 'static + Sync + Fn(Entity<E>, TypedEnvelope<M>, AsyncApp) -> F + Send + Sync,
 748        F: 'static + Future<Output = Result<M::Response>>,
 749    {
 750        self.add_message_handler_impl(entity, move |handle, envelope, this, cx| {
 751            Self::respond_to_request(envelope.receipt(), handler(handle, envelope, cx), this)
 752        })
 753    }
 754
 755    async fn respond_to_request<T: RequestMessage, F: Future<Output = Result<T::Response>>>(
 756        receipt: Receipt<T>,
 757        response: F,
 758        client: AnyProtoClient,
 759    ) -> Result<()> {
 760        match response.await {
 761            Ok(response) => {
 762                client.send_response(receipt.message_id, response)?;
 763                Ok(())
 764            }
 765            Err(error) => {
 766                client.send_response(receipt.message_id, error.to_proto())?;
 767                Err(error)
 768            }
 769        }
 770    }
 771
 772    pub async fn has_credentials(&self, cx: &AsyncApp) -> bool {
 773        self.credentials_provider
 774            .read_credentials(cx)
 775            .await
 776            .is_some()
 777    }
 778
 779    #[async_recursion(?Send)]
 780    pub async fn authenticate_and_connect(
 781        self: &Arc<Self>,
 782        try_provider: bool,
 783        cx: &AsyncApp,
 784    ) -> anyhow::Result<()> {
 785        let was_disconnected = match *self.status().borrow() {
 786            Status::SignedOut => true,
 787            Status::ConnectionError
 788            | Status::ConnectionLost
 789            | Status::Authenticating { .. }
 790            | Status::Reauthenticating { .. }
 791            | Status::ReconnectionError { .. } => false,
 792            Status::Connected { .. } | Status::Connecting { .. } | Status::Reconnecting { .. } => {
 793                return Ok(())
 794            }
 795            Status::UpgradeRequired => return Err(EstablishConnectionError::UpgradeRequired)?,
 796        };
 797        if was_disconnected {
 798            self.set_status(Status::Authenticating, cx);
 799        } else {
 800            self.set_status(Status::Reauthenticating, cx)
 801        }
 802
 803        let mut read_from_provider = false;
 804        let mut credentials = self.state.read().credentials.clone();
 805        if credentials.is_none() && try_provider {
 806            credentials = self.credentials_provider.read_credentials(cx).await;
 807            read_from_provider = credentials.is_some();
 808        }
 809
 810        if credentials.is_none() {
 811            let mut status_rx = self.status();
 812            let _ = status_rx.next().await;
 813            futures::select_biased! {
 814                authenticate = self.authenticate(cx).fuse() => {
 815                    match authenticate {
 816                        Ok(creds) => credentials = Some(creds),
 817                        Err(err) => {
 818                            self.set_status(Status::ConnectionError, cx);
 819                            return Err(err);
 820                        }
 821                    }
 822                }
 823                _ = status_rx.next().fuse() => {
 824                    return Err(anyhow!("authentication canceled"));
 825                }
 826            }
 827        }
 828        let credentials = credentials.unwrap();
 829        self.set_id(credentials.user_id);
 830
 831        if was_disconnected {
 832            self.set_status(Status::Connecting, cx);
 833        } else {
 834            self.set_status(Status::Reconnecting, cx);
 835        }
 836
 837        let mut timeout =
 838            futures::FutureExt::fuse(cx.background_executor().timer(CONNECTION_TIMEOUT));
 839        futures::select_biased! {
 840            connection = self.establish_connection(&credentials, cx).fuse() => {
 841                match connection {
 842                    Ok(conn) => {
 843                        self.state.write().credentials = Some(credentials.clone());
 844                        if !read_from_provider && IMPERSONATE_LOGIN.is_none() {
 845                                self.credentials_provider.write_credentials(credentials.user_id, credentials.access_token, cx).await.log_err();
 846
 847                        }
 848
 849                        futures::select_biased! {
 850                            result = self.set_connection(conn, cx).fuse() => result,
 851                            _ = timeout => {
 852                                self.set_status(Status::ConnectionError, cx);
 853                                Err(anyhow!("timed out waiting on hello message from server"))
 854                            }
 855                        }
 856                    }
 857                    Err(EstablishConnectionError::Unauthorized) => {
 858                        self.state.write().credentials.take();
 859                        if read_from_provider {
 860                            self.credentials_provider.delete_credentials(cx).await.log_err();
 861                            self.set_status(Status::SignedOut, cx);
 862                            self.authenticate_and_connect(false, cx).await
 863                        } else {
 864                            self.set_status(Status::ConnectionError, cx);
 865                            Err(EstablishConnectionError::Unauthorized)?
 866                        }
 867                    }
 868                    Err(EstablishConnectionError::UpgradeRequired) => {
 869                        self.set_status(Status::UpgradeRequired, cx);
 870                        Err(EstablishConnectionError::UpgradeRequired)?
 871                    }
 872                    Err(error) => {
 873                        self.set_status(Status::ConnectionError, cx);
 874                        Err(error)?
 875                    }
 876                }
 877            }
 878            _ = &mut timeout => {
 879                self.set_status(Status::ConnectionError, cx);
 880                Err(anyhow!("timed out trying to establish connection"))
 881            }
 882        }
 883    }
 884
 885    async fn set_connection(self: &Arc<Self>, conn: Connection, cx: &AsyncApp) -> Result<()> {
 886        let executor = cx.background_executor();
 887        log::debug!("add connection to peer");
 888        let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn, {
 889            let executor = executor.clone();
 890            move |duration| executor.timer(duration)
 891        });
 892        let handle_io = executor.spawn(handle_io);
 893
 894        let peer_id = async {
 895            log::debug!("waiting for server hello");
 896            let message = incoming
 897                .next()
 898                .await
 899                .ok_or_else(|| anyhow!("no hello message received"))?;
 900            log::debug!("got server hello");
 901            let hello_message_type_name = message.payload_type_name().to_string();
 902            let hello = message
 903                .into_any()
 904                .downcast::<TypedEnvelope<proto::Hello>>()
 905                .map_err(|_| {
 906                    anyhow!(
 907                        "invalid hello message received: {:?}",
 908                        hello_message_type_name
 909                    )
 910                })?;
 911            let peer_id = hello
 912                .payload
 913                .peer_id
 914                .ok_or_else(|| anyhow!("invalid peer id"))?;
 915            Ok(peer_id)
 916        };
 917
 918        let peer_id = match peer_id.await {
 919            Ok(peer_id) => peer_id,
 920            Err(error) => {
 921                self.peer.disconnect(connection_id);
 922                return Err(error);
 923            }
 924        };
 925
 926        log::debug!(
 927            "set status to connected (connection id: {:?}, peer id: {:?})",
 928            connection_id,
 929            peer_id
 930        );
 931        self.set_status(
 932            Status::Connected {
 933                peer_id,
 934                connection_id,
 935            },
 936            cx,
 937        );
 938
 939        cx.spawn({
 940            let this = self.clone();
 941            |cx| {
 942                async move {
 943                    while let Some(message) = incoming.next().await {
 944                        this.handle_message(message, &cx);
 945                        // Don't starve the main thread when receiving lots of messages at once.
 946                        smol::future::yield_now().await;
 947                    }
 948                }
 949            }
 950        })
 951        .detach();
 952
 953        cx.spawn({
 954            let this = self.clone();
 955            move |cx| async move {
 956                match handle_io.await {
 957                    Ok(()) => {
 958                        if *this.status().borrow()
 959                            == (Status::Connected {
 960                                connection_id,
 961                                peer_id,
 962                            })
 963                        {
 964                            this.set_status(Status::SignedOut, &cx);
 965                        }
 966                    }
 967                    Err(err) => {
 968                        log::error!("connection error: {:?}", err);
 969                        this.set_status(Status::ConnectionLost, &cx);
 970                    }
 971                }
 972            }
 973        })
 974        .detach();
 975
 976        Ok(())
 977    }
 978
 979    fn authenticate(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
 980        #[cfg(any(test, feature = "test-support"))]
 981        if let Some(callback) = self.authenticate.read().as_ref() {
 982            return callback(cx);
 983        }
 984
 985        self.authenticate_with_browser(cx)
 986    }
 987
 988    fn establish_connection(
 989        self: &Arc<Self>,
 990        credentials: &Credentials,
 991        cx: &AsyncApp,
 992    ) -> Task<Result<Connection, EstablishConnectionError>> {
 993        #[cfg(any(test, feature = "test-support"))]
 994        if let Some(callback) = self.establish_connection.read().as_ref() {
 995            return callback(credentials, cx);
 996        }
 997
 998        self.establish_websocket_connection(credentials, cx)
 999    }
1000
1001    fn rpc_url(
1002        &self,
1003        http: Arc<HttpClientWithUrl>,
1004        release_channel: Option<ReleaseChannel>,
1005    ) -> impl Future<Output = Result<url::Url>> {
1006        #[cfg(any(test, feature = "test-support"))]
1007        let url_override = self.rpc_url.read().clone();
1008
1009        async move {
1010            #[cfg(any(test, feature = "test-support"))]
1011            if let Some(url) = url_override {
1012                return Ok(url);
1013            }
1014
1015            if let Some(url) = &*ZED_RPC_URL {
1016                return Url::parse(url).context("invalid rpc url");
1017            }
1018
1019            let mut url = http.build_url("/rpc");
1020            if let Some(preview_param) =
1021                release_channel.and_then(|channel| channel.release_query_param())
1022            {
1023                url += "?";
1024                url += preview_param;
1025            }
1026
1027            let response = http.get(&url, Default::default(), false).await?;
1028            let collab_url = if response.status().is_redirection() {
1029                response
1030                    .headers()
1031                    .get("Location")
1032                    .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
1033                    .to_str()
1034                    .map_err(EstablishConnectionError::other)?
1035                    .to_string()
1036            } else {
1037                Err(anyhow!(
1038                    "unexpected /rpc response status {}",
1039                    response.status()
1040                ))?
1041            };
1042
1043            Url::parse(&collab_url).context("invalid rpc url")
1044        }
1045    }
1046
1047    fn establish_websocket_connection(
1048        self: &Arc<Self>,
1049        credentials: &Credentials,
1050        cx: &AsyncApp,
1051    ) -> Task<Result<Connection, EstablishConnectionError>> {
1052        let release_channel = cx
1053            .update(|cx| ReleaseChannel::try_global(cx))
1054            .ok()
1055            .flatten();
1056        let app_version = cx
1057            .update(|cx| AppVersion::global(cx).to_string())
1058            .ok()
1059            .unwrap_or_default();
1060
1061        let http = self.http.clone();
1062        let proxy = http.proxy().cloned();
1063        let credentials = credentials.clone();
1064        let rpc_url = self.rpc_url(http, release_channel);
1065        let system_id = self.telemetry.system_id();
1066        let metrics_id = self.telemetry.metrics_id();
1067        cx.background_executor().spawn(async move {
1068            use HttpOrHttps::*;
1069
1070            #[derive(Debug)]
1071            enum HttpOrHttps {
1072                Http,
1073                Https,
1074            }
1075
1076            let mut rpc_url = rpc_url.await?;
1077            let url_scheme = match rpc_url.scheme() {
1078                "https" => Https,
1079                "http" => Http,
1080                _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1081            };
1082            let rpc_host = rpc_url
1083                .host_str()
1084                .zip(rpc_url.port_or_known_default())
1085                .ok_or_else(|| anyhow!("missing host in rpc url"))?;
1086            let stream = connect_socks_proxy_stream(proxy.as_ref(), rpc_host).await?;
1087
1088            log::info!("connected to rpc endpoint {}", rpc_url);
1089
1090            rpc_url
1091                .set_scheme(match url_scheme {
1092                    Https => "wss",
1093                    Http => "ws",
1094                })
1095                .unwrap();
1096
1097            // We call `into_client_request` to let `tungstenite` construct the WebSocket request
1098            // for us from the RPC URL.
1099            //
1100            // Among other things, it will generate and set a `Sec-WebSocket-Key` header for us.
1101            let mut request = IntoClientRequest::into_client_request(rpc_url.as_str())?;
1102
1103            // We then modify the request to add our desired headers.
1104            let request_headers = request.headers_mut();
1105            request_headers.insert(
1106                "Authorization",
1107                HeaderValue::from_str(&credentials.authorization_header())?,
1108            );
1109            request_headers.insert(
1110                "x-zed-protocol-version",
1111                HeaderValue::from_str(&rpc::PROTOCOL_VERSION.to_string())?,
1112            );
1113            request_headers.insert("x-zed-app-version", HeaderValue::from_str(&app_version)?);
1114            request_headers.insert(
1115                "x-zed-release-channel",
1116                HeaderValue::from_str(release_channel.map(|r| r.dev_name()).unwrap_or("unknown"))?,
1117            );
1118            if let Some(system_id) = system_id {
1119                request_headers.insert("x-zed-system-id", HeaderValue::from_str(&system_id)?);
1120            }
1121            if let Some(metrics_id) = metrics_id {
1122                request_headers.insert("x-zed-metrics-id", HeaderValue::from_str(&metrics_id)?);
1123            }
1124
1125            match url_scheme {
1126                Https => {
1127                    let client_config = {
1128                        let mut root_store = rustls::RootCertStore::empty();
1129
1130                        let root_certs = rustls_native_certs::load_native_certs();
1131                        for error in root_certs.errors {
1132                            log::warn!("error loading native certs: {:?}", error);
1133                        }
1134                        root_store.add_parsable_certificates(
1135                            &root_certs
1136                                .certs
1137                                .into_iter()
1138                                .map(|cert| cert.as_ref().to_owned())
1139                                .collect::<Vec<_>>(),
1140                        );
1141                        rustls::ClientConfig::builder()
1142                            .with_safe_defaults()
1143                            .with_root_certificates(root_store)
1144                            .with_no_client_auth()
1145                    };
1146
1147                    let (stream, _) =
1148                        async_tungstenite::async_tls::client_async_tls_with_connector(
1149                            request,
1150                            stream,
1151                            Some(client_config.into()),
1152                        )
1153                        .await?;
1154                    Ok(Connection::new(
1155                        stream
1156                            .map_err(|error| anyhow!(error))
1157                            .sink_map_err(|error| anyhow!(error)),
1158                    ))
1159                }
1160                Http => {
1161                    let (stream, _) = async_tungstenite::client_async(request, stream).await?;
1162                    Ok(Connection::new(
1163                        stream
1164                            .map_err(|error| anyhow!(error))
1165                            .sink_map_err(|error| anyhow!(error)),
1166                    ))
1167                }
1168            }
1169        })
1170    }
1171
1172    pub fn authenticate_with_browser(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1173        let http = self.http.clone();
1174        let this = self.clone();
1175        cx.spawn(|cx| async move {
1176            let background = cx.background_executor().clone();
1177
1178            let (open_url_tx, open_url_rx) = oneshot::channel::<String>();
1179            cx.update(|cx| {
1180                cx.spawn(move |cx| async move {
1181                    let url = open_url_rx.await?;
1182                    cx.update(|cx| cx.open_url(&url))
1183                })
1184                .detach_and_log_err(cx);
1185            })
1186            .log_err();
1187
1188            let credentials = background
1189                .clone()
1190                .spawn(async move {
1191                    // Generate a pair of asymmetric encryption keys. The public key will be used by the
1192                    // zed server to encrypt the user's access token, so that it can'be intercepted by
1193                    // any other app running on the user's device.
1194                    let (public_key, private_key) =
1195                        rpc::auth::keypair().expect("failed to generate keypair for auth");
1196                    let public_key_string = String::try_from(public_key)
1197                        .expect("failed to serialize public key for auth");
1198
1199                    if let Some((login, token)) =
1200                        IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref())
1201                    {
1202                        eprintln!("authenticate as admin {login}, {token}");
1203
1204                        return this
1205                            .authenticate_as_admin(http, login.clone(), token.clone())
1206                            .await;
1207                    }
1208
1209                    // Start an HTTP server to receive the redirect from Zed's sign-in page.
1210                    let server =
1211                        tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1212                    let port = server.server_addr().port();
1213
1214                    // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1215                    // that the user is signing in from a Zed app running on the same device.
1216                    let mut url = http.build_url(&format!(
1217                        "/native_app_signin?native_app_port={}&native_app_public_key={}",
1218                        port, public_key_string
1219                    ));
1220
1221                    if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1222                        log::info!("impersonating user @{}", impersonate_login);
1223                        write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1224                    }
1225
1226                    open_url_tx.send(url).log_err();
1227
1228                    // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1229                    // access token from the query params.
1230                    //
1231                    // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1232                    // custom URL scheme instead of this local HTTP server.
1233                    let (user_id, access_token) = background
1234                        .spawn(async move {
1235                            for _ in 0..100 {
1236                                if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1237                                    let path = req.url();
1238                                    let mut user_id = None;
1239                                    let mut access_token = None;
1240                                    let url = Url::parse(&format!("http://example.com{}", path))
1241                                        .context("failed to parse login notification url")?;
1242                                    for (key, value) in url.query_pairs() {
1243                                        if key == "access_token" {
1244                                            access_token = Some(value.to_string());
1245                                        } else if key == "user_id" {
1246                                            user_id = Some(value.to_string());
1247                                        }
1248                                    }
1249
1250                                    let post_auth_url =
1251                                        http.build_url("/native_app_signin_succeeded");
1252                                    req.respond(
1253                                        tiny_http::Response::empty(302).with_header(
1254                                            tiny_http::Header::from_bytes(
1255                                                &b"Location"[..],
1256                                                post_auth_url.as_bytes(),
1257                                            )
1258                                            .unwrap(),
1259                                        ),
1260                                    )
1261                                    .context("failed to respond to login http request")?;
1262                                    return Ok((
1263                                        user_id
1264                                            .ok_or_else(|| anyhow!("missing user_id parameter"))?,
1265                                        access_token.ok_or_else(|| {
1266                                            anyhow!("missing access_token parameter")
1267                                        })?,
1268                                    ));
1269                                }
1270                            }
1271
1272                            Err(anyhow!("didn't receive login redirect"))
1273                        })
1274                        .await?;
1275
1276                    let access_token = private_key
1277                        .decrypt_string(&access_token)
1278                        .context("failed to decrypt access token")?;
1279
1280                    Ok(Credentials {
1281                        user_id: user_id.parse()?,
1282                        access_token,
1283                    })
1284                })
1285                .await?;
1286
1287            cx.update(|cx| cx.activate(true))?;
1288            Ok(credentials)
1289        })
1290    }
1291
1292    async fn authenticate_as_admin(
1293        self: &Arc<Self>,
1294        http: Arc<HttpClientWithUrl>,
1295        login: String,
1296        mut api_token: String,
1297    ) -> Result<Credentials> {
1298        #[derive(Deserialize)]
1299        struct AuthenticatedUserResponse {
1300            user: User,
1301        }
1302
1303        #[derive(Deserialize)]
1304        struct User {
1305            id: u64,
1306        }
1307
1308        let github_user = {
1309            #[derive(Deserialize)]
1310            struct GithubUser {
1311                id: i32,
1312                login: String,
1313                created_at: DateTime<Utc>,
1314            }
1315
1316            let request = {
1317                let mut request_builder =
1318                    Request::get(&format!("https://api.github.com/users/{login}"));
1319                if let Ok(github_token) = std::env::var("GITHUB_TOKEN") {
1320                    request_builder =
1321                        request_builder.header("Authorization", format!("Bearer {}", github_token));
1322                }
1323
1324                request_builder.body(AsyncBody::empty())?
1325            };
1326
1327            let mut response = http
1328                .send(request)
1329                .await
1330                .context("error fetching GitHub user")?;
1331
1332            let mut body = Vec::new();
1333            response
1334                .body_mut()
1335                .read_to_end(&mut body)
1336                .await
1337                .context("error reading GitHub user")?;
1338
1339            if !response.status().is_success() {
1340                let text = String::from_utf8_lossy(body.as_slice());
1341                bail!(
1342                    "status error {}, response: {text:?}",
1343                    response.status().as_u16()
1344                );
1345            }
1346
1347            serde_json::from_slice::<GithubUser>(body.as_slice()).map_err(|err| {
1348                log::error!("Error deserializing: {:?}", err);
1349                log::error!(
1350                    "GitHub API response text: {:?}",
1351                    String::from_utf8_lossy(body.as_slice())
1352                );
1353                anyhow!("error deserializing GitHub user")
1354            })?
1355        };
1356
1357        let query_params = [
1358            ("github_login", &github_user.login),
1359            ("github_user_id", &github_user.id.to_string()),
1360            (
1361                "github_user_created_at",
1362                &github_user.created_at.to_rfc3339(),
1363            ),
1364        ];
1365
1366        // Use the collab server's admin API to retrieve the ID
1367        // of the impersonated user.
1368        let mut url = self.rpc_url(http.clone(), None).await?;
1369        url.set_path("/user");
1370        url.set_query(Some(
1371            &query_params
1372                .iter()
1373                .map(|(key, value)| {
1374                    format!(
1375                        "{}={}",
1376                        key,
1377                        url::form_urlencoded::byte_serialize(value.as_bytes()).collect::<String>()
1378                    )
1379                })
1380                .collect::<Vec<String>>()
1381                .join("&"),
1382        ));
1383        let request: http_client::Request<AsyncBody> = Request::get(url.as_str())
1384            .header("Authorization", format!("token {api_token}"))
1385            .body("".into())?;
1386
1387        let mut response = http.send(request).await?;
1388        let mut body = String::new();
1389        response.body_mut().read_to_string(&mut body).await?;
1390        if !response.status().is_success() {
1391            Err(anyhow!(
1392                "admin user request failed {} - {}",
1393                response.status().as_u16(),
1394                body,
1395            ))?;
1396        }
1397        let response: AuthenticatedUserResponse = serde_json::from_str(&body)?;
1398
1399        // Use the admin API token to authenticate as the impersonated user.
1400        api_token.insert_str(0, "ADMIN_TOKEN:");
1401        Ok(Credentials {
1402            user_id: response.user.id,
1403            access_token: api_token,
1404        })
1405    }
1406
1407    pub async fn sign_out(self: &Arc<Self>, cx: &AsyncApp) {
1408        self.state.write().credentials = None;
1409        self.disconnect(cx);
1410
1411        if self.has_credentials(cx).await {
1412            self.credentials_provider
1413                .delete_credentials(cx)
1414                .await
1415                .log_err();
1416        }
1417    }
1418
1419    pub fn disconnect(self: &Arc<Self>, cx: &AsyncApp) {
1420        self.peer.teardown();
1421        self.set_status(Status::SignedOut, cx);
1422    }
1423
1424    pub fn reconnect(self: &Arc<Self>, cx: &AsyncApp) {
1425        self.peer.teardown();
1426        self.set_status(Status::ConnectionLost, cx);
1427    }
1428
1429    fn connection_id(&self) -> Result<ConnectionId> {
1430        if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1431            Ok(connection_id)
1432        } else {
1433            Err(anyhow!("not connected"))
1434        }
1435    }
1436
1437    pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1438        log::debug!("rpc send. client_id:{}, name:{}", self.id(), T::NAME);
1439        self.peer.send(self.connection_id()?, message)
1440    }
1441
1442    pub fn request<T: RequestMessage>(
1443        &self,
1444        request: T,
1445    ) -> impl Future<Output = Result<T::Response>> {
1446        self.request_envelope(request)
1447            .map_ok(|envelope| envelope.payload)
1448    }
1449
1450    pub fn request_stream<T: RequestMessage>(
1451        &self,
1452        request: T,
1453    ) -> impl Future<Output = Result<impl Stream<Item = Result<T::Response>>>> {
1454        let client_id = self.id.load(Ordering::SeqCst);
1455        log::debug!(
1456            "rpc request start. client_id:{}. name:{}",
1457            client_id,
1458            T::NAME
1459        );
1460        let response = self
1461            .connection_id()
1462            .map(|conn_id| self.peer.request_stream(conn_id, request));
1463        async move {
1464            let response = response?.await;
1465            log::debug!(
1466                "rpc request finish. client_id:{}. name:{}",
1467                client_id,
1468                T::NAME
1469            );
1470            response
1471        }
1472    }
1473
1474    pub fn request_envelope<T: RequestMessage>(
1475        &self,
1476        request: T,
1477    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> {
1478        let client_id = self.id();
1479        log::debug!(
1480            "rpc request start. client_id:{}. name:{}",
1481            client_id,
1482            T::NAME
1483        );
1484        let response = self
1485            .connection_id()
1486            .map(|conn_id| self.peer.request_envelope(conn_id, request));
1487        async move {
1488            let response = response?.await;
1489            log::debug!(
1490                "rpc request finish. client_id:{}. name:{}",
1491                client_id,
1492                T::NAME
1493            );
1494            response
1495        }
1496    }
1497
1498    pub fn request_dynamic(
1499        &self,
1500        envelope: proto::Envelope,
1501        request_type: &'static str,
1502    ) -> impl Future<Output = Result<proto::Envelope>> {
1503        let client_id = self.id();
1504        log::debug!(
1505            "rpc request start. client_id:{}. name:{}",
1506            client_id,
1507            request_type
1508        );
1509        let response = self
1510            .connection_id()
1511            .map(|conn_id| self.peer.request_dynamic(conn_id, envelope, request_type));
1512        async move {
1513            let response = response?.await;
1514            log::debug!(
1515                "rpc request finish. client_id:{}. name:{}",
1516                client_id,
1517                request_type
1518            );
1519            Ok(response?.0)
1520        }
1521    }
1522
1523    fn handle_message(self: &Arc<Client>, message: Box<dyn AnyTypedEnvelope>, cx: &AsyncApp) {
1524        let sender_id = message.sender_id();
1525        let request_id = message.message_id();
1526        let type_name = message.payload_type_name();
1527        let original_sender_id = message.original_sender_id();
1528
1529        if let Some(future) = ProtoMessageHandlerSet::handle_message(
1530            &self.handler_set,
1531            message,
1532            self.clone().into(),
1533            cx.clone(),
1534        ) {
1535            let client_id = self.id();
1536            log::debug!(
1537                "rpc message received. client_id:{}, sender_id:{:?}, type:{}",
1538                client_id,
1539                original_sender_id,
1540                type_name
1541            );
1542            cx.spawn(move |_| async move {
1543                match future.await {
1544                    Ok(()) => {
1545                        log::debug!(
1546                            "rpc message handled. client_id:{}, sender_id:{:?}, type:{}",
1547                            client_id,
1548                            original_sender_id,
1549                            type_name
1550                        );
1551                    }
1552                    Err(error) => {
1553                        log::error!(
1554                            "error handling message. client_id:{}, sender_id:{:?}, type:{}, error:{:?}",
1555                            client_id,
1556                            original_sender_id,
1557                            type_name,
1558                            error
1559                        );
1560                    }
1561                }
1562            })
1563            .detach();
1564        } else {
1565            log::info!("unhandled message {}", type_name);
1566            self.peer
1567                .respond_with_unhandled_message(sender_id.into(), request_id, type_name)
1568                .log_err();
1569        }
1570    }
1571
1572    pub fn telemetry(&self) -> &Arc<Telemetry> {
1573        &self.telemetry
1574    }
1575}
1576
1577impl ProtoClient for Client {
1578    fn request(
1579        &self,
1580        envelope: proto::Envelope,
1581        request_type: &'static str,
1582    ) -> BoxFuture<'static, Result<proto::Envelope>> {
1583        self.request_dynamic(envelope, request_type).boxed()
1584    }
1585
1586    fn send(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1587        log::debug!("rpc send. client_id:{}, name:{}", self.id(), message_type);
1588        let connection_id = self.connection_id()?;
1589        self.peer.send_dynamic(connection_id, envelope)
1590    }
1591
1592    fn send_response(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1593        log::debug!(
1594            "rpc respond. client_id:{}, name:{}",
1595            self.id(),
1596            message_type
1597        );
1598        let connection_id = self.connection_id()?;
1599        self.peer.send_dynamic(connection_id, envelope)
1600    }
1601
1602    fn message_handler_set(&self) -> &parking_lot::Mutex<ProtoMessageHandlerSet> {
1603        &self.handler_set
1604    }
1605
1606    fn is_via_collab(&self) -> bool {
1607        true
1608    }
1609}
1610
1611#[derive(Serialize, Deserialize)]
1612struct DevelopmentCredentials {
1613    user_id: u64,
1614    access_token: String,
1615}
1616
1617/// A credentials provider that stores credentials in a local file.
1618///
1619/// This MUST only be used in development, as this is not a secure way of storing
1620/// credentials on user machines.
1621///
1622/// Its existence is purely to work around the annoyance of having to constantly
1623/// re-allow access to the system keychain when developing Zed.
1624struct DevelopmentCredentialsProvider {
1625    path: PathBuf,
1626}
1627
1628impl CredentialsProvider for DevelopmentCredentialsProvider {
1629    fn read_credentials<'a>(
1630        &'a self,
1631        _cx: &'a AsyncApp,
1632    ) -> Pin<Box<dyn Future<Output = Option<Credentials>> + 'a>> {
1633        async move {
1634            if IMPERSONATE_LOGIN.is_some() {
1635                return None;
1636            }
1637
1638            let json = std::fs::read(&self.path).log_err()?;
1639
1640            let credentials: DevelopmentCredentials = serde_json::from_slice(&json).log_err()?;
1641
1642            Some(Credentials {
1643                user_id: credentials.user_id,
1644                access_token: credentials.access_token,
1645            })
1646        }
1647        .boxed_local()
1648    }
1649
1650    fn write_credentials<'a>(
1651        &'a self,
1652        user_id: u64,
1653        access_token: String,
1654        _cx: &'a AsyncApp,
1655    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>> {
1656        async move {
1657            let json = serde_json::to_string(&DevelopmentCredentials {
1658                user_id,
1659                access_token,
1660            })?;
1661
1662            std::fs::write(&self.path, json)?;
1663
1664            Ok(())
1665        }
1666        .boxed_local()
1667    }
1668
1669    fn delete_credentials<'a>(
1670        &'a self,
1671        _cx: &'a AsyncApp,
1672    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>> {
1673        async move { Ok(std::fs::remove_file(&self.path)?) }.boxed_local()
1674    }
1675}
1676
1677/// A credentials provider that stores credentials in the system keychain.
1678struct KeychainCredentialsProvider;
1679
1680impl CredentialsProvider for KeychainCredentialsProvider {
1681    fn read_credentials<'a>(
1682        &'a self,
1683        cx: &'a AsyncApp,
1684    ) -> Pin<Box<dyn Future<Output = Option<Credentials>> + 'a>> {
1685        async move {
1686            if IMPERSONATE_LOGIN.is_some() {
1687                return None;
1688            }
1689
1690            let (user_id, access_token) = cx
1691                .update(|cx| cx.read_credentials(&ClientSettings::get_global(cx).server_url))
1692                .log_err()?
1693                .await
1694                .log_err()??;
1695
1696            Some(Credentials {
1697                user_id: user_id.parse().ok()?,
1698                access_token: String::from_utf8(access_token).ok()?,
1699            })
1700        }
1701        .boxed_local()
1702    }
1703
1704    fn write_credentials<'a>(
1705        &'a self,
1706        user_id: u64,
1707        access_token: String,
1708        cx: &'a AsyncApp,
1709    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>> {
1710        async move {
1711            cx.update(move |cx| {
1712                cx.write_credentials(
1713                    &ClientSettings::get_global(cx).server_url,
1714                    &user_id.to_string(),
1715                    access_token.as_bytes(),
1716                )
1717            })?
1718            .await
1719        }
1720        .boxed_local()
1721    }
1722
1723    fn delete_credentials<'a>(
1724        &'a self,
1725        cx: &'a AsyncApp,
1726    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>> {
1727        async move {
1728            cx.update(move |cx| cx.delete_credentials(&ClientSettings::get_global(cx).server_url))?
1729                .await
1730        }
1731        .boxed_local()
1732    }
1733}
1734
1735/// prefix for the zed:// url scheme
1736pub const ZED_URL_SCHEME: &str = "zed";
1737
1738/// Parses the given link into a Zed link.
1739///
1740/// Returns a [`Some`] containing the unprefixed link if the link is a Zed link.
1741/// Returns [`None`] otherwise.
1742pub fn parse_zed_link<'a>(link: &'a str, cx: &App) -> Option<&'a str> {
1743    let server_url = &ClientSettings::get_global(cx).server_url;
1744    if let Some(stripped) = link
1745        .strip_prefix(server_url)
1746        .and_then(|result| result.strip_prefix('/'))
1747    {
1748        return Some(stripped);
1749    }
1750    if let Some(stripped) = link
1751        .strip_prefix(ZED_URL_SCHEME)
1752        .and_then(|result| result.strip_prefix("://"))
1753    {
1754        return Some(stripped);
1755    }
1756
1757    None
1758}
1759
1760#[cfg(test)]
1761mod tests {
1762    use super::*;
1763    use crate::test::FakeServer;
1764
1765    use clock::FakeSystemClock;
1766    use gpui::{AppContext as _, BackgroundExecutor, TestAppContext};
1767    use http_client::FakeHttpClient;
1768    use parking_lot::Mutex;
1769    use proto::TypedEnvelope;
1770    use settings::SettingsStore;
1771    use std::future;
1772
1773    #[gpui::test(iterations = 10)]
1774    async fn test_reconnection(cx: &mut TestAppContext) {
1775        init_test(cx);
1776        let user_id = 5;
1777        let client = cx.update(|cx| {
1778            Client::new(
1779                Arc::new(FakeSystemClock::new()),
1780                FakeHttpClient::with_404_response(),
1781                cx,
1782            )
1783        });
1784        let server = FakeServer::for_client(user_id, &client, cx).await;
1785        let mut status = client.status();
1786        assert!(matches!(
1787            status.next().await,
1788            Some(Status::Connected { .. })
1789        ));
1790        assert_eq!(server.auth_count(), 1);
1791
1792        server.forbid_connections();
1793        server.disconnect();
1794        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1795
1796        server.allow_connections();
1797        cx.executor().advance_clock(Duration::from_secs(10));
1798        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1799        assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1800
1801        server.forbid_connections();
1802        server.disconnect();
1803        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1804
1805        // Clear cached credentials after authentication fails
1806        server.roll_access_token();
1807        server.allow_connections();
1808        cx.executor().run_until_parked();
1809        cx.executor().advance_clock(Duration::from_secs(10));
1810        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1811        assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1812    }
1813
1814    #[gpui::test(iterations = 10)]
1815    async fn test_connection_timeout(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1816        init_test(cx);
1817        let user_id = 5;
1818        let client = cx.update(|cx| {
1819            Client::new(
1820                Arc::new(FakeSystemClock::new()),
1821                FakeHttpClient::with_404_response(),
1822                cx,
1823            )
1824        });
1825        let mut status = client.status();
1826
1827        // Time out when client tries to connect.
1828        client.override_authenticate(move |cx| {
1829            cx.background_executor().spawn(async move {
1830                Ok(Credentials {
1831                    user_id,
1832                    access_token: "token".into(),
1833                })
1834            })
1835        });
1836        client.override_establish_connection(|_, cx| {
1837            cx.background_executor().spawn(async move {
1838                future::pending::<()>().await;
1839                unreachable!()
1840            })
1841        });
1842        let auth_and_connect = cx.spawn({
1843            let client = client.clone();
1844            |cx| async move { client.authenticate_and_connect(false, &cx).await }
1845        });
1846        executor.run_until_parked();
1847        assert!(matches!(status.next().await, Some(Status::Connecting)));
1848
1849        executor.advance_clock(CONNECTION_TIMEOUT);
1850        assert!(matches!(
1851            status.next().await,
1852            Some(Status::ConnectionError { .. })
1853        ));
1854        auth_and_connect.await.unwrap_err();
1855
1856        // Allow the connection to be established.
1857        let server = FakeServer::for_client(user_id, &client, cx).await;
1858        assert!(matches!(
1859            status.next().await,
1860            Some(Status::Connected { .. })
1861        ));
1862
1863        // Disconnect client.
1864        server.forbid_connections();
1865        server.disconnect();
1866        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1867
1868        // Time out when re-establishing the connection.
1869        server.allow_connections();
1870        client.override_establish_connection(|_, cx| {
1871            cx.background_executor().spawn(async move {
1872                future::pending::<()>().await;
1873                unreachable!()
1874            })
1875        });
1876        executor.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1877        assert!(matches!(
1878            status.next().await,
1879            Some(Status::Reconnecting { .. })
1880        ));
1881
1882        executor.advance_clock(CONNECTION_TIMEOUT);
1883        assert!(matches!(
1884            status.next().await,
1885            Some(Status::ReconnectionError { .. })
1886        ));
1887    }
1888
1889    #[gpui::test(iterations = 10)]
1890    async fn test_authenticating_more_than_once(
1891        cx: &mut TestAppContext,
1892        executor: BackgroundExecutor,
1893    ) {
1894        init_test(cx);
1895        let auth_count = Arc::new(Mutex::new(0));
1896        let dropped_auth_count = Arc::new(Mutex::new(0));
1897        let client = cx.update(|cx| {
1898            Client::new(
1899                Arc::new(FakeSystemClock::new()),
1900                FakeHttpClient::with_404_response(),
1901                cx,
1902            )
1903        });
1904        client.override_authenticate({
1905            let auth_count = auth_count.clone();
1906            let dropped_auth_count = dropped_auth_count.clone();
1907            move |cx| {
1908                let auth_count = auth_count.clone();
1909                let dropped_auth_count = dropped_auth_count.clone();
1910                cx.background_executor().spawn(async move {
1911                    *auth_count.lock() += 1;
1912                    let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
1913                    future::pending::<()>().await;
1914                    unreachable!()
1915                })
1916            }
1917        });
1918
1919        let _authenticate = cx.spawn({
1920            let client = client.clone();
1921            move |cx| async move { client.authenticate_and_connect(false, &cx).await }
1922        });
1923        executor.run_until_parked();
1924        assert_eq!(*auth_count.lock(), 1);
1925        assert_eq!(*dropped_auth_count.lock(), 0);
1926
1927        let _authenticate = cx.spawn({
1928            let client = client.clone();
1929            |cx| async move { client.authenticate_and_connect(false, &cx).await }
1930        });
1931        executor.run_until_parked();
1932        assert_eq!(*auth_count.lock(), 2);
1933        assert_eq!(*dropped_auth_count.lock(), 1);
1934    }
1935
1936    #[gpui::test]
1937    async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1938        init_test(cx);
1939        let user_id = 5;
1940        let client = cx.update(|cx| {
1941            Client::new(
1942                Arc::new(FakeSystemClock::new()),
1943                FakeHttpClient::with_404_response(),
1944                cx,
1945            )
1946        });
1947        let server = FakeServer::for_client(user_id, &client, cx).await;
1948
1949        let (done_tx1, done_rx1) = smol::channel::unbounded();
1950        let (done_tx2, done_rx2) = smol::channel::unbounded();
1951        AnyProtoClient::from(client.clone()).add_entity_message_handler(
1952            move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::JoinProject>, mut cx| {
1953                match entity.update(&mut cx, |entity, _| entity.id).unwrap() {
1954                    1 => done_tx1.try_send(()).unwrap(),
1955                    2 => done_tx2.try_send(()).unwrap(),
1956                    _ => unreachable!(),
1957                }
1958                async { Ok(()) }
1959            },
1960        );
1961        let entity1 = cx.new(|_| TestEntity {
1962            id: 1,
1963            subscription: None,
1964        });
1965        let entity2 = cx.new(|_| TestEntity {
1966            id: 2,
1967            subscription: None,
1968        });
1969        let entity3 = cx.new(|_| TestEntity {
1970            id: 3,
1971            subscription: None,
1972        });
1973
1974        let _subscription1 = client
1975            .subscribe_to_entity(1)
1976            .unwrap()
1977            .set_entity(&entity1, &mut cx.to_async());
1978        let _subscription2 = client
1979            .subscribe_to_entity(2)
1980            .unwrap()
1981            .set_entity(&entity2, &mut cx.to_async());
1982        // Ensure dropping a subscription for the same entity type still allows receiving of
1983        // messages for other entity IDs of the same type.
1984        let subscription3 = client
1985            .subscribe_to_entity(3)
1986            .unwrap()
1987            .set_entity(&entity3, &mut cx.to_async());
1988        drop(subscription3);
1989
1990        server.send(proto::JoinProject { project_id: 1 });
1991        server.send(proto::JoinProject { project_id: 2 });
1992        done_rx1.recv().await.unwrap();
1993        done_rx2.recv().await.unwrap();
1994    }
1995
1996    #[gpui::test]
1997    async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
1998        init_test(cx);
1999        let user_id = 5;
2000        let client = cx.update(|cx| {
2001            Client::new(
2002                Arc::new(FakeSystemClock::new()),
2003                FakeHttpClient::with_404_response(),
2004                cx,
2005            )
2006        });
2007        let server = FakeServer::for_client(user_id, &client, cx).await;
2008
2009        let entity = cx.new(|_| TestEntity::default());
2010        let (done_tx1, _done_rx1) = smol::channel::unbounded();
2011        let (done_tx2, done_rx2) = smol::channel::unbounded();
2012        let subscription1 = client.add_message_handler(
2013            entity.downgrade(),
2014            move |_, _: TypedEnvelope<proto::Ping>, _| {
2015                done_tx1.try_send(()).unwrap();
2016                async { Ok(()) }
2017            },
2018        );
2019        drop(subscription1);
2020        let _subscription2 = client.add_message_handler(
2021            entity.downgrade(),
2022            move |_, _: TypedEnvelope<proto::Ping>, _| {
2023                done_tx2.try_send(()).unwrap();
2024                async { Ok(()) }
2025            },
2026        );
2027        server.send(proto::Ping {});
2028        done_rx2.recv().await.unwrap();
2029    }
2030
2031    #[gpui::test]
2032    async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
2033        init_test(cx);
2034        let user_id = 5;
2035        let client = cx.update(|cx| {
2036            Client::new(
2037                Arc::new(FakeSystemClock::new()),
2038                FakeHttpClient::with_404_response(),
2039                cx,
2040            )
2041        });
2042        let server = FakeServer::for_client(user_id, &client, cx).await;
2043
2044        let entity = cx.new(|_| TestEntity::default());
2045        let (done_tx, done_rx) = smol::channel::unbounded();
2046        let subscription = client.add_message_handler(
2047            entity.clone().downgrade(),
2048            move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::Ping>, mut cx| {
2049                entity
2050                    .update(&mut cx, |entity, _| entity.subscription.take())
2051                    .unwrap();
2052                done_tx.try_send(()).unwrap();
2053                async { Ok(()) }
2054            },
2055        );
2056        entity.update(cx, |entity, _| {
2057            entity.subscription = Some(subscription);
2058        });
2059        server.send(proto::Ping {});
2060        done_rx.recv().await.unwrap();
2061    }
2062
2063    #[derive(Default)]
2064    struct TestEntity {
2065        id: usize,
2066        subscription: Option<Subscription>,
2067    }
2068
2069    fn init_test(cx: &mut TestAppContext) {
2070        cx.update(|cx| {
2071            let settings_store = SettingsStore::test(cx);
2072            cx.set_global(settings_store);
2073            init_settings(cx);
2074        });
2075    }
2076}