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