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            if self
 860                .cloud_client
 861                .validate_credentials(
 862                    old_credentials.user_id as u32,
 863                    &old_credentials.access_token,
 864                )
 865                .await?
 866            {
 867                credentials = Some(old_credentials);
 868            }
 869        }
 870
 871        if credentials.is_none() && try_provider {
 872            if let Some(stored_credentials) = self.credentials_provider.read_credentials(cx).await {
 873                if self
 874                    .cloud_client
 875                    .validate_credentials(
 876                        stored_credentials.user_id as u32,
 877                        &stored_credentials.access_token,
 878                    )
 879                    .await?
 880                {
 881                    credentials = Some(stored_credentials);
 882                } else {
 883                    self.credentials_provider
 884                        .delete_credentials(cx)
 885                        .await
 886                        .log_err();
 887                }
 888            }
 889        }
 890
 891        if credentials.is_none() {
 892            let mut status_rx = self.status();
 893            let _ = status_rx.next().await;
 894            futures::select_biased! {
 895                authenticate = self.authenticate(cx).fuse() => {
 896                    match authenticate {
 897                        Ok(creds) => {
 898                            if IMPERSONATE_LOGIN.is_none() {
 899                                self.credentials_provider
 900                                    .write_credentials(creds.user_id, creds.access_token.clone(), cx)
 901                                    .await
 902                                    .log_err();
 903                            }
 904
 905                            credentials = Some(creds);
 906                        },
 907                        Err(err) => {
 908                            self.set_status(Status::AuthenticationError, cx);
 909                            return Err(err);
 910                        }
 911                    }
 912                }
 913                _ = status_rx.next().fuse() => {
 914                    return Err(anyhow!("authentication canceled"));
 915                }
 916            }
 917        }
 918
 919        let credentials = credentials.unwrap();
 920        self.set_id(credentials.user_id);
 921        self.cloud_client
 922            .set_credentials(credentials.user_id as u32, credentials.access_token.clone());
 923        self.state.write().credentials = Some(credentials.clone());
 924        self.set_status(Status::Authenticated, cx);
 925
 926        Ok(credentials)
 927    }
 928
 929    /// Performs a sign-in and also connects to Collab.
 930    ///
 931    /// This is called in places where we *don't* need to connect in the future. We will replace these calls with calls
 932    /// to `sign_in` when we're ready to remove auto-connection to Collab.
 933    pub async fn sign_in_with_optional_connect(
 934        self: &Arc<Self>,
 935        try_provider: bool,
 936        cx: &AsyncApp,
 937    ) -> Result<()> {
 938        let credentials = self.sign_in(try_provider, cx).await?;
 939
 940        let connect_result = match self.connect_with_credentials(credentials, cx).await {
 941            ConnectionResult::Timeout => Err(anyhow!("connection timed out")),
 942            ConnectionResult::ConnectionReset => Err(anyhow!("connection reset")),
 943            ConnectionResult::Result(result) => result.context("client auth and connect"),
 944        };
 945        connect_result.log_err();
 946
 947        Ok(())
 948    }
 949
 950    pub async fn connect(
 951        self: &Arc<Self>,
 952        try_provider: bool,
 953        cx: &AsyncApp,
 954    ) -> ConnectionResult<()> {
 955        let was_disconnected = match *self.status().borrow() {
 956            Status::SignedOut | Status::Authenticated => true,
 957            Status::ConnectionError
 958            | Status::ConnectionLost
 959            | Status::Authenticating { .. }
 960            | Status::AuthenticationError
 961            | Status::Reauthenticating { .. }
 962            | Status::ReconnectionError { .. } => false,
 963            Status::Connected { .. } | Status::Connecting { .. } | Status::Reconnecting { .. } => {
 964                return ConnectionResult::Result(Ok(()));
 965            }
 966            Status::UpgradeRequired => {
 967                return ConnectionResult::Result(
 968                    Err(EstablishConnectionError::UpgradeRequired)
 969                        .context("client auth and connect"),
 970                );
 971            }
 972        };
 973        let credentials = match self.sign_in(try_provider, cx).await {
 974            Ok(credentials) => credentials,
 975            Err(err) => return ConnectionResult::Result(Err(err)),
 976        };
 977
 978        if was_disconnected {
 979            self.set_status(Status::Connecting, cx);
 980        } else {
 981            self.set_status(Status::Reconnecting, cx);
 982        }
 983
 984        self.connect_with_credentials(credentials, cx).await
 985    }
 986
 987    async fn connect_with_credentials(
 988        self: &Arc<Self>,
 989        credentials: Credentials,
 990        cx: &AsyncApp,
 991    ) -> ConnectionResult<()> {
 992        let mut timeout =
 993            futures::FutureExt::fuse(cx.background_executor().timer(CONNECTION_TIMEOUT));
 994        futures::select_biased! {
 995            connection = self.establish_connection(&credentials, cx).fuse() => {
 996                match connection {
 997                    Ok(conn) => {
 998                        futures::select_biased! {
 999                            result = self.set_connection(conn, cx).fuse() => {
1000                                match result.context("client auth and connect") {
1001                                    Ok(()) => ConnectionResult::Result(Ok(())),
1002                                    Err(err) => {
1003                                        self.set_status(Status::ConnectionError, cx);
1004                                        ConnectionResult::Result(Err(err))
1005                                    },
1006                                }
1007                            },
1008                            _ = timeout => {
1009                                self.set_status(Status::ConnectionError, cx);
1010                                ConnectionResult::Timeout
1011                            }
1012                        }
1013                    }
1014                    Err(EstablishConnectionError::Unauthorized) => {
1015                        self.set_status(Status::ConnectionError, cx);
1016                        ConnectionResult::Result(Err(EstablishConnectionError::Unauthorized).context("client auth and connect"))
1017                    }
1018                    Err(EstablishConnectionError::UpgradeRequired) => {
1019                        self.set_status(Status::UpgradeRequired, cx);
1020                        ConnectionResult::Result(Err(EstablishConnectionError::UpgradeRequired).context("client auth and connect"))
1021                    }
1022                    Err(error) => {
1023                        self.set_status(Status::ConnectionError, cx);
1024                        ConnectionResult::Result(Err(error).context("client auth and connect"))
1025                    }
1026                }
1027            }
1028            _ = &mut timeout => {
1029                self.set_status(Status::ConnectionError, cx);
1030                ConnectionResult::Timeout
1031            }
1032        }
1033    }
1034
1035    async fn set_connection(self: &Arc<Self>, conn: Connection, cx: &AsyncApp) -> Result<()> {
1036        let executor = cx.background_executor();
1037        log::debug!("add connection to peer");
1038        let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn, {
1039            let executor = executor.clone();
1040            move |duration| executor.timer(duration)
1041        });
1042        let handle_io = executor.spawn(handle_io);
1043
1044        let peer_id = async {
1045            log::debug!("waiting for server hello");
1046            let message = incoming.next().await.context("no hello message received")?;
1047            log::debug!("got server hello");
1048            let hello_message_type_name = message.payload_type_name().to_string();
1049            let hello = message
1050                .into_any()
1051                .downcast::<TypedEnvelope<proto::Hello>>()
1052                .map_err(|_| {
1053                    anyhow!(
1054                        "invalid hello message received: {:?}",
1055                        hello_message_type_name
1056                    )
1057                })?;
1058            let peer_id = hello.payload.peer_id.context("invalid peer id")?;
1059            Ok(peer_id)
1060        };
1061
1062        let peer_id = match peer_id.await {
1063            Ok(peer_id) => peer_id,
1064            Err(error) => {
1065                self.peer.disconnect(connection_id);
1066                return Err(error);
1067            }
1068        };
1069
1070        log::debug!(
1071            "set status to connected (connection id: {:?}, peer id: {:?})",
1072            connection_id,
1073            peer_id
1074        );
1075        self.set_status(
1076            Status::Connected {
1077                peer_id,
1078                connection_id,
1079            },
1080            cx,
1081        );
1082
1083        cx.spawn({
1084            let this = self.clone();
1085            async move |cx| {
1086                while let Some(message) = incoming.next().await {
1087                    this.handle_message(message, &cx);
1088                    // Don't starve the main thread when receiving lots of messages at once.
1089                    smol::future::yield_now().await;
1090                }
1091            }
1092        })
1093        .detach();
1094
1095        cx.spawn({
1096            let this = self.clone();
1097            async move |cx| match handle_io.await {
1098                Ok(()) => {
1099                    if *this.status().borrow()
1100                        == (Status::Connected {
1101                            connection_id,
1102                            peer_id,
1103                        })
1104                    {
1105                        this.set_status(Status::SignedOut, &cx);
1106                    }
1107                }
1108                Err(err) => {
1109                    log::error!("connection error: {:?}", err);
1110                    this.set_status(Status::ConnectionLost, &cx);
1111                }
1112            }
1113        })
1114        .detach();
1115
1116        Ok(())
1117    }
1118
1119    fn authenticate(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1120        #[cfg(any(test, feature = "test-support"))]
1121        if let Some(callback) = self.authenticate.read().as_ref() {
1122            return callback(cx);
1123        }
1124
1125        self.authenticate_with_browser(cx)
1126    }
1127
1128    fn establish_connection(
1129        self: &Arc<Self>,
1130        credentials: &Credentials,
1131        cx: &AsyncApp,
1132    ) -> Task<Result<Connection, EstablishConnectionError>> {
1133        #[cfg(any(test, feature = "test-support"))]
1134        if let Some(callback) = self.establish_connection.read().as_ref() {
1135            return callback(credentials, cx);
1136        }
1137
1138        self.establish_websocket_connection(credentials, cx)
1139    }
1140
1141    fn rpc_url(
1142        &self,
1143        http: Arc<HttpClientWithUrl>,
1144        release_channel: Option<ReleaseChannel>,
1145    ) -> impl Future<Output = Result<url::Url>> + use<> {
1146        #[cfg(any(test, feature = "test-support"))]
1147        let url_override = self.rpc_url.read().clone();
1148
1149        async move {
1150            #[cfg(any(test, feature = "test-support"))]
1151            if let Some(url) = url_override {
1152                return Ok(url);
1153            }
1154
1155            if let Some(url) = &*ZED_RPC_URL {
1156                return Url::parse(url).context("invalid rpc url");
1157            }
1158
1159            let mut url = http.build_url("/rpc");
1160            if let Some(preview_param) =
1161                release_channel.and_then(|channel| channel.release_query_param())
1162            {
1163                url += "?";
1164                url += preview_param;
1165            }
1166
1167            let response = http.get(&url, Default::default(), false).await?;
1168            anyhow::ensure!(
1169                response.status().is_redirection(),
1170                "unexpected /rpc response status {}",
1171                response.status()
1172            );
1173            let collab_url = response
1174                .headers()
1175                .get("Location")
1176                .context("missing location header in /rpc response")?
1177                .to_str()
1178                .map_err(EstablishConnectionError::other)?
1179                .to_string();
1180            Url::parse(&collab_url).with_context(|| format!("parsing collab rpc url {collab_url}"))
1181        }
1182    }
1183
1184    fn establish_websocket_connection(
1185        self: &Arc<Self>,
1186        credentials: &Credentials,
1187        cx: &AsyncApp,
1188    ) -> Task<Result<Connection, EstablishConnectionError>> {
1189        let release_channel = cx
1190            .update(|cx| ReleaseChannel::try_global(cx))
1191            .ok()
1192            .flatten();
1193        let app_version = cx
1194            .update(|cx| AppVersion::global(cx).to_string())
1195            .ok()
1196            .unwrap_or_default();
1197
1198        let http = self.http.clone();
1199        let proxy = http.proxy().cloned();
1200        let user_agent = http.user_agent().cloned();
1201        let credentials = credentials.clone();
1202        let rpc_url = self.rpc_url(http, release_channel);
1203        let system_id = self.telemetry.system_id();
1204        let metrics_id = self.telemetry.metrics_id();
1205        cx.spawn(async move |cx| {
1206            use HttpOrHttps::*;
1207
1208            #[derive(Debug)]
1209            enum HttpOrHttps {
1210                Http,
1211                Https,
1212            }
1213
1214            let mut rpc_url = rpc_url.await?;
1215            let url_scheme = match rpc_url.scheme() {
1216                "https" => Https,
1217                "http" => Http,
1218                _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1219            };
1220            let rpc_host = rpc_url
1221                .host_str()
1222                .zip(rpc_url.port_or_known_default())
1223                .context("missing host in rpc url")?;
1224
1225            let stream = {
1226                let handle = cx.update(|cx| gpui_tokio::Tokio::handle(cx)).ok().unwrap();
1227                let _guard = handle.enter();
1228                match proxy {
1229                    Some(proxy) => connect_proxy_stream(&proxy, rpc_host).await?,
1230                    None => Box::new(TcpStream::connect(rpc_host).await?),
1231                }
1232            };
1233
1234            log::info!("connected to rpc endpoint {}", rpc_url);
1235
1236            rpc_url
1237                .set_scheme(match url_scheme {
1238                    Https => "wss",
1239                    Http => "ws",
1240                })
1241                .unwrap();
1242
1243            // We call `into_client_request` to let `tungstenite` construct the WebSocket request
1244            // for us from the RPC URL.
1245            //
1246            // Among other things, it will generate and set a `Sec-WebSocket-Key` header for us.
1247            let mut request = IntoClientRequest::into_client_request(rpc_url.as_str())?;
1248
1249            // We then modify the request to add our desired headers.
1250            let request_headers = request.headers_mut();
1251            request_headers.insert(
1252                http::header::AUTHORIZATION,
1253                HeaderValue::from_str(&credentials.authorization_header())?,
1254            );
1255            request_headers.insert(
1256                "x-zed-protocol-version",
1257                HeaderValue::from_str(&rpc::PROTOCOL_VERSION.to_string())?,
1258            );
1259            request_headers.insert("x-zed-app-version", HeaderValue::from_str(&app_version)?);
1260            request_headers.insert(
1261                "x-zed-release-channel",
1262                HeaderValue::from_str(release_channel.map(|r| r.dev_name()).unwrap_or("unknown"))?,
1263            );
1264            if let Some(user_agent) = user_agent {
1265                request_headers.insert(http::header::USER_AGENT, user_agent);
1266            }
1267            if let Some(system_id) = system_id {
1268                request_headers.insert("x-zed-system-id", HeaderValue::from_str(&system_id)?);
1269            }
1270            if let Some(metrics_id) = metrics_id {
1271                request_headers.insert("x-zed-metrics-id", HeaderValue::from_str(&metrics_id)?);
1272            }
1273
1274            let (stream, _) = async_tungstenite::tokio::client_async_tls_with_connector_and_config(
1275                request,
1276                stream,
1277                Some(Arc::new(http_client_tls::tls_config()).into()),
1278                None,
1279            )
1280            .await?;
1281
1282            Ok(Connection::new(
1283                stream
1284                    .map_err(|error| anyhow!(error))
1285                    .sink_map_err(|error| anyhow!(error)),
1286            ))
1287        })
1288    }
1289
1290    pub fn authenticate_with_browser(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1291        let http = self.http.clone();
1292        let this = self.clone();
1293        cx.spawn(async move |cx| {
1294            let background = cx.background_executor().clone();
1295
1296            let (open_url_tx, open_url_rx) = oneshot::channel::<String>();
1297            cx.update(|cx| {
1298                cx.spawn(async move |cx| {
1299                    let url = open_url_rx.await?;
1300                    cx.update(|cx| cx.open_url(&url))
1301                })
1302                .detach_and_log_err(cx);
1303            })
1304            .log_err();
1305
1306            let credentials = background
1307                .clone()
1308                .spawn(async move {
1309                    // Generate a pair of asymmetric encryption keys. The public key will be used by the
1310                    // zed server to encrypt the user's access token, so that it can'be intercepted by
1311                    // any other app running on the user's device.
1312                    let (public_key, private_key) =
1313                        rpc::auth::keypair().expect("failed to generate keypair for auth");
1314                    let public_key_string = String::try_from(public_key)
1315                        .expect("failed to serialize public key for auth");
1316
1317                    if let Some((login, token)) =
1318                        IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref())
1319                    {
1320                        eprintln!("authenticate as admin {login}, {token}");
1321
1322                        return this
1323                            .authenticate_as_admin(http, login.clone(), token.clone())
1324                            .await;
1325                    }
1326
1327                    // Start an HTTP server to receive the redirect from Zed's sign-in page.
1328                    let server =
1329                        tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1330                    let port = server.server_addr().port();
1331
1332                    // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1333                    // that the user is signing in from a Zed app running on the same device.
1334                    let mut url = http.build_url(&format!(
1335                        "/native_app_signin?native_app_port={}&native_app_public_key={}",
1336                        port, public_key_string
1337                    ));
1338
1339                    if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1340                        log::info!("impersonating user @{}", impersonate_login);
1341                        write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1342                    }
1343
1344                    open_url_tx.send(url).log_err();
1345
1346                    // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1347                    // access token from the query params.
1348                    //
1349                    // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1350                    // custom URL scheme instead of this local HTTP server.
1351                    let (user_id, access_token) = background
1352                        .spawn(async move {
1353                            for _ in 0..100 {
1354                                if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1355                                    let path = req.url();
1356                                    let mut user_id = None;
1357                                    let mut access_token = None;
1358                                    let url = Url::parse(&format!("http://example.com{}", path))
1359                                        .context("failed to parse login notification url")?;
1360                                    for (key, value) in url.query_pairs() {
1361                                        if key == "access_token" {
1362                                            access_token = Some(value.to_string());
1363                                        } else if key == "user_id" {
1364                                            user_id = Some(value.to_string());
1365                                        }
1366                                    }
1367
1368                                    let post_auth_url =
1369                                        http.build_url("/native_app_signin_succeeded");
1370                                    req.respond(
1371                                        tiny_http::Response::empty(302).with_header(
1372                                            tiny_http::Header::from_bytes(
1373                                                &b"Location"[..],
1374                                                post_auth_url.as_bytes(),
1375                                            )
1376                                            .unwrap(),
1377                                        ),
1378                                    )
1379                                    .context("failed to respond to login http request")?;
1380                                    return Ok((
1381                                        user_id.context("missing user_id parameter")?,
1382                                        access_token.context("missing access_token parameter")?,
1383                                    ));
1384                                }
1385                            }
1386
1387                            anyhow::bail!("didn't receive login redirect");
1388                        })
1389                        .await?;
1390
1391                    let access_token = private_key
1392                        .decrypt_string(&access_token)
1393                        .context("failed to decrypt access token")?;
1394
1395                    Ok(Credentials {
1396                        user_id: user_id.parse()?,
1397                        access_token,
1398                    })
1399                })
1400                .await?;
1401
1402            cx.update(|cx| cx.activate(true))?;
1403            Ok(credentials)
1404        })
1405    }
1406
1407    async fn authenticate_as_admin(
1408        self: &Arc<Self>,
1409        http: Arc<HttpClientWithUrl>,
1410        login: String,
1411        api_token: String,
1412    ) -> Result<Credentials> {
1413        #[derive(Serialize)]
1414        struct ImpersonateUserBody {
1415            github_login: String,
1416        }
1417
1418        #[derive(Deserialize)]
1419        struct ImpersonateUserResponse {
1420            user_id: u64,
1421            access_token: String,
1422        }
1423
1424        let url = self
1425            .http
1426            .build_zed_cloud_url("/internal/users/impersonate", &[])?;
1427        let request = Request::post(url.as_str())
1428            .header("Content-Type", "application/json")
1429            .header("Authorization", format!("Bearer {api_token}"))
1430            .body(
1431                serde_json::to_string(&ImpersonateUserBody {
1432                    github_login: login,
1433                })?
1434                .into(),
1435            )?;
1436
1437        let mut response = http.send(request).await?;
1438        let mut body = String::new();
1439        response.body_mut().read_to_string(&mut body).await?;
1440        anyhow::ensure!(
1441            response.status().is_success(),
1442            "admin user request failed {} - {}",
1443            response.status().as_u16(),
1444            body,
1445        );
1446        let response: ImpersonateUserResponse = serde_json::from_str(&body)?;
1447
1448        Ok(Credentials {
1449            user_id: response.user_id,
1450            access_token: response.access_token,
1451        })
1452    }
1453
1454    pub async fn sign_out(self: &Arc<Self>, cx: &AsyncApp) {
1455        self.state.write().credentials = None;
1456        self.cloud_client.clear_credentials();
1457        self.disconnect(cx);
1458
1459        if self.has_credentials(cx).await {
1460            self.credentials_provider
1461                .delete_credentials(cx)
1462                .await
1463                .log_err();
1464        }
1465    }
1466
1467    pub fn disconnect(self: &Arc<Self>, cx: &AsyncApp) {
1468        self.peer.teardown();
1469        self.set_status(Status::SignedOut, cx);
1470    }
1471
1472    pub fn reconnect(self: &Arc<Self>, cx: &AsyncApp) {
1473        self.peer.teardown();
1474        self.set_status(Status::ConnectionLost, cx);
1475    }
1476
1477    fn connection_id(&self) -> Result<ConnectionId> {
1478        if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1479            Ok(connection_id)
1480        } else {
1481            anyhow::bail!("not connected");
1482        }
1483    }
1484
1485    pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1486        log::debug!("rpc send. client_id:{}, name:{}", self.id(), T::NAME);
1487        self.peer.send(self.connection_id()?, message)
1488    }
1489
1490    pub fn request<T: RequestMessage>(
1491        &self,
1492        request: T,
1493    ) -> impl Future<Output = Result<T::Response>> + use<T> {
1494        self.request_envelope(request)
1495            .map_ok(|envelope| envelope.payload)
1496    }
1497
1498    pub fn request_stream<T: RequestMessage>(
1499        &self,
1500        request: T,
1501    ) -> impl Future<Output = Result<impl Stream<Item = Result<T::Response>>>> {
1502        let client_id = self.id.load(Ordering::SeqCst);
1503        log::debug!(
1504            "rpc request start. client_id:{}. name:{}",
1505            client_id,
1506            T::NAME
1507        );
1508        let response = self
1509            .connection_id()
1510            .map(|conn_id| self.peer.request_stream(conn_id, request));
1511        async move {
1512            let response = response?.await;
1513            log::debug!(
1514                "rpc request finish. client_id:{}. name:{}",
1515                client_id,
1516                T::NAME
1517            );
1518            response
1519        }
1520    }
1521
1522    pub fn request_envelope<T: RequestMessage>(
1523        &self,
1524        request: T,
1525    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> + use<T> {
1526        let client_id = self.id();
1527        log::debug!(
1528            "rpc request start. client_id:{}. name:{}",
1529            client_id,
1530            T::NAME
1531        );
1532        let response = self
1533            .connection_id()
1534            .map(|conn_id| self.peer.request_envelope(conn_id, request));
1535        async move {
1536            let response = response?.await;
1537            log::debug!(
1538                "rpc request finish. client_id:{}. name:{}",
1539                client_id,
1540                T::NAME
1541            );
1542            response
1543        }
1544    }
1545
1546    pub fn request_dynamic(
1547        &self,
1548        envelope: proto::Envelope,
1549        request_type: &'static str,
1550    ) -> impl Future<Output = Result<proto::Envelope>> + use<> {
1551        let client_id = self.id();
1552        log::debug!(
1553            "rpc request start. client_id:{}. name:{}",
1554            client_id,
1555            request_type
1556        );
1557        let response = self
1558            .connection_id()
1559            .map(|conn_id| self.peer.request_dynamic(conn_id, envelope, request_type));
1560        async move {
1561            let response = response?.await;
1562            log::debug!(
1563                "rpc request finish. client_id:{}. name:{}",
1564                client_id,
1565                request_type
1566            );
1567            Ok(response?.0)
1568        }
1569    }
1570
1571    fn handle_message(self: &Arc<Client>, message: Box<dyn AnyTypedEnvelope>, cx: &AsyncApp) {
1572        let sender_id = message.sender_id();
1573        let request_id = message.message_id();
1574        let type_name = message.payload_type_name();
1575        let original_sender_id = message.original_sender_id();
1576
1577        if let Some(future) = ProtoMessageHandlerSet::handle_message(
1578            &self.handler_set,
1579            message,
1580            self.clone().into(),
1581            cx.clone(),
1582        ) {
1583            let client_id = self.id();
1584            log::debug!(
1585                "rpc message received. client_id:{}, sender_id:{:?}, type:{}",
1586                client_id,
1587                original_sender_id,
1588                type_name
1589            );
1590            cx.spawn(async move |_| match future.await {
1591                Ok(()) => {
1592                    log::debug!(
1593                        "rpc message handled. client_id:{}, sender_id:{:?}, type:{}",
1594                        client_id,
1595                        original_sender_id,
1596                        type_name
1597                    );
1598                }
1599                Err(error) => {
1600                    log::error!(
1601                        "error handling message. client_id:{}, sender_id:{:?}, type:{}, error:{:?}",
1602                        client_id,
1603                        original_sender_id,
1604                        type_name,
1605                        error
1606                    );
1607                }
1608            })
1609            .detach();
1610        } else {
1611            log::info!("unhandled message {}", type_name);
1612            self.peer
1613                .respond_with_unhandled_message(sender_id.into(), request_id, type_name)
1614                .log_err();
1615        }
1616    }
1617
1618    pub fn telemetry(&self) -> &Arc<Telemetry> {
1619        &self.telemetry
1620    }
1621}
1622
1623impl ProtoClient for Client {
1624    fn request(
1625        &self,
1626        envelope: proto::Envelope,
1627        request_type: &'static str,
1628    ) -> BoxFuture<'static, Result<proto::Envelope>> {
1629        self.request_dynamic(envelope, request_type).boxed()
1630    }
1631
1632    fn send(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1633        log::debug!("rpc send. client_id:{}, name:{}", self.id(), message_type);
1634        let connection_id = self.connection_id()?;
1635        self.peer.send_dynamic(connection_id, envelope)
1636    }
1637
1638    fn send_response(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1639        log::debug!(
1640            "rpc respond. client_id:{}, name:{}",
1641            self.id(),
1642            message_type
1643        );
1644        let connection_id = self.connection_id()?;
1645        self.peer.send_dynamic(connection_id, envelope)
1646    }
1647
1648    fn message_handler_set(&self) -> &parking_lot::Mutex<ProtoMessageHandlerSet> {
1649        &self.handler_set
1650    }
1651
1652    fn is_via_collab(&self) -> bool {
1653        true
1654    }
1655}
1656
1657/// prefix for the zed:// url scheme
1658pub const ZED_URL_SCHEME: &str = "zed";
1659
1660/// Parses the given link into a Zed link.
1661///
1662/// Returns a [`Some`] containing the unprefixed link if the link is a Zed link.
1663/// Returns [`None`] otherwise.
1664pub fn parse_zed_link<'a>(link: &'a str, cx: &App) -> Option<&'a str> {
1665    let server_url = &ClientSettings::get_global(cx).server_url;
1666    if let Some(stripped) = link
1667        .strip_prefix(server_url)
1668        .and_then(|result| result.strip_prefix('/'))
1669    {
1670        return Some(stripped);
1671    }
1672    if let Some(stripped) = link
1673        .strip_prefix(ZED_URL_SCHEME)
1674        .and_then(|result| result.strip_prefix("://"))
1675    {
1676        return Some(stripped);
1677    }
1678
1679    None
1680}
1681
1682#[cfg(test)]
1683mod tests {
1684    use super::*;
1685    use crate::test::{FakeServer, parse_authorization_header};
1686
1687    use clock::FakeSystemClock;
1688    use gpui::{AppContext as _, BackgroundExecutor, TestAppContext};
1689    use http_client::FakeHttpClient;
1690    use parking_lot::Mutex;
1691    use proto::TypedEnvelope;
1692    use settings::SettingsStore;
1693    use std::future;
1694
1695    #[gpui::test(iterations = 10)]
1696    async fn test_reconnection(cx: &mut TestAppContext) {
1697        init_test(cx);
1698        let user_id = 5;
1699        let client = cx.update(|cx| {
1700            Client::new(
1701                Arc::new(FakeSystemClock::new()),
1702                FakeHttpClient::with_404_response(),
1703                cx,
1704            )
1705        });
1706        let server = FakeServer::for_client(user_id, &client, cx).await;
1707        let mut status = client.status();
1708        assert!(matches!(
1709            status.next().await,
1710            Some(Status::Connected { .. })
1711        ));
1712        assert_eq!(server.auth_count(), 1);
1713
1714        server.forbid_connections();
1715        server.disconnect();
1716        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1717
1718        server.allow_connections();
1719        cx.executor().advance_clock(Duration::from_secs(10));
1720        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1721        assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1722
1723        server.forbid_connections();
1724        server.disconnect();
1725        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1726
1727        // Clear cached credentials after authentication fails
1728        server.roll_access_token();
1729        server.allow_connections();
1730        cx.executor().run_until_parked();
1731        cx.executor().advance_clock(Duration::from_secs(10));
1732        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1733        assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1734    }
1735
1736    #[gpui::test(iterations = 10)]
1737    async fn test_connection_timeout(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1738        init_test(cx);
1739        let user_id = 5;
1740        let client = cx.update(|cx| {
1741            Client::new(
1742                Arc::new(FakeSystemClock::new()),
1743                FakeHttpClient::with_404_response(),
1744                cx,
1745            )
1746        });
1747        let mut status = client.status();
1748
1749        // Time out when client tries to connect.
1750        client.override_authenticate(move |cx| {
1751            cx.background_spawn(async move {
1752                Ok(Credentials {
1753                    user_id,
1754                    access_token: "token".into(),
1755                })
1756            })
1757        });
1758        client.override_establish_connection(|_, cx| {
1759            cx.background_spawn(async move {
1760                future::pending::<()>().await;
1761                unreachable!()
1762            })
1763        });
1764        let auth_and_connect = cx.spawn({
1765            let client = client.clone();
1766            |cx| async move { client.connect(false, &cx).await }
1767        });
1768        executor.run_until_parked();
1769        assert!(matches!(status.next().await, Some(Status::Connecting)));
1770
1771        executor.advance_clock(CONNECTION_TIMEOUT);
1772        assert!(matches!(
1773            status.next().await,
1774            Some(Status::ConnectionError { .. })
1775        ));
1776        auth_and_connect.await.into_response().unwrap_err();
1777
1778        // Allow the connection to be established.
1779        let server = FakeServer::for_client(user_id, &client, cx).await;
1780        assert!(matches!(
1781            status.next().await,
1782            Some(Status::Connected { .. })
1783        ));
1784
1785        // Disconnect client.
1786        server.forbid_connections();
1787        server.disconnect();
1788        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1789
1790        // Time out when re-establishing the connection.
1791        server.allow_connections();
1792        client.override_establish_connection(|_, cx| {
1793            cx.background_spawn(async move {
1794                future::pending::<()>().await;
1795                unreachable!()
1796            })
1797        });
1798        executor.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1799        assert!(matches!(
1800            status.next().await,
1801            Some(Status::Reconnecting { .. })
1802        ));
1803
1804        executor.advance_clock(CONNECTION_TIMEOUT);
1805        assert!(matches!(
1806            status.next().await,
1807            Some(Status::ReconnectionError { .. })
1808        ));
1809    }
1810
1811    #[gpui::test(iterations = 10)]
1812    async fn test_reauthenticate_only_if_unauthorized(cx: &mut TestAppContext) {
1813        init_test(cx);
1814        let auth_count = Arc::new(Mutex::new(0));
1815        let http_client = FakeHttpClient::create(|_request| async move {
1816            Ok(http_client::Response::builder()
1817                .status(200)
1818                .body("".into())
1819                .unwrap())
1820        });
1821        let client =
1822            cx.update(|cx| Client::new(Arc::new(FakeSystemClock::new()), http_client.clone(), cx));
1823        client.override_authenticate({
1824            let auth_count = auth_count.clone();
1825            move |cx| {
1826                let auth_count = auth_count.clone();
1827                cx.background_spawn(async move {
1828                    *auth_count.lock() += 1;
1829                    Ok(Credentials {
1830                        user_id: 1,
1831                        access_token: auth_count.lock().to_string(),
1832                    })
1833                })
1834            }
1835        });
1836
1837        let credentials = client.sign_in(false, &cx.to_async()).await.unwrap();
1838        assert_eq!(*auth_count.lock(), 1);
1839        assert_eq!(credentials.access_token, "1");
1840
1841        // If credentials are still valid, signing in doesn't trigger authentication.
1842        let credentials = client.sign_in(false, &cx.to_async()).await.unwrap();
1843        assert_eq!(*auth_count.lock(), 1);
1844        assert_eq!(credentials.access_token, "1");
1845
1846        // If the server is unavailable, signing in doesn't trigger authentication.
1847        http_client
1848            .as_fake()
1849            .replace_handler(|_, _request| async move {
1850                Ok(http_client::Response::builder()
1851                    .status(503)
1852                    .body("".into())
1853                    .unwrap())
1854            });
1855        client.sign_in(false, &cx.to_async()).await.unwrap_err();
1856        assert_eq!(*auth_count.lock(), 1);
1857
1858        // If credentials became invalid, signing in triggers authentication.
1859        http_client
1860            .as_fake()
1861            .replace_handler(|_, request| async move {
1862                let credentials = parse_authorization_header(&request).unwrap();
1863                if credentials.access_token == "2" {
1864                    Ok(http_client::Response::builder()
1865                        .status(200)
1866                        .body("".into())
1867                        .unwrap())
1868                } else {
1869                    Ok(http_client::Response::builder()
1870                        .status(401)
1871                        .body("".into())
1872                        .unwrap())
1873                }
1874            });
1875        let credentials = client.sign_in(false, &cx.to_async()).await.unwrap();
1876        assert_eq!(*auth_count.lock(), 2);
1877        assert_eq!(credentials.access_token, "2");
1878    }
1879
1880    #[gpui::test(iterations = 10)]
1881    async fn test_authenticating_more_than_once(
1882        cx: &mut TestAppContext,
1883        executor: BackgroundExecutor,
1884    ) {
1885        init_test(cx);
1886        let auth_count = Arc::new(Mutex::new(0));
1887        let dropped_auth_count = Arc::new(Mutex::new(0));
1888        let client = cx.update(|cx| {
1889            Client::new(
1890                Arc::new(FakeSystemClock::new()),
1891                FakeHttpClient::with_404_response(),
1892                cx,
1893            )
1894        });
1895        client.override_authenticate({
1896            let auth_count = auth_count.clone();
1897            let dropped_auth_count = dropped_auth_count.clone();
1898            move |cx| {
1899                let auth_count = auth_count.clone();
1900                let dropped_auth_count = dropped_auth_count.clone();
1901                cx.background_spawn(async move {
1902                    *auth_count.lock() += 1;
1903                    let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
1904                    future::pending::<()>().await;
1905                    unreachable!()
1906                })
1907            }
1908        });
1909
1910        let _authenticate = cx.spawn({
1911            let client = client.clone();
1912            move |cx| async move { client.connect(false, &cx).await }
1913        });
1914        executor.run_until_parked();
1915        assert_eq!(*auth_count.lock(), 1);
1916        assert_eq!(*dropped_auth_count.lock(), 0);
1917
1918        let _authenticate = cx.spawn({
1919            let client = client.clone();
1920            |cx| async move { client.connect(false, &cx).await }
1921        });
1922        executor.run_until_parked();
1923        assert_eq!(*auth_count.lock(), 2);
1924        assert_eq!(*dropped_auth_count.lock(), 1);
1925    }
1926
1927    #[gpui::test]
1928    async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1929        init_test(cx);
1930        let user_id = 5;
1931        let client = cx.update(|cx| {
1932            Client::new(
1933                Arc::new(FakeSystemClock::new()),
1934                FakeHttpClient::with_404_response(),
1935                cx,
1936            )
1937        });
1938        let server = FakeServer::for_client(user_id, &client, cx).await;
1939
1940        let (done_tx1, done_rx1) = smol::channel::unbounded();
1941        let (done_tx2, done_rx2) = smol::channel::unbounded();
1942        AnyProtoClient::from(client.clone()).add_entity_message_handler(
1943            move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::JoinProject>, mut cx| {
1944                match entity.read_with(&mut cx, |entity, _| entity.id).unwrap() {
1945                    1 => done_tx1.try_send(()).unwrap(),
1946                    2 => done_tx2.try_send(()).unwrap(),
1947                    _ => unreachable!(),
1948                }
1949                async { Ok(()) }
1950            },
1951        );
1952        let entity1 = cx.new(|_| TestEntity {
1953            id: 1,
1954            subscription: None,
1955        });
1956        let entity2 = cx.new(|_| TestEntity {
1957            id: 2,
1958            subscription: None,
1959        });
1960        let entity3 = cx.new(|_| TestEntity {
1961            id: 3,
1962            subscription: None,
1963        });
1964
1965        let _subscription1 = client
1966            .subscribe_to_entity(1)
1967            .unwrap()
1968            .set_entity(&entity1, &mut cx.to_async());
1969        let _subscription2 = client
1970            .subscribe_to_entity(2)
1971            .unwrap()
1972            .set_entity(&entity2, &mut cx.to_async());
1973        // Ensure dropping a subscription for the same entity type still allows receiving of
1974        // messages for other entity IDs of the same type.
1975        let subscription3 = client
1976            .subscribe_to_entity(3)
1977            .unwrap()
1978            .set_entity(&entity3, &mut cx.to_async());
1979        drop(subscription3);
1980
1981        server.send(proto::JoinProject {
1982            project_id: 1,
1983            committer_name: None,
1984            committer_email: None,
1985        });
1986        server.send(proto::JoinProject {
1987            project_id: 2,
1988            committer_name: None,
1989            committer_email: None,
1990        });
1991        done_rx1.recv().await.unwrap();
1992        done_rx2.recv().await.unwrap();
1993    }
1994
1995    #[gpui::test]
1996    async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
1997        init_test(cx);
1998        let user_id = 5;
1999        let client = cx.update(|cx| {
2000            Client::new(
2001                Arc::new(FakeSystemClock::new()),
2002                FakeHttpClient::with_404_response(),
2003                cx,
2004            )
2005        });
2006        let server = FakeServer::for_client(user_id, &client, cx).await;
2007
2008        let entity = cx.new(|_| TestEntity::default());
2009        let (done_tx1, _done_rx1) = smol::channel::unbounded();
2010        let (done_tx2, done_rx2) = smol::channel::unbounded();
2011        let subscription1 = client.add_message_handler(
2012            entity.downgrade(),
2013            move |_, _: TypedEnvelope<proto::Ping>, _| {
2014                done_tx1.try_send(()).unwrap();
2015                async { Ok(()) }
2016            },
2017        );
2018        drop(subscription1);
2019        let _subscription2 = client.add_message_handler(
2020            entity.downgrade(),
2021            move |_, _: TypedEnvelope<proto::Ping>, _| {
2022                done_tx2.try_send(()).unwrap();
2023                async { Ok(()) }
2024            },
2025        );
2026        server.send(proto::Ping {});
2027        done_rx2.recv().await.unwrap();
2028    }
2029
2030    #[gpui::test]
2031    async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
2032        init_test(cx);
2033        let user_id = 5;
2034        let client = cx.update(|cx| {
2035            Client::new(
2036                Arc::new(FakeSystemClock::new()),
2037                FakeHttpClient::with_404_response(),
2038                cx,
2039            )
2040        });
2041        let server = FakeServer::for_client(user_id, &client, cx).await;
2042
2043        let entity = cx.new(|_| TestEntity::default());
2044        let (done_tx, done_rx) = smol::channel::unbounded();
2045        let subscription = client.add_message_handler(
2046            entity.clone().downgrade(),
2047            move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::Ping>, mut cx| {
2048                entity
2049                    .update(&mut cx, |entity, _| entity.subscription.take())
2050                    .unwrap();
2051                done_tx.try_send(()).unwrap();
2052                async { Ok(()) }
2053            },
2054        );
2055        entity.update(cx, |entity, _| {
2056            entity.subscription = Some(subscription);
2057        });
2058        server.send(proto::Ping {});
2059        done_rx.recv().await.unwrap();
2060    }
2061
2062    #[derive(Default)]
2063    struct TestEntity {
2064        id: usize,
2065        subscription: Option<Subscription>,
2066    }
2067
2068    fn init_test(cx: &mut TestAppContext) {
2069        cx.update(|cx| {
2070            let settings_store = SettingsStore::test(cx);
2071            cx.set_global(settings_store);
2072            init_settings(cx);
2073        });
2074    }
2075}