client.rs

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