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