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