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