client.rs

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