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, AppContext as _, 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_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 (stream, _) =
1128                        async_tungstenite::async_tls::client_async_tls_with_connector(
1129                            request,
1130                            stream,
1131                            Some(http_client::tls_config().into()),
1132                        )
1133                        .await?;
1134                    Ok(Connection::new(
1135                        stream
1136                            .map_err(|error| anyhow!(error))
1137                            .sink_map_err(|error| anyhow!(error)),
1138                    ))
1139                }
1140                Http => {
1141                    let (stream, _) = async_tungstenite::client_async(request, stream).await?;
1142                    Ok(Connection::new(
1143                        stream
1144                            .map_err(|error| anyhow!(error))
1145                            .sink_map_err(|error| anyhow!(error)),
1146                    ))
1147                }
1148            }
1149        })
1150    }
1151
1152    pub fn authenticate_with_browser(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1153        let http = self.http.clone();
1154        let this = self.clone();
1155        cx.spawn(|cx| async move {
1156            let background = cx.background_executor().clone();
1157
1158            let (open_url_tx, open_url_rx) = oneshot::channel::<String>();
1159            cx.update(|cx| {
1160                cx.spawn(move |cx| async move {
1161                    let url = open_url_rx.await?;
1162                    cx.update(|cx| cx.open_url(&url))
1163                })
1164                .detach_and_log_err(cx);
1165            })
1166            .log_err();
1167
1168            let credentials = background
1169                .clone()
1170                .spawn(async move {
1171                    // Generate a pair of asymmetric encryption keys. The public key will be used by the
1172                    // zed server to encrypt the user's access token, so that it can'be intercepted by
1173                    // any other app running on the user's device.
1174                    let (public_key, private_key) =
1175                        rpc::auth::keypair().expect("failed to generate keypair for auth");
1176                    let public_key_string = String::try_from(public_key)
1177                        .expect("failed to serialize public key for auth");
1178
1179                    if let Some((login, token)) =
1180                        IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref())
1181                    {
1182                        eprintln!("authenticate as admin {login}, {token}");
1183
1184                        return this
1185                            .authenticate_as_admin(http, login.clone(), token.clone())
1186                            .await;
1187                    }
1188
1189                    // Start an HTTP server to receive the redirect from Zed's sign-in page.
1190                    let server =
1191                        tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1192                    let port = server.server_addr().port();
1193
1194                    // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1195                    // that the user is signing in from a Zed app running on the same device.
1196                    let mut url = http.build_url(&format!(
1197                        "/native_app_signin?native_app_port={}&native_app_public_key={}",
1198                        port, public_key_string
1199                    ));
1200
1201                    if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1202                        log::info!("impersonating user @{}", impersonate_login);
1203                        write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1204                    }
1205
1206                    open_url_tx.send(url).log_err();
1207
1208                    // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1209                    // access token from the query params.
1210                    //
1211                    // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1212                    // custom URL scheme instead of this local HTTP server.
1213                    let (user_id, access_token) = background
1214                        .spawn(async move {
1215                            for _ in 0..100 {
1216                                if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1217                                    let path = req.url();
1218                                    let mut user_id = None;
1219                                    let mut access_token = None;
1220                                    let url = Url::parse(&format!("http://example.com{}", path))
1221                                        .context("failed to parse login notification url")?;
1222                                    for (key, value) in url.query_pairs() {
1223                                        if key == "access_token" {
1224                                            access_token = Some(value.to_string());
1225                                        } else if key == "user_id" {
1226                                            user_id = Some(value.to_string());
1227                                        }
1228                                    }
1229
1230                                    let post_auth_url =
1231                                        http.build_url("/native_app_signin_succeeded");
1232                                    req.respond(
1233                                        tiny_http::Response::empty(302).with_header(
1234                                            tiny_http::Header::from_bytes(
1235                                                &b"Location"[..],
1236                                                post_auth_url.as_bytes(),
1237                                            )
1238                                            .unwrap(),
1239                                        ),
1240                                    )
1241                                    .context("failed to respond to login http request")?;
1242                                    return Ok((
1243                                        user_id
1244                                            .ok_or_else(|| anyhow!("missing user_id parameter"))?,
1245                                        access_token.ok_or_else(|| {
1246                                            anyhow!("missing access_token parameter")
1247                                        })?,
1248                                    ));
1249                                }
1250                            }
1251
1252                            Err(anyhow!("didn't receive login redirect"))
1253                        })
1254                        .await?;
1255
1256                    let access_token = private_key
1257                        .decrypt_string(&access_token)
1258                        .context("failed to decrypt access token")?;
1259
1260                    Ok(Credentials {
1261                        user_id: user_id.parse()?,
1262                        access_token,
1263                    })
1264                })
1265                .await?;
1266
1267            cx.update(|cx| cx.activate(true))?;
1268            Ok(credentials)
1269        })
1270    }
1271
1272    async fn authenticate_as_admin(
1273        self: &Arc<Self>,
1274        http: Arc<HttpClientWithUrl>,
1275        login: String,
1276        mut api_token: String,
1277    ) -> Result<Credentials> {
1278        #[derive(Deserialize)]
1279        struct AuthenticatedUserResponse {
1280            user: User,
1281        }
1282
1283        #[derive(Deserialize)]
1284        struct User {
1285            id: u64,
1286        }
1287
1288        let github_user = {
1289            #[derive(Deserialize)]
1290            struct GithubUser {
1291                id: i32,
1292                login: String,
1293                created_at: DateTime<Utc>,
1294            }
1295
1296            let request = {
1297                let mut request_builder =
1298                    Request::get(&format!("https://api.github.com/users/{login}"));
1299                if let Ok(github_token) = std::env::var("GITHUB_TOKEN") {
1300                    request_builder =
1301                        request_builder.header("Authorization", format!("Bearer {}", github_token));
1302                }
1303
1304                request_builder.body(AsyncBody::empty())?
1305            };
1306
1307            let mut response = http
1308                .send(request)
1309                .await
1310                .context("error fetching GitHub user")?;
1311
1312            let mut body = Vec::new();
1313            response
1314                .body_mut()
1315                .read_to_end(&mut body)
1316                .await
1317                .context("error reading GitHub user")?;
1318
1319            if !response.status().is_success() {
1320                let text = String::from_utf8_lossy(body.as_slice());
1321                bail!(
1322                    "status error {}, response: {text:?}",
1323                    response.status().as_u16()
1324                );
1325            }
1326
1327            serde_json::from_slice::<GithubUser>(body.as_slice()).map_err(|err| {
1328                log::error!("Error deserializing: {:?}", err);
1329                log::error!(
1330                    "GitHub API response text: {:?}",
1331                    String::from_utf8_lossy(body.as_slice())
1332                );
1333                anyhow!("error deserializing GitHub user")
1334            })?
1335        };
1336
1337        let query_params = [
1338            ("github_login", &github_user.login),
1339            ("github_user_id", &github_user.id.to_string()),
1340            (
1341                "github_user_created_at",
1342                &github_user.created_at.to_rfc3339(),
1343            ),
1344        ];
1345
1346        // Use the collab server's admin API to retrieve the ID
1347        // of the impersonated user.
1348        let mut url = self.rpc_url(http.clone(), None).await?;
1349        url.set_path("/user");
1350        url.set_query(Some(
1351            &query_params
1352                .iter()
1353                .map(|(key, value)| {
1354                    format!(
1355                        "{}={}",
1356                        key,
1357                        url::form_urlencoded::byte_serialize(value.as_bytes()).collect::<String>()
1358                    )
1359                })
1360                .collect::<Vec<String>>()
1361                .join("&"),
1362        ));
1363        let request: http_client::Request<AsyncBody> = Request::get(url.as_str())
1364            .header("Authorization", format!("token {api_token}"))
1365            .body("".into())?;
1366
1367        let mut response = http.send(request).await?;
1368        let mut body = String::new();
1369        response.body_mut().read_to_string(&mut body).await?;
1370        if !response.status().is_success() {
1371            Err(anyhow!(
1372                "admin user request failed {} - {}",
1373                response.status().as_u16(),
1374                body,
1375            ))?;
1376        }
1377        let response: AuthenticatedUserResponse = serde_json::from_str(&body)?;
1378
1379        // Use the admin API token to authenticate as the impersonated user.
1380        api_token.insert_str(0, "ADMIN_TOKEN:");
1381        Ok(Credentials {
1382            user_id: response.user.id,
1383            access_token: api_token,
1384        })
1385    }
1386
1387    pub async fn sign_out(self: &Arc<Self>, cx: &AsyncApp) {
1388        self.state.write().credentials = None;
1389        self.disconnect(cx);
1390
1391        if self.has_credentials(cx).await {
1392            self.credentials_provider
1393                .delete_credentials(cx)
1394                .await
1395                .log_err();
1396        }
1397    }
1398
1399    pub fn disconnect(self: &Arc<Self>, cx: &AsyncApp) {
1400        self.peer.teardown();
1401        self.set_status(Status::SignedOut, cx);
1402    }
1403
1404    pub fn reconnect(self: &Arc<Self>, cx: &AsyncApp) {
1405        self.peer.teardown();
1406        self.set_status(Status::ConnectionLost, cx);
1407    }
1408
1409    fn connection_id(&self) -> Result<ConnectionId> {
1410        if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1411            Ok(connection_id)
1412        } else {
1413            Err(anyhow!("not connected"))
1414        }
1415    }
1416
1417    pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1418        log::debug!("rpc send. client_id:{}, name:{}", self.id(), T::NAME);
1419        self.peer.send(self.connection_id()?, message)
1420    }
1421
1422    pub fn request<T: RequestMessage>(
1423        &self,
1424        request: T,
1425    ) -> impl Future<Output = Result<T::Response>> {
1426        self.request_envelope(request)
1427            .map_ok(|envelope| envelope.payload)
1428    }
1429
1430    pub fn request_stream<T: RequestMessage>(
1431        &self,
1432        request: T,
1433    ) -> impl Future<Output = Result<impl Stream<Item = Result<T::Response>>>> {
1434        let client_id = self.id.load(Ordering::SeqCst);
1435        log::debug!(
1436            "rpc request start. client_id:{}. name:{}",
1437            client_id,
1438            T::NAME
1439        );
1440        let response = self
1441            .connection_id()
1442            .map(|conn_id| self.peer.request_stream(conn_id, request));
1443        async move {
1444            let response = response?.await;
1445            log::debug!(
1446                "rpc request finish. client_id:{}. name:{}",
1447                client_id,
1448                T::NAME
1449            );
1450            response
1451        }
1452    }
1453
1454    pub fn request_envelope<T: RequestMessage>(
1455        &self,
1456        request: T,
1457    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> {
1458        let client_id = self.id();
1459        log::debug!(
1460            "rpc request start. client_id:{}. name:{}",
1461            client_id,
1462            T::NAME
1463        );
1464        let response = self
1465            .connection_id()
1466            .map(|conn_id| self.peer.request_envelope(conn_id, request));
1467        async move {
1468            let response = response?.await;
1469            log::debug!(
1470                "rpc request finish. client_id:{}. name:{}",
1471                client_id,
1472                T::NAME
1473            );
1474            response
1475        }
1476    }
1477
1478    pub fn request_dynamic(
1479        &self,
1480        envelope: proto::Envelope,
1481        request_type: &'static str,
1482    ) -> impl Future<Output = Result<proto::Envelope>> {
1483        let client_id = self.id();
1484        log::debug!(
1485            "rpc request start. client_id:{}. name:{}",
1486            client_id,
1487            request_type
1488        );
1489        let response = self
1490            .connection_id()
1491            .map(|conn_id| self.peer.request_dynamic(conn_id, envelope, request_type));
1492        async move {
1493            let response = response?.await;
1494            log::debug!(
1495                "rpc request finish. client_id:{}. name:{}",
1496                client_id,
1497                request_type
1498            );
1499            Ok(response?.0)
1500        }
1501    }
1502
1503    fn handle_message(self: &Arc<Client>, message: Box<dyn AnyTypedEnvelope>, cx: &AsyncApp) {
1504        let sender_id = message.sender_id();
1505        let request_id = message.message_id();
1506        let type_name = message.payload_type_name();
1507        let original_sender_id = message.original_sender_id();
1508
1509        if let Some(future) = ProtoMessageHandlerSet::handle_message(
1510            &self.handler_set,
1511            message,
1512            self.clone().into(),
1513            cx.clone(),
1514        ) {
1515            let client_id = self.id();
1516            log::debug!(
1517                "rpc message received. client_id:{}, sender_id:{:?}, type:{}",
1518                client_id,
1519                original_sender_id,
1520                type_name
1521            );
1522            cx.spawn(move |_| async move {
1523                match future.await {
1524                    Ok(()) => {
1525                        log::debug!(
1526                            "rpc message handled. client_id:{}, sender_id:{:?}, type:{}",
1527                            client_id,
1528                            original_sender_id,
1529                            type_name
1530                        );
1531                    }
1532                    Err(error) => {
1533                        log::error!(
1534                            "error handling message. client_id:{}, sender_id:{:?}, type:{}, error:{:?}",
1535                            client_id,
1536                            original_sender_id,
1537                            type_name,
1538                            error
1539                        );
1540                    }
1541                }
1542            })
1543            .detach();
1544        } else {
1545            log::info!("unhandled message {}", type_name);
1546            self.peer
1547                .respond_with_unhandled_message(sender_id.into(), request_id, type_name)
1548                .log_err();
1549        }
1550    }
1551
1552    pub fn telemetry(&self) -> &Arc<Telemetry> {
1553        &self.telemetry
1554    }
1555}
1556
1557impl ProtoClient for Client {
1558    fn request(
1559        &self,
1560        envelope: proto::Envelope,
1561        request_type: &'static str,
1562    ) -> BoxFuture<'static, Result<proto::Envelope>> {
1563        self.request_dynamic(envelope, request_type).boxed()
1564    }
1565
1566    fn send(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1567        log::debug!("rpc send. client_id:{}, name:{}", self.id(), message_type);
1568        let connection_id = self.connection_id()?;
1569        self.peer.send_dynamic(connection_id, envelope)
1570    }
1571
1572    fn send_response(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1573        log::debug!(
1574            "rpc respond. client_id:{}, name:{}",
1575            self.id(),
1576            message_type
1577        );
1578        let connection_id = self.connection_id()?;
1579        self.peer.send_dynamic(connection_id, envelope)
1580    }
1581
1582    fn message_handler_set(&self) -> &parking_lot::Mutex<ProtoMessageHandlerSet> {
1583        &self.handler_set
1584    }
1585
1586    fn is_via_collab(&self) -> bool {
1587        true
1588    }
1589}
1590
1591#[derive(Serialize, Deserialize)]
1592struct DevelopmentCredentials {
1593    user_id: u64,
1594    access_token: String,
1595}
1596
1597/// A credentials provider that stores credentials in a local file.
1598///
1599/// This MUST only be used in development, as this is not a secure way of storing
1600/// credentials on user machines.
1601///
1602/// Its existence is purely to work around the annoyance of having to constantly
1603/// re-allow access to the system keychain when developing Zed.
1604struct DevelopmentCredentialsProvider {
1605    path: PathBuf,
1606}
1607
1608impl CredentialsProvider for DevelopmentCredentialsProvider {
1609    fn read_credentials<'a>(
1610        &'a self,
1611        _cx: &'a AsyncApp,
1612    ) -> Pin<Box<dyn Future<Output = Option<Credentials>> + 'a>> {
1613        async move {
1614            if IMPERSONATE_LOGIN.is_some() {
1615                return None;
1616            }
1617
1618            let json = std::fs::read(&self.path).log_err()?;
1619
1620            let credentials: DevelopmentCredentials = serde_json::from_slice(&json).log_err()?;
1621
1622            Some(Credentials {
1623                user_id: credentials.user_id,
1624                access_token: credentials.access_token,
1625            })
1626        }
1627        .boxed_local()
1628    }
1629
1630    fn write_credentials<'a>(
1631        &'a self,
1632        user_id: u64,
1633        access_token: String,
1634        _cx: &'a AsyncApp,
1635    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>> {
1636        async move {
1637            let json = serde_json::to_string(&DevelopmentCredentials {
1638                user_id,
1639                access_token,
1640            })?;
1641
1642            std::fs::write(&self.path, json)?;
1643
1644            Ok(())
1645        }
1646        .boxed_local()
1647    }
1648
1649    fn delete_credentials<'a>(
1650        &'a self,
1651        _cx: &'a AsyncApp,
1652    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>> {
1653        async move { Ok(std::fs::remove_file(&self.path)?) }.boxed_local()
1654    }
1655}
1656
1657/// A credentials provider that stores credentials in the system keychain.
1658struct KeychainCredentialsProvider;
1659
1660impl CredentialsProvider for KeychainCredentialsProvider {
1661    fn read_credentials<'a>(
1662        &'a self,
1663        cx: &'a AsyncApp,
1664    ) -> Pin<Box<dyn Future<Output = Option<Credentials>> + 'a>> {
1665        async move {
1666            if IMPERSONATE_LOGIN.is_some() {
1667                return None;
1668            }
1669
1670            let (user_id, access_token) = cx
1671                .update(|cx| cx.read_credentials(&ClientSettings::get_global(cx).server_url))
1672                .log_err()?
1673                .await
1674                .log_err()??;
1675
1676            Some(Credentials {
1677                user_id: user_id.parse().ok()?,
1678                access_token: String::from_utf8(access_token).ok()?,
1679            })
1680        }
1681        .boxed_local()
1682    }
1683
1684    fn write_credentials<'a>(
1685        &'a self,
1686        user_id: u64,
1687        access_token: String,
1688        cx: &'a AsyncApp,
1689    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>> {
1690        async move {
1691            cx.update(move |cx| {
1692                cx.write_credentials(
1693                    &ClientSettings::get_global(cx).server_url,
1694                    &user_id.to_string(),
1695                    access_token.as_bytes(),
1696                )
1697            })?
1698            .await
1699        }
1700        .boxed_local()
1701    }
1702
1703    fn delete_credentials<'a>(
1704        &'a self,
1705        cx: &'a AsyncApp,
1706    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>> {
1707        async move {
1708            cx.update(move |cx| cx.delete_credentials(&ClientSettings::get_global(cx).server_url))?
1709                .await
1710        }
1711        .boxed_local()
1712    }
1713}
1714
1715/// prefix for the zed:// url scheme
1716pub const ZED_URL_SCHEME: &str = "zed";
1717
1718/// Parses the given link into a Zed link.
1719///
1720/// Returns a [`Some`] containing the unprefixed link if the link is a Zed link.
1721/// Returns [`None`] otherwise.
1722pub fn parse_zed_link<'a>(link: &'a str, cx: &App) -> Option<&'a str> {
1723    let server_url = &ClientSettings::get_global(cx).server_url;
1724    if let Some(stripped) = link
1725        .strip_prefix(server_url)
1726        .and_then(|result| result.strip_prefix('/'))
1727    {
1728        return Some(stripped);
1729    }
1730    if let Some(stripped) = link
1731        .strip_prefix(ZED_URL_SCHEME)
1732        .and_then(|result| result.strip_prefix("://"))
1733    {
1734        return Some(stripped);
1735    }
1736
1737    None
1738}
1739
1740#[cfg(test)]
1741mod tests {
1742    use super::*;
1743    use crate::test::FakeServer;
1744
1745    use clock::FakeSystemClock;
1746    use gpui::{BackgroundExecutor, TestAppContext};
1747    use http_client::FakeHttpClient;
1748    use parking_lot::Mutex;
1749    use proto::TypedEnvelope;
1750    use settings::SettingsStore;
1751    use std::future;
1752
1753    #[gpui::test(iterations = 10)]
1754    async fn test_reconnection(cx: &mut TestAppContext) {
1755        init_test(cx);
1756        let user_id = 5;
1757        let client = cx.update(|cx| {
1758            Client::new(
1759                Arc::new(FakeSystemClock::new()),
1760                FakeHttpClient::with_404_response(),
1761                cx,
1762            )
1763        });
1764        let server = FakeServer::for_client(user_id, &client, cx).await;
1765        let mut status = client.status();
1766        assert!(matches!(
1767            status.next().await,
1768            Some(Status::Connected { .. })
1769        ));
1770        assert_eq!(server.auth_count(), 1);
1771
1772        server.forbid_connections();
1773        server.disconnect();
1774        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1775
1776        server.allow_connections();
1777        cx.executor().advance_clock(Duration::from_secs(10));
1778        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1779        assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1780
1781        server.forbid_connections();
1782        server.disconnect();
1783        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1784
1785        // Clear cached credentials after authentication fails
1786        server.roll_access_token();
1787        server.allow_connections();
1788        cx.executor().run_until_parked();
1789        cx.executor().advance_clock(Duration::from_secs(10));
1790        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1791        assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1792    }
1793
1794    #[gpui::test(iterations = 10)]
1795    async fn test_connection_timeout(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1796        init_test(cx);
1797        let user_id = 5;
1798        let client = cx.update(|cx| {
1799            Client::new(
1800                Arc::new(FakeSystemClock::new()),
1801                FakeHttpClient::with_404_response(),
1802                cx,
1803            )
1804        });
1805        let mut status = client.status();
1806
1807        // Time out when client tries to connect.
1808        client.override_authenticate(move |cx| {
1809            cx.background_spawn(async move {
1810                Ok(Credentials {
1811                    user_id,
1812                    access_token: "token".into(),
1813                })
1814            })
1815        });
1816        client.override_establish_connection(|_, cx| {
1817            cx.background_spawn(async move {
1818                future::pending::<()>().await;
1819                unreachable!()
1820            })
1821        });
1822        let auth_and_connect = cx.spawn({
1823            let client = client.clone();
1824            |cx| async move { client.authenticate_and_connect(false, &cx).await }
1825        });
1826        executor.run_until_parked();
1827        assert!(matches!(status.next().await, Some(Status::Connecting)));
1828
1829        executor.advance_clock(CONNECTION_TIMEOUT);
1830        assert!(matches!(
1831            status.next().await,
1832            Some(Status::ConnectionError { .. })
1833        ));
1834        auth_and_connect.await.unwrap_err();
1835
1836        // Allow the connection to be established.
1837        let server = FakeServer::for_client(user_id, &client, cx).await;
1838        assert!(matches!(
1839            status.next().await,
1840            Some(Status::Connected { .. })
1841        ));
1842
1843        // Disconnect client.
1844        server.forbid_connections();
1845        server.disconnect();
1846        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1847
1848        // Time out when re-establishing the connection.
1849        server.allow_connections();
1850        client.override_establish_connection(|_, cx| {
1851            cx.background_spawn(async move {
1852                future::pending::<()>().await;
1853                unreachable!()
1854            })
1855        });
1856        executor.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1857        assert!(matches!(
1858            status.next().await,
1859            Some(Status::Reconnecting { .. })
1860        ));
1861
1862        executor.advance_clock(CONNECTION_TIMEOUT);
1863        assert!(matches!(
1864            status.next().await,
1865            Some(Status::ReconnectionError { .. })
1866        ));
1867    }
1868
1869    #[gpui::test(iterations = 10)]
1870    async fn test_authenticating_more_than_once(
1871        cx: &mut TestAppContext,
1872        executor: BackgroundExecutor,
1873    ) {
1874        init_test(cx);
1875        let auth_count = Arc::new(Mutex::new(0));
1876        let dropped_auth_count = Arc::new(Mutex::new(0));
1877        let client = cx.update(|cx| {
1878            Client::new(
1879                Arc::new(FakeSystemClock::new()),
1880                FakeHttpClient::with_404_response(),
1881                cx,
1882            )
1883        });
1884        client.override_authenticate({
1885            let auth_count = auth_count.clone();
1886            let dropped_auth_count = dropped_auth_count.clone();
1887            move |cx| {
1888                let auth_count = auth_count.clone();
1889                let dropped_auth_count = dropped_auth_count.clone();
1890                cx.background_spawn(async move {
1891                    *auth_count.lock() += 1;
1892                    let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
1893                    future::pending::<()>().await;
1894                    unreachable!()
1895                })
1896            }
1897        });
1898
1899        let _authenticate = cx.spawn({
1900            let client = client.clone();
1901            move |cx| async move { client.authenticate_and_connect(false, &cx).await }
1902        });
1903        executor.run_until_parked();
1904        assert_eq!(*auth_count.lock(), 1);
1905        assert_eq!(*dropped_auth_count.lock(), 0);
1906
1907        let _authenticate = cx.spawn({
1908            let client = client.clone();
1909            |cx| async move { client.authenticate_and_connect(false, &cx).await }
1910        });
1911        executor.run_until_parked();
1912        assert_eq!(*auth_count.lock(), 2);
1913        assert_eq!(*dropped_auth_count.lock(), 1);
1914    }
1915
1916    #[gpui::test]
1917    async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1918        init_test(cx);
1919        let user_id = 5;
1920        let client = cx.update(|cx| {
1921            Client::new(
1922                Arc::new(FakeSystemClock::new()),
1923                FakeHttpClient::with_404_response(),
1924                cx,
1925            )
1926        });
1927        let server = FakeServer::for_client(user_id, &client, cx).await;
1928
1929        let (done_tx1, done_rx1) = smol::channel::unbounded();
1930        let (done_tx2, done_rx2) = smol::channel::unbounded();
1931        AnyProtoClient::from(client.clone()).add_entity_message_handler(
1932            move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::JoinProject>, mut cx| {
1933                match entity.update(&mut cx, |entity, _| entity.id).unwrap() {
1934                    1 => done_tx1.try_send(()).unwrap(),
1935                    2 => done_tx2.try_send(()).unwrap(),
1936                    _ => unreachable!(),
1937                }
1938                async { Ok(()) }
1939            },
1940        );
1941        let entity1 = cx.new(|_| TestEntity {
1942            id: 1,
1943            subscription: None,
1944        });
1945        let entity2 = cx.new(|_| TestEntity {
1946            id: 2,
1947            subscription: None,
1948        });
1949        let entity3 = cx.new(|_| TestEntity {
1950            id: 3,
1951            subscription: None,
1952        });
1953
1954        let _subscription1 = client
1955            .subscribe_to_entity(1)
1956            .unwrap()
1957            .set_entity(&entity1, &mut cx.to_async());
1958        let _subscription2 = client
1959            .subscribe_to_entity(2)
1960            .unwrap()
1961            .set_entity(&entity2, &mut cx.to_async());
1962        // Ensure dropping a subscription for the same entity type still allows receiving of
1963        // messages for other entity IDs of the same type.
1964        let subscription3 = client
1965            .subscribe_to_entity(3)
1966            .unwrap()
1967            .set_entity(&entity3, &mut cx.to_async());
1968        drop(subscription3);
1969
1970        server.send(proto::JoinProject { project_id: 1 });
1971        server.send(proto::JoinProject { project_id: 2 });
1972        done_rx1.recv().await.unwrap();
1973        done_rx2.recv().await.unwrap();
1974    }
1975
1976    #[gpui::test]
1977    async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
1978        init_test(cx);
1979        let user_id = 5;
1980        let client = cx.update(|cx| {
1981            Client::new(
1982                Arc::new(FakeSystemClock::new()),
1983                FakeHttpClient::with_404_response(),
1984                cx,
1985            )
1986        });
1987        let server = FakeServer::for_client(user_id, &client, cx).await;
1988
1989        let entity = cx.new(|_| TestEntity::default());
1990        let (done_tx1, _done_rx1) = smol::channel::unbounded();
1991        let (done_tx2, done_rx2) = smol::channel::unbounded();
1992        let subscription1 = client.add_message_handler(
1993            entity.downgrade(),
1994            move |_, _: TypedEnvelope<proto::Ping>, _| {
1995                done_tx1.try_send(()).unwrap();
1996                async { Ok(()) }
1997            },
1998        );
1999        drop(subscription1);
2000        let _subscription2 = client.add_message_handler(
2001            entity.downgrade(),
2002            move |_, _: TypedEnvelope<proto::Ping>, _| {
2003                done_tx2.try_send(()).unwrap();
2004                async { Ok(()) }
2005            },
2006        );
2007        server.send(proto::Ping {});
2008        done_rx2.recv().await.unwrap();
2009    }
2010
2011    #[gpui::test]
2012    async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
2013        init_test(cx);
2014        let user_id = 5;
2015        let client = cx.update(|cx| {
2016            Client::new(
2017                Arc::new(FakeSystemClock::new()),
2018                FakeHttpClient::with_404_response(),
2019                cx,
2020            )
2021        });
2022        let server = FakeServer::for_client(user_id, &client, cx).await;
2023
2024        let entity = cx.new(|_| TestEntity::default());
2025        let (done_tx, done_rx) = smol::channel::unbounded();
2026        let subscription = client.add_message_handler(
2027            entity.clone().downgrade(),
2028            move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::Ping>, mut cx| {
2029                entity
2030                    .update(&mut cx, |entity, _| entity.subscription.take())
2031                    .unwrap();
2032                done_tx.try_send(()).unwrap();
2033                async { Ok(()) }
2034            },
2035        );
2036        entity.update(cx, |entity, _| {
2037            entity.subscription = Some(subscription);
2038        });
2039        server.send(proto::Ping {});
2040        done_rx.recv().await.unwrap();
2041    }
2042
2043    #[derive(Default)]
2044    struct TestEntity {
2045        id: usize,
2046        subscription: Option<Subscription>,
2047    }
2048
2049    fn init_test(cx: &mut TestAppContext) {
2050        cx.update(|cx| {
2051            let settings_store = SettingsStore::test(cx);
2052            cx.set_global(settings_store);
2053            init_settings(cx);
2054        });
2055    }
2056}