client.rs

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