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)]
 100pub struct ClientSettingsContent {
 101    server_url: Option<String>,
 102}
 103
 104#[derive(Deserialize, SettingsUi)]
 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)]
 126pub struct ProxySettingsContent {
 127    proxy: Option<String>,
 128}
 129
 130#[derive(Deserialize, Default, SettingsUi)]
 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, SettingsUi)]
 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)]
 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_entropy();
 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 =
 725                                Duration::from_millis(rng.gen_range(0..delay.as_millis() as u64));
 726                            cx.background_executor().timer(delay + jitter).await;
 727                            delay = cmp::min(delay * 2, MAX_RECONNECTION_DELAY);
 728                        } else {
 729                            break;
 730                        }
 731                    }
 732                }));
 733            }
 734            Status::SignedOut | Status::UpgradeRequired => {
 735                self.telemetry.set_authenticated_user_info(None, false);
 736                state._reconnect_task.take();
 737            }
 738            _ => {}
 739        }
 740    }
 741
 742    pub fn subscribe_to_entity<T>(
 743        self: &Arc<Self>,
 744        remote_id: u64,
 745    ) -> Result<PendingEntitySubscription<T>>
 746    where
 747        T: 'static,
 748    {
 749        let id = (TypeId::of::<T>(), remote_id);
 750
 751        let mut state = self.handler_set.lock();
 752        anyhow::ensure!(
 753            !state.entities_by_type_and_remote_id.contains_key(&id),
 754            "already subscribed to entity"
 755        );
 756
 757        state
 758            .entities_by_type_and_remote_id
 759            .insert(id, EntityMessageSubscriber::Pending(Default::default()));
 760
 761        Ok(PendingEntitySubscription {
 762            client: self.clone(),
 763            remote_id,
 764            consumed: false,
 765            _entity_type: PhantomData,
 766        })
 767    }
 768
 769    #[track_caller]
 770    pub fn add_message_handler<M, E, H, F>(
 771        self: &Arc<Self>,
 772        entity: WeakEntity<E>,
 773        handler: H,
 774    ) -> Subscription
 775    where
 776        M: EnvelopedMessage,
 777        E: 'static,
 778        H: 'static + Sync + Fn(Entity<E>, TypedEnvelope<M>, AsyncApp) -> F + Send + Sync,
 779        F: 'static + Future<Output = Result<()>>,
 780    {
 781        self.add_message_handler_impl(entity, move |entity, message, _, cx| {
 782            handler(entity, message, cx)
 783        })
 784    }
 785
 786    fn add_message_handler_impl<M, E, H, F>(
 787        self: &Arc<Self>,
 788        entity: WeakEntity<E>,
 789        handler: H,
 790    ) -> Subscription
 791    where
 792        M: EnvelopedMessage,
 793        E: 'static,
 794        H: 'static
 795            + Sync
 796            + Fn(Entity<E>, TypedEnvelope<M>, AnyProtoClient, AsyncApp) -> F
 797            + Send
 798            + Sync,
 799        F: 'static + Future<Output = Result<()>>,
 800    {
 801        let message_type_id = TypeId::of::<M>();
 802        let mut state = self.handler_set.lock();
 803        state
 804            .entities_by_message_type
 805            .insert(message_type_id, entity.into());
 806
 807        let prev_handler = state.message_handlers.insert(
 808            message_type_id,
 809            Arc::new(move |subscriber, envelope, client, cx| {
 810                let subscriber = subscriber.downcast::<E>().unwrap();
 811                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 812                handler(subscriber, *envelope, client, cx).boxed_local()
 813            }),
 814        );
 815        if prev_handler.is_some() {
 816            let location = std::panic::Location::caller();
 817            panic!(
 818                "{}:{} registered handler for the same message {} twice",
 819                location.file(),
 820                location.line(),
 821                std::any::type_name::<M>()
 822            );
 823        }
 824
 825        Subscription::Message {
 826            client: Arc::downgrade(self),
 827            id: message_type_id,
 828        }
 829    }
 830
 831    pub fn add_request_handler<M, E, H, F>(
 832        self: &Arc<Self>,
 833        entity: WeakEntity<E>,
 834        handler: H,
 835    ) -> Subscription
 836    where
 837        M: RequestMessage,
 838        E: 'static,
 839        H: 'static + Sync + Fn(Entity<E>, TypedEnvelope<M>, AsyncApp) -> F + Send + Sync,
 840        F: 'static + Future<Output = Result<M::Response>>,
 841    {
 842        self.add_message_handler_impl(entity, move |handle, envelope, this, cx| {
 843            Self::respond_to_request(envelope.receipt(), handler(handle, envelope, cx), this)
 844        })
 845    }
 846
 847    async fn respond_to_request<T: RequestMessage, F: Future<Output = Result<T::Response>>>(
 848        receipt: Receipt<T>,
 849        response: F,
 850        client: AnyProtoClient,
 851    ) -> Result<()> {
 852        match response.await {
 853            Ok(response) => {
 854                client.send_response(receipt.message_id, response)?;
 855                Ok(())
 856            }
 857            Err(error) => {
 858                client.send_response(receipt.message_id, error.to_proto())?;
 859                Err(error)
 860            }
 861        }
 862    }
 863
 864    pub async fn has_credentials(&self, cx: &AsyncApp) -> bool {
 865        self.credentials_provider
 866            .read_credentials(cx)
 867            .await
 868            .is_some()
 869    }
 870
 871    pub async fn sign_in(
 872        self: &Arc<Self>,
 873        try_provider: bool,
 874        cx: &AsyncApp,
 875    ) -> Result<Credentials> {
 876        let is_reauthenticating = if self.status().borrow().is_signed_out() {
 877            self.set_status(Status::Authenticating, cx);
 878            false
 879        } else {
 880            self.set_status(Status::Reauthenticating, cx);
 881            true
 882        };
 883
 884        let mut credentials = None;
 885
 886        let old_credentials = self.state.read().credentials.clone();
 887        if let Some(old_credentials) = old_credentials
 888            && self.validate_credentials(&old_credentials, cx).await?
 889        {
 890            credentials = Some(old_credentials);
 891        }
 892
 893        if credentials.is_none()
 894            && try_provider
 895            && let Some(stored_credentials) = self.credentials_provider.read_credentials(cx).await
 896        {
 897            if self.validate_credentials(&stored_credentials, cx).await? {
 898                credentials = Some(stored_credentials);
 899            } else {
 900                self.credentials_provider
 901                    .delete_credentials(cx)
 902                    .await
 903                    .log_err();
 904            }
 905        }
 906
 907        if credentials.is_none() {
 908            let mut status_rx = self.status();
 909            let _ = status_rx.next().await;
 910            futures::select_biased! {
 911                authenticate = self.authenticate(cx).fuse() => {
 912                    match authenticate {
 913                        Ok(creds) => {
 914                            if IMPERSONATE_LOGIN.is_none() {
 915                                self.credentials_provider
 916                                    .write_credentials(creds.user_id, creds.access_token.clone(), cx)
 917                                    .await
 918                                    .log_err();
 919                            }
 920
 921                            credentials = Some(creds);
 922                        },
 923                        Err(err) => {
 924                            self.set_status(Status::AuthenticationError, cx);
 925                            return Err(err);
 926                        }
 927                    }
 928                }
 929                _ = status_rx.next().fuse() => {
 930                    return Err(anyhow!("authentication canceled"));
 931                }
 932            }
 933        }
 934
 935        let credentials = credentials.unwrap();
 936        self.set_id(credentials.user_id);
 937        self.cloud_client
 938            .set_credentials(credentials.user_id as u32, credentials.access_token.clone());
 939        self.state.write().credentials = Some(credentials.clone());
 940        self.set_status(
 941            if is_reauthenticating {
 942                Status::Reauthenticated
 943            } else {
 944                Status::Authenticated
 945            },
 946            cx,
 947        );
 948
 949        Ok(credentials)
 950    }
 951
 952    async fn validate_credentials(
 953        self: &Arc<Self>,
 954        credentials: &Credentials,
 955        cx: &AsyncApp,
 956    ) -> Result<bool> {
 957        match self
 958            .cloud_client
 959            .validate_credentials(credentials.user_id as u32, &credentials.access_token)
 960            .await
 961        {
 962            Ok(valid) => Ok(valid),
 963            Err(err) => {
 964                self.set_status(Status::AuthenticationError, cx);
 965                Err(anyhow!("failed to validate credentials: {}", err))
 966            }
 967        }
 968    }
 969
 970    /// Establishes a WebSocket connection with Cloud for receiving updates from the server.
 971    async fn connect_to_cloud(self: &Arc<Self>, cx: &AsyncApp) -> Result<()> {
 972        let connect_task = cx.update({
 973            let cloud_client = self.cloud_client.clone();
 974            move |cx| cloud_client.connect(cx)
 975        })??;
 976        let connection = connect_task.await?;
 977
 978        let (mut messages, task) = cx.update(|cx| connection.spawn(cx))?;
 979        task.detach();
 980
 981        cx.spawn({
 982            let this = self.clone();
 983            async move |cx| {
 984                while let Some(message) = messages.next().await {
 985                    if let Some(message) = message.log_err() {
 986                        this.handle_message_to_client(message, cx);
 987                    }
 988                }
 989            }
 990        })
 991        .detach();
 992
 993        Ok(())
 994    }
 995
 996    /// Performs a sign-in and also (optionally) connects to Collab.
 997    ///
 998    /// Only Zed staff automatically connect to Collab.
 999    pub async fn sign_in_with_optional_connect(
1000        self: &Arc<Self>,
1001        try_provider: bool,
1002        cx: &AsyncApp,
1003    ) -> Result<()> {
1004        // Don't try to sign in again if we're already connected to Collab, as it will temporarily disconnect us.
1005        if self.status().borrow().is_connected() {
1006            return Ok(());
1007        }
1008
1009        let (is_staff_tx, is_staff_rx) = oneshot::channel::<bool>();
1010        let mut is_staff_tx = Some(is_staff_tx);
1011        cx.update(|cx| {
1012            cx.on_flags_ready(move |state, _cx| {
1013                if let Some(is_staff_tx) = is_staff_tx.take() {
1014                    is_staff_tx.send(state.is_staff).log_err();
1015                }
1016            })
1017            .detach();
1018        })
1019        .log_err();
1020
1021        let credentials = self.sign_in(try_provider, cx).await?;
1022
1023        self.connect_to_cloud(cx).await.log_err();
1024
1025        cx.update(move |cx| {
1026            cx.spawn({
1027                let client = self.clone();
1028                async move |cx| {
1029                    let is_staff = is_staff_rx.await?;
1030                    if is_staff {
1031                        match client.connect_with_credentials(credentials, cx).await {
1032                            ConnectionResult::Timeout => Err(anyhow!("connection timed out")),
1033                            ConnectionResult::ConnectionReset => Err(anyhow!("connection reset")),
1034                            ConnectionResult::Result(result) => {
1035                                result.context("client auth and connect")
1036                            }
1037                        }
1038                    } else {
1039                        Ok(())
1040                    }
1041                }
1042            })
1043            .detach_and_log_err(cx);
1044        })
1045        .log_err();
1046
1047        Ok(())
1048    }
1049
1050    pub async fn connect(
1051        self: &Arc<Self>,
1052        try_provider: bool,
1053        cx: &AsyncApp,
1054    ) -> ConnectionResult<()> {
1055        let was_disconnected = match *self.status().borrow() {
1056            Status::SignedOut | Status::Authenticated => true,
1057            Status::ConnectionError
1058            | Status::ConnectionLost
1059            | Status::Authenticating
1060            | Status::AuthenticationError
1061            | Status::Reauthenticating
1062            | Status::Reauthenticated
1063            | Status::ReconnectionError { .. } => false,
1064            Status::Connected { .. } | Status::Connecting | Status::Reconnecting => {
1065                return ConnectionResult::Result(Ok(()));
1066            }
1067            Status::UpgradeRequired => {
1068                return ConnectionResult::Result(
1069                    Err(EstablishConnectionError::UpgradeRequired)
1070                        .context("client auth and connect"),
1071                );
1072            }
1073        };
1074        let credentials = match self.sign_in(try_provider, cx).await {
1075            Ok(credentials) => credentials,
1076            Err(err) => return ConnectionResult::Result(Err(err)),
1077        };
1078
1079        if was_disconnected {
1080            self.set_status(Status::Connecting, cx);
1081        } else {
1082            self.set_status(Status::Reconnecting, cx);
1083        }
1084
1085        self.connect_with_credentials(credentials, cx).await
1086    }
1087
1088    async fn connect_with_credentials(
1089        self: &Arc<Self>,
1090        credentials: Credentials,
1091        cx: &AsyncApp,
1092    ) -> ConnectionResult<()> {
1093        let mut timeout =
1094            futures::FutureExt::fuse(cx.background_executor().timer(CONNECTION_TIMEOUT));
1095        futures::select_biased! {
1096            connection = self.establish_connection(&credentials, cx).fuse() => {
1097                match connection {
1098                    Ok(conn) => {
1099                        futures::select_biased! {
1100                            result = self.set_connection(conn, cx).fuse() => {
1101                                match result.context("client auth and connect") {
1102                                    Ok(()) => ConnectionResult::Result(Ok(())),
1103                                    Err(err) => {
1104                                        self.set_status(Status::ConnectionError, cx);
1105                                        ConnectionResult::Result(Err(err))
1106                                    },
1107                                }
1108                            },
1109                            _ = timeout => {
1110                                self.set_status(Status::ConnectionError, cx);
1111                                ConnectionResult::Timeout
1112                            }
1113                        }
1114                    }
1115                    Err(EstablishConnectionError::Unauthorized) => {
1116                        self.set_status(Status::ConnectionError, cx);
1117                        ConnectionResult::Result(Err(EstablishConnectionError::Unauthorized).context("client auth and connect"))
1118                    }
1119                    Err(EstablishConnectionError::UpgradeRequired) => {
1120                        self.set_status(Status::UpgradeRequired, cx);
1121                        ConnectionResult::Result(Err(EstablishConnectionError::UpgradeRequired).context("client auth and connect"))
1122                    }
1123                    Err(error) => {
1124                        self.set_status(Status::ConnectionError, cx);
1125                        ConnectionResult::Result(Err(error).context("client auth and connect"))
1126                    }
1127                }
1128            }
1129            _ = &mut timeout => {
1130                self.set_status(Status::ConnectionError, cx);
1131                ConnectionResult::Timeout
1132            }
1133        }
1134    }
1135
1136    async fn set_connection(self: &Arc<Self>, conn: Connection, cx: &AsyncApp) -> Result<()> {
1137        let executor = cx.background_executor();
1138        log::debug!("add connection to peer");
1139        let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn, {
1140            let executor = executor.clone();
1141            move |duration| executor.timer(duration)
1142        });
1143        let handle_io = executor.spawn(handle_io);
1144
1145        let peer_id = async {
1146            log::debug!("waiting for server hello");
1147            let message = incoming.next().await.context("no hello message received")?;
1148            log::debug!("got server hello");
1149            let hello_message_type_name = message.payload_type_name().to_string();
1150            let hello = message
1151                .into_any()
1152                .downcast::<TypedEnvelope<proto::Hello>>()
1153                .map_err(|_| {
1154                    anyhow!(
1155                        "invalid hello message received: {:?}",
1156                        hello_message_type_name
1157                    )
1158                })?;
1159            let peer_id = hello.payload.peer_id.context("invalid peer id")?;
1160            Ok(peer_id)
1161        };
1162
1163        let peer_id = match peer_id.await {
1164            Ok(peer_id) => peer_id,
1165            Err(error) => {
1166                self.peer.disconnect(connection_id);
1167                return Err(error);
1168            }
1169        };
1170
1171        log::debug!(
1172            "set status to connected (connection id: {:?}, peer id: {:?})",
1173            connection_id,
1174            peer_id
1175        );
1176        self.set_status(
1177            Status::Connected {
1178                peer_id,
1179                connection_id,
1180            },
1181            cx,
1182        );
1183
1184        cx.spawn({
1185            let this = self.clone();
1186            async move |cx| {
1187                while let Some(message) = incoming.next().await {
1188                    this.handle_message(message, cx);
1189                    // Don't starve the main thread when receiving lots of messages at once.
1190                    smol::future::yield_now().await;
1191                }
1192            }
1193        })
1194        .detach();
1195
1196        cx.spawn({
1197            let this = self.clone();
1198            async move |cx| match handle_io.await {
1199                Ok(()) => {
1200                    if *this.status().borrow()
1201                        == (Status::Connected {
1202                            connection_id,
1203                            peer_id,
1204                        })
1205                    {
1206                        this.set_status(Status::SignedOut, cx);
1207                    }
1208                }
1209                Err(err) => {
1210                    log::error!("connection error: {:?}", err);
1211                    this.set_status(Status::ConnectionLost, cx);
1212                }
1213            }
1214        })
1215        .detach();
1216
1217        Ok(())
1218    }
1219
1220    fn authenticate(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1221        #[cfg(any(test, feature = "test-support"))]
1222        if let Some(callback) = self.authenticate.read().as_ref() {
1223            return callback(cx);
1224        }
1225
1226        self.authenticate_with_browser(cx)
1227    }
1228
1229    fn establish_connection(
1230        self: &Arc<Self>,
1231        credentials: &Credentials,
1232        cx: &AsyncApp,
1233    ) -> Task<Result<Connection, EstablishConnectionError>> {
1234        #[cfg(any(test, feature = "test-support"))]
1235        if let Some(callback) = self.establish_connection.read().as_ref() {
1236            return callback(credentials, cx);
1237        }
1238
1239        self.establish_websocket_connection(credentials, cx)
1240    }
1241
1242    fn rpc_url(
1243        &self,
1244        http: Arc<HttpClientWithUrl>,
1245        release_channel: Option<ReleaseChannel>,
1246    ) -> impl Future<Output = Result<url::Url>> + use<> {
1247        #[cfg(any(test, feature = "test-support"))]
1248        let url_override = self.rpc_url.read().clone();
1249
1250        async move {
1251            #[cfg(any(test, feature = "test-support"))]
1252            if let Some(url) = url_override {
1253                return Ok(url);
1254            }
1255
1256            if let Some(url) = &*ZED_RPC_URL {
1257                return Url::parse(url).context("invalid rpc url");
1258            }
1259
1260            let mut url = http.build_url("/rpc");
1261            if let Some(preview_param) =
1262                release_channel.and_then(|channel| channel.release_query_param())
1263            {
1264                url += "?";
1265                url += preview_param;
1266            }
1267
1268            let response = http.get(&url, Default::default(), false).await?;
1269            anyhow::ensure!(
1270                response.status().is_redirection(),
1271                "unexpected /rpc response status {}",
1272                response.status()
1273            );
1274            let collab_url = response
1275                .headers()
1276                .get("Location")
1277                .context("missing location header in /rpc response")?
1278                .to_str()
1279                .map_err(EstablishConnectionError::other)?
1280                .to_string();
1281            Url::parse(&collab_url).with_context(|| format!("parsing collab rpc url {collab_url}"))
1282        }
1283    }
1284
1285    fn establish_websocket_connection(
1286        self: &Arc<Self>,
1287        credentials: &Credentials,
1288        cx: &AsyncApp,
1289    ) -> Task<Result<Connection, EstablishConnectionError>> {
1290        let release_channel = cx
1291            .update(|cx| ReleaseChannel::try_global(cx))
1292            .ok()
1293            .flatten();
1294        let app_version = cx
1295            .update(|cx| AppVersion::global(cx).to_string())
1296            .ok()
1297            .unwrap_or_default();
1298
1299        let http = self.http.clone();
1300        let proxy = http.proxy().cloned();
1301        let user_agent = http.user_agent().cloned();
1302        let credentials = credentials.clone();
1303        let rpc_url = self.rpc_url(http, release_channel);
1304        let system_id = self.telemetry.system_id();
1305        let metrics_id = self.telemetry.metrics_id();
1306        cx.spawn(async move |cx| {
1307            use HttpOrHttps::*;
1308
1309            #[derive(Debug)]
1310            enum HttpOrHttps {
1311                Http,
1312                Https,
1313            }
1314
1315            let mut rpc_url = rpc_url.await?;
1316            let url_scheme = match rpc_url.scheme() {
1317                "https" => Https,
1318                "http" => Http,
1319                _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1320            };
1321
1322            let stream = gpui_tokio::Tokio::spawn_result(cx, {
1323                let rpc_url = rpc_url.clone();
1324                async move {
1325                    let rpc_host = rpc_url
1326                        .host_str()
1327                        .zip(rpc_url.port_or_known_default())
1328                        .context("missing host in rpc url")?;
1329                    Ok(match proxy {
1330                        Some(proxy) => connect_proxy_stream(&proxy, rpc_host).await?,
1331                        None => Box::new(TcpStream::connect(rpc_host).await?),
1332                    })
1333                }
1334            })?
1335            .await?;
1336
1337            log::info!("connected to rpc endpoint {}", rpc_url);
1338
1339            rpc_url
1340                .set_scheme(match url_scheme {
1341                    Https => "wss",
1342                    Http => "ws",
1343                })
1344                .unwrap();
1345
1346            // We call `into_client_request` to let `tungstenite` construct the WebSocket request
1347            // for us from the RPC URL.
1348            //
1349            // Among other things, it will generate and set a `Sec-WebSocket-Key` header for us.
1350            let mut request = IntoClientRequest::into_client_request(rpc_url.as_str())?;
1351
1352            // We then modify the request to add our desired headers.
1353            let request_headers = request.headers_mut();
1354            request_headers.insert(
1355                http::header::AUTHORIZATION,
1356                HeaderValue::from_str(&credentials.authorization_header())?,
1357            );
1358            request_headers.insert(
1359                "x-zed-protocol-version",
1360                HeaderValue::from_str(&rpc::PROTOCOL_VERSION.to_string())?,
1361            );
1362            request_headers.insert("x-zed-app-version", HeaderValue::from_str(&app_version)?);
1363            request_headers.insert(
1364                "x-zed-release-channel",
1365                HeaderValue::from_str(release_channel.map(|r| r.dev_name()).unwrap_or("unknown"))?,
1366            );
1367            if let Some(user_agent) = user_agent {
1368                request_headers.insert(http::header::USER_AGENT, user_agent);
1369            }
1370            if let Some(system_id) = system_id {
1371                request_headers.insert("x-zed-system-id", HeaderValue::from_str(&system_id)?);
1372            }
1373            if let Some(metrics_id) = metrics_id {
1374                request_headers.insert("x-zed-metrics-id", HeaderValue::from_str(&metrics_id)?);
1375            }
1376
1377            let (stream, _) = async_tungstenite::tokio::client_async_tls_with_connector_and_config(
1378                request,
1379                stream,
1380                Some(Arc::new(http_client_tls::tls_config()).into()),
1381                None,
1382            )
1383            .await?;
1384
1385            Ok(Connection::new(
1386                stream
1387                    .map_err(|error| anyhow!(error))
1388                    .sink_map_err(|error| anyhow!(error)),
1389            ))
1390        })
1391    }
1392
1393    pub fn authenticate_with_browser(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1394        let http = self.http.clone();
1395        let this = self.clone();
1396        cx.spawn(async move |cx| {
1397            let background = cx.background_executor().clone();
1398
1399            let (open_url_tx, open_url_rx) = oneshot::channel::<String>();
1400            cx.update(|cx| {
1401                cx.spawn(async move |cx| {
1402                    let url = open_url_rx.await?;
1403                    cx.update(|cx| cx.open_url(&url))
1404                })
1405                .detach_and_log_err(cx);
1406            })
1407            .log_err();
1408
1409            let credentials = background
1410                .clone()
1411                .spawn(async move {
1412                    // Generate a pair of asymmetric encryption keys. The public key will be used by the
1413                    // zed server to encrypt the user's access token, so that it can'be intercepted by
1414                    // any other app running on the user's device.
1415                    let (public_key, private_key) =
1416                        rpc::auth::keypair().expect("failed to generate keypair for auth");
1417                    let public_key_string = String::try_from(public_key)
1418                        .expect("failed to serialize public key for auth");
1419
1420                    if let Some((login, token)) =
1421                        IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref())
1422                    {
1423                        if !*USE_WEB_LOGIN {
1424                            eprintln!("authenticate as admin {login}, {token}");
1425
1426                            return this
1427                                .authenticate_as_admin(http, login.clone(), token.clone())
1428                                .await;
1429                        }
1430                    }
1431
1432                    // Start an HTTP server to receive the redirect from Zed's sign-in page.
1433                    let server =
1434                        tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1435                    let port = server.server_addr().port();
1436
1437                    // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1438                    // that the user is signing in from a Zed app running on the same device.
1439                    let mut url = http.build_url(&format!(
1440                        "/native_app_signin?native_app_port={}&native_app_public_key={}",
1441                        port, public_key_string
1442                    ));
1443
1444                    if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1445                        log::info!("impersonating user @{}", impersonate_login);
1446                        write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1447                    }
1448
1449                    open_url_tx.send(url).log_err();
1450
1451                    #[derive(Deserialize)]
1452                    struct CallbackParams {
1453                        pub user_id: String,
1454                        pub access_token: String,
1455                    }
1456
1457                    // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1458                    // access token from the query params.
1459                    //
1460                    // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1461                    // custom URL scheme instead of this local HTTP server.
1462                    let (user_id, access_token) = background
1463                        .spawn(async move {
1464                            for _ in 0..100 {
1465                                if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1466                                    let path = req.url();
1467                                    let url = Url::parse(&format!("http://example.com{}", path))
1468                                        .context("failed to parse login notification url")?;
1469                                    let callback_params: CallbackParams =
1470                                        serde_urlencoded::from_str(url.query().unwrap_or_default())
1471                                            .context(
1472                                                "failed to parse sign-in callback query parameters",
1473                                            )?;
1474
1475                                    let post_auth_url =
1476                                        http.build_url("/native_app_signin_succeeded");
1477                                    req.respond(
1478                                        tiny_http::Response::empty(302).with_header(
1479                                            tiny_http::Header::from_bytes(
1480                                                &b"Location"[..],
1481                                                post_auth_url.as_bytes(),
1482                                            )
1483                                            .unwrap(),
1484                                        ),
1485                                    )
1486                                    .context("failed to respond to login http request")?;
1487                                    return Ok((
1488                                        callback_params.user_id,
1489                                        callback_params.access_token,
1490                                    ));
1491                                }
1492                            }
1493
1494                            anyhow::bail!("didn't receive login redirect");
1495                        })
1496                        .await?;
1497
1498                    let access_token = private_key
1499                        .decrypt_string(&access_token)
1500                        .context("failed to decrypt access token")?;
1501
1502                    Ok(Credentials {
1503                        user_id: user_id.parse()?,
1504                        access_token,
1505                    })
1506                })
1507                .await?;
1508
1509            cx.update(|cx| cx.activate(true))?;
1510            Ok(credentials)
1511        })
1512    }
1513
1514    async fn authenticate_as_admin(
1515        self: &Arc<Self>,
1516        http: Arc<HttpClientWithUrl>,
1517        login: String,
1518        api_token: String,
1519    ) -> Result<Credentials> {
1520        #[derive(Serialize)]
1521        struct ImpersonateUserBody {
1522            github_login: String,
1523        }
1524
1525        #[derive(Deserialize)]
1526        struct ImpersonateUserResponse {
1527            user_id: u64,
1528            access_token: String,
1529        }
1530
1531        let url = self
1532            .http
1533            .build_zed_cloud_url("/internal/users/impersonate", &[])?;
1534        let request = Request::post(url.as_str())
1535            .header("Content-Type", "application/json")
1536            .header("Authorization", format!("Bearer {api_token}"))
1537            .body(
1538                serde_json::to_string(&ImpersonateUserBody {
1539                    github_login: login,
1540                })?
1541                .into(),
1542            )?;
1543
1544        let mut response = http.send(request).await?;
1545        let mut body = String::new();
1546        response.body_mut().read_to_string(&mut body).await?;
1547        anyhow::ensure!(
1548            response.status().is_success(),
1549            "admin user request failed {} - {}",
1550            response.status().as_u16(),
1551            body,
1552        );
1553        let response: ImpersonateUserResponse = serde_json::from_str(&body)?;
1554
1555        Ok(Credentials {
1556            user_id: response.user_id,
1557            access_token: response.access_token,
1558        })
1559    }
1560
1561    pub async fn sign_out(self: &Arc<Self>, cx: &AsyncApp) {
1562        self.state.write().credentials = None;
1563        self.cloud_client.clear_credentials();
1564        self.disconnect(cx);
1565
1566        if self.has_credentials(cx).await {
1567            self.credentials_provider
1568                .delete_credentials(cx)
1569                .await
1570                .log_err();
1571        }
1572    }
1573
1574    pub fn disconnect(self: &Arc<Self>, cx: &AsyncApp) {
1575        self.peer.teardown();
1576        self.set_status(Status::SignedOut, cx);
1577    }
1578
1579    pub fn reconnect(self: &Arc<Self>, cx: &AsyncApp) {
1580        self.peer.teardown();
1581        self.set_status(Status::ConnectionLost, cx);
1582    }
1583
1584    fn connection_id(&self) -> Result<ConnectionId> {
1585        if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1586            Ok(connection_id)
1587        } else {
1588            anyhow::bail!("not connected");
1589        }
1590    }
1591
1592    pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1593        log::debug!("rpc send. client_id:{}, name:{}", self.id(), T::NAME);
1594        self.peer.send(self.connection_id()?, message)
1595    }
1596
1597    pub fn request<T: RequestMessage>(
1598        &self,
1599        request: T,
1600    ) -> impl Future<Output = Result<T::Response>> + use<T> {
1601        self.request_envelope(request)
1602            .map_ok(|envelope| envelope.payload)
1603    }
1604
1605    pub fn request_stream<T: RequestMessage>(
1606        &self,
1607        request: T,
1608    ) -> impl Future<Output = Result<impl Stream<Item = Result<T::Response>>>> {
1609        let client_id = self.id.load(Ordering::SeqCst);
1610        log::debug!(
1611            "rpc request start. client_id:{}. name:{}",
1612            client_id,
1613            T::NAME
1614        );
1615        let response = self
1616            .connection_id()
1617            .map(|conn_id| self.peer.request_stream(conn_id, request));
1618        async move {
1619            let response = response?.await;
1620            log::debug!(
1621                "rpc request finish. client_id:{}. name:{}",
1622                client_id,
1623                T::NAME
1624            );
1625            response
1626        }
1627    }
1628
1629    pub fn request_envelope<T: RequestMessage>(
1630        &self,
1631        request: T,
1632    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> + use<T> {
1633        let client_id = self.id();
1634        log::debug!(
1635            "rpc request start. client_id:{}. name:{}",
1636            client_id,
1637            T::NAME
1638        );
1639        let response = self
1640            .connection_id()
1641            .map(|conn_id| self.peer.request_envelope(conn_id, request));
1642        async move {
1643            let response = response?.await;
1644            log::debug!(
1645                "rpc request finish. client_id:{}. name:{}",
1646                client_id,
1647                T::NAME
1648            );
1649            response
1650        }
1651    }
1652
1653    pub fn request_dynamic(
1654        &self,
1655        envelope: proto::Envelope,
1656        request_type: &'static str,
1657    ) -> impl Future<Output = Result<proto::Envelope>> + use<> {
1658        let client_id = self.id();
1659        log::debug!(
1660            "rpc request start. client_id:{}. name:{}",
1661            client_id,
1662            request_type
1663        );
1664        let response = self
1665            .connection_id()
1666            .map(|conn_id| self.peer.request_dynamic(conn_id, envelope, request_type));
1667        async move {
1668            let response = response?.await;
1669            log::debug!(
1670                "rpc request finish. client_id:{}. name:{}",
1671                client_id,
1672                request_type
1673            );
1674            Ok(response?.0)
1675        }
1676    }
1677
1678    fn handle_message(self: &Arc<Client>, message: Box<dyn AnyTypedEnvelope>, cx: &AsyncApp) {
1679        let sender_id = message.sender_id();
1680        let request_id = message.message_id();
1681        let type_name = message.payload_type_name();
1682        let original_sender_id = message.original_sender_id();
1683
1684        if let Some(future) = ProtoMessageHandlerSet::handle_message(
1685            &self.handler_set,
1686            message,
1687            self.clone().into(),
1688            cx.clone(),
1689        ) {
1690            let client_id = self.id();
1691            log::debug!(
1692                "rpc message received. client_id:{}, sender_id:{:?}, type:{}",
1693                client_id,
1694                original_sender_id,
1695                type_name
1696            );
1697            cx.spawn(async move |_| match future.await {
1698                Ok(()) => {
1699                    log::debug!("rpc message handled. client_id:{client_id}, sender_id:{original_sender_id:?}, type:{type_name}");
1700                }
1701                Err(error) => {
1702                    log::error!("error handling message. client_id:{client_id}, sender_id:{original_sender_id:?}, type:{type_name}, error:{error:#}");
1703                }
1704            })
1705            .detach();
1706        } else {
1707            log::info!("unhandled message {}", type_name);
1708            self.peer
1709                .respond_with_unhandled_message(sender_id.into(), request_id, type_name)
1710                .log_err();
1711        }
1712    }
1713
1714    pub fn add_message_to_client_handler(
1715        self: &Arc<Client>,
1716        handler: impl Fn(&MessageToClient, &mut App) + Send + Sync + 'static,
1717    ) {
1718        self.message_to_client_handlers
1719            .lock()
1720            .push(Box::new(handler));
1721    }
1722
1723    fn handle_message_to_client(self: &Arc<Client>, message: MessageToClient, cx: &AsyncApp) {
1724        cx.update(|cx| {
1725            for handler in self.message_to_client_handlers.lock().iter() {
1726                handler(&message, cx);
1727            }
1728        })
1729        .ok();
1730    }
1731
1732    pub fn telemetry(&self) -> &Arc<Telemetry> {
1733        &self.telemetry
1734    }
1735}
1736
1737impl ProtoClient for Client {
1738    fn request(
1739        &self,
1740        envelope: proto::Envelope,
1741        request_type: &'static str,
1742    ) -> BoxFuture<'static, Result<proto::Envelope>> {
1743        self.request_dynamic(envelope, request_type).boxed()
1744    }
1745
1746    fn send(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1747        log::debug!("rpc send. client_id:{}, name:{}", self.id(), message_type);
1748        let connection_id = self.connection_id()?;
1749        self.peer.send_dynamic(connection_id, envelope)
1750    }
1751
1752    fn send_response(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1753        log::debug!(
1754            "rpc respond. client_id:{}, name:{}",
1755            self.id(),
1756            message_type
1757        );
1758        let connection_id = self.connection_id()?;
1759        self.peer.send_dynamic(connection_id, envelope)
1760    }
1761
1762    fn message_handler_set(&self) -> &parking_lot::Mutex<ProtoMessageHandlerSet> {
1763        &self.handler_set
1764    }
1765
1766    fn is_via_collab(&self) -> bool {
1767        true
1768    }
1769}
1770
1771/// prefix for the zed:// url scheme
1772pub const ZED_URL_SCHEME: &str = "zed";
1773
1774/// Parses the given link into a Zed link.
1775///
1776/// Returns a [`Some`] containing the unprefixed link if the link is a Zed link.
1777/// Returns [`None`] otherwise.
1778pub fn parse_zed_link<'a>(link: &'a str, cx: &App) -> Option<&'a str> {
1779    let server_url = &ClientSettings::get_global(cx).server_url;
1780    if let Some(stripped) = link
1781        .strip_prefix(server_url)
1782        .and_then(|result| result.strip_prefix('/'))
1783    {
1784        return Some(stripped);
1785    }
1786    if let Some(stripped) = link
1787        .strip_prefix(ZED_URL_SCHEME)
1788        .and_then(|result| result.strip_prefix("://"))
1789    {
1790        return Some(stripped);
1791    }
1792
1793    None
1794}
1795
1796#[cfg(test)]
1797mod tests {
1798    use super::*;
1799    use crate::test::{FakeServer, parse_authorization_header};
1800
1801    use clock::FakeSystemClock;
1802    use gpui::{AppContext as _, BackgroundExecutor, TestAppContext};
1803    use http_client::FakeHttpClient;
1804    use parking_lot::Mutex;
1805    use proto::TypedEnvelope;
1806    use settings::SettingsStore;
1807    use std::future;
1808
1809    #[gpui::test(iterations = 10)]
1810    async fn test_reconnection(cx: &mut TestAppContext) {
1811        init_test(cx);
1812        let user_id = 5;
1813        let client = cx.update(|cx| {
1814            Client::new(
1815                Arc::new(FakeSystemClock::new()),
1816                FakeHttpClient::with_404_response(),
1817                cx,
1818            )
1819        });
1820        let server = FakeServer::for_client(user_id, &client, cx).await;
1821        let mut status = client.status();
1822        assert!(matches!(
1823            status.next().await,
1824            Some(Status::Connected { .. })
1825        ));
1826        assert_eq!(server.auth_count(), 1);
1827
1828        server.forbid_connections();
1829        server.disconnect();
1830        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1831
1832        server.allow_connections();
1833        cx.executor().advance_clock(Duration::from_secs(10));
1834        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1835        assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1836
1837        server.forbid_connections();
1838        server.disconnect();
1839        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1840
1841        // Clear cached credentials after authentication fails
1842        server.roll_access_token();
1843        server.allow_connections();
1844        cx.executor().run_until_parked();
1845        cx.executor().advance_clock(Duration::from_secs(10));
1846        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1847        assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1848    }
1849
1850    #[gpui::test(iterations = 10)]
1851    async fn test_auth_failure_during_reconnection(cx: &mut TestAppContext) {
1852        init_test(cx);
1853        let http_client = FakeHttpClient::with_200_response();
1854        let client =
1855            cx.update(|cx| Client::new(Arc::new(FakeSystemClock::new()), http_client.clone(), cx));
1856        let server = FakeServer::for_client(42, &client, cx).await;
1857        let mut status = client.status();
1858        assert!(matches!(
1859            status.next().await,
1860            Some(Status::Connected { .. })
1861        ));
1862        assert_eq!(server.auth_count(), 1);
1863
1864        // Simulate an auth failure during reconnection.
1865        http_client
1866            .as_fake()
1867            .replace_handler(|_, _request| async move {
1868                Ok(http_client::Response::builder()
1869                    .status(503)
1870                    .body("".into())
1871                    .unwrap())
1872            });
1873        server.disconnect();
1874        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1875
1876        // Restore the ability to authenticate.
1877        http_client
1878            .as_fake()
1879            .replace_handler(|_, _request| async move {
1880                Ok(http_client::Response::builder()
1881                    .status(200)
1882                    .body("".into())
1883                    .unwrap())
1884            });
1885        cx.executor().advance_clock(Duration::from_secs(10));
1886        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1887        assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1888    }
1889
1890    #[gpui::test(iterations = 10)]
1891    async fn test_connection_timeout(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1892        init_test(cx);
1893        let user_id = 5;
1894        let client = cx.update(|cx| {
1895            Client::new(
1896                Arc::new(FakeSystemClock::new()),
1897                FakeHttpClient::with_404_response(),
1898                cx,
1899            )
1900        });
1901        let mut status = client.status();
1902
1903        // Time out when client tries to connect.
1904        client.override_authenticate(move |cx| {
1905            cx.background_spawn(async move {
1906                Ok(Credentials {
1907                    user_id,
1908                    access_token: "token".into(),
1909                })
1910            })
1911        });
1912        client.override_establish_connection(|_, cx| {
1913            cx.background_spawn(async move {
1914                future::pending::<()>().await;
1915                unreachable!()
1916            })
1917        });
1918        let auth_and_connect = cx.spawn({
1919            let client = client.clone();
1920            |cx| async move { client.connect(false, &cx).await }
1921        });
1922        executor.run_until_parked();
1923        assert!(matches!(status.next().await, Some(Status::Connecting)));
1924
1925        executor.advance_clock(CONNECTION_TIMEOUT);
1926        assert!(matches!(status.next().await, Some(Status::ConnectionError)));
1927        auth_and_connect.await.into_response().unwrap_err();
1928
1929        // Allow the connection to be established.
1930        let server = FakeServer::for_client(user_id, &client, cx).await;
1931        assert!(matches!(
1932            status.next().await,
1933            Some(Status::Connected { .. })
1934        ));
1935
1936        // Disconnect client.
1937        server.forbid_connections();
1938        server.disconnect();
1939        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1940
1941        // Time out when re-establishing the connection.
1942        server.allow_connections();
1943        client.override_establish_connection(|_, cx| {
1944            cx.background_spawn(async move {
1945                future::pending::<()>().await;
1946                unreachable!()
1947            })
1948        });
1949        executor.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1950        assert!(matches!(status.next().await, Some(Status::Reconnecting)));
1951
1952        executor.advance_clock(CONNECTION_TIMEOUT);
1953        assert!(matches!(
1954            status.next().await,
1955            Some(Status::ReconnectionError { .. })
1956        ));
1957    }
1958
1959    #[gpui::test(iterations = 10)]
1960    async fn test_reauthenticate_only_if_unauthorized(cx: &mut TestAppContext) {
1961        init_test(cx);
1962        let auth_count = Arc::new(Mutex::new(0));
1963        let http_client = FakeHttpClient::create(|_request| async move {
1964            Ok(http_client::Response::builder()
1965                .status(200)
1966                .body("".into())
1967                .unwrap())
1968        });
1969        let client =
1970            cx.update(|cx| Client::new(Arc::new(FakeSystemClock::new()), http_client.clone(), cx));
1971        client.override_authenticate({
1972            let auth_count = auth_count.clone();
1973            move |cx| {
1974                let auth_count = auth_count.clone();
1975                cx.background_spawn(async move {
1976                    *auth_count.lock() += 1;
1977                    Ok(Credentials {
1978                        user_id: 1,
1979                        access_token: auth_count.lock().to_string(),
1980                    })
1981                })
1982            }
1983        });
1984
1985        let credentials = client.sign_in(false, &cx.to_async()).await.unwrap();
1986        assert_eq!(*auth_count.lock(), 1);
1987        assert_eq!(credentials.access_token, "1");
1988
1989        // If credentials are still valid, signing in doesn't trigger authentication.
1990        let credentials = client.sign_in(false, &cx.to_async()).await.unwrap();
1991        assert_eq!(*auth_count.lock(), 1);
1992        assert_eq!(credentials.access_token, "1");
1993
1994        // If the server is unavailable, signing in doesn't trigger authentication.
1995        http_client
1996            .as_fake()
1997            .replace_handler(|_, _request| async move {
1998                Ok(http_client::Response::builder()
1999                    .status(503)
2000                    .body("".into())
2001                    .unwrap())
2002            });
2003        client.sign_in(false, &cx.to_async()).await.unwrap_err();
2004        assert_eq!(*auth_count.lock(), 1);
2005
2006        // If credentials became invalid, signing in triggers authentication.
2007        http_client
2008            .as_fake()
2009            .replace_handler(|_, request| async move {
2010                let credentials = parse_authorization_header(&request).unwrap();
2011                if credentials.access_token == "2" {
2012                    Ok(http_client::Response::builder()
2013                        .status(200)
2014                        .body("".into())
2015                        .unwrap())
2016                } else {
2017                    Ok(http_client::Response::builder()
2018                        .status(401)
2019                        .body("".into())
2020                        .unwrap())
2021                }
2022            });
2023        let credentials = client.sign_in(false, &cx.to_async()).await.unwrap();
2024        assert_eq!(*auth_count.lock(), 2);
2025        assert_eq!(credentials.access_token, "2");
2026    }
2027
2028    #[gpui::test(iterations = 10)]
2029    async fn test_authenticating_more_than_once(
2030        cx: &mut TestAppContext,
2031        executor: BackgroundExecutor,
2032    ) {
2033        init_test(cx);
2034        let auth_count = Arc::new(Mutex::new(0));
2035        let dropped_auth_count = Arc::new(Mutex::new(0));
2036        let client = cx.update(|cx| {
2037            Client::new(
2038                Arc::new(FakeSystemClock::new()),
2039                FakeHttpClient::with_404_response(),
2040                cx,
2041            )
2042        });
2043        client.override_authenticate({
2044            let auth_count = auth_count.clone();
2045            let dropped_auth_count = dropped_auth_count.clone();
2046            move |cx| {
2047                let auth_count = auth_count.clone();
2048                let dropped_auth_count = dropped_auth_count.clone();
2049                cx.background_spawn(async move {
2050                    *auth_count.lock() += 1;
2051                    let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
2052                    future::pending::<()>().await;
2053                    unreachable!()
2054                })
2055            }
2056        });
2057
2058        let _authenticate = cx.spawn({
2059            let client = client.clone();
2060            move |cx| async move { client.connect(false, &cx).await }
2061        });
2062        executor.run_until_parked();
2063        assert_eq!(*auth_count.lock(), 1);
2064        assert_eq!(*dropped_auth_count.lock(), 0);
2065
2066        let _authenticate = cx.spawn(|cx| async move { client.connect(false, &cx).await });
2067        executor.run_until_parked();
2068        assert_eq!(*auth_count.lock(), 2);
2069        assert_eq!(*dropped_auth_count.lock(), 1);
2070    }
2071
2072    #[gpui::test]
2073    async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
2074        init_test(cx);
2075        let user_id = 5;
2076        let client = cx.update(|cx| {
2077            Client::new(
2078                Arc::new(FakeSystemClock::new()),
2079                FakeHttpClient::with_404_response(),
2080                cx,
2081            )
2082        });
2083        let server = FakeServer::for_client(user_id, &client, cx).await;
2084
2085        let (done_tx1, done_rx1) = smol::channel::unbounded();
2086        let (done_tx2, done_rx2) = smol::channel::unbounded();
2087        AnyProtoClient::from(client.clone()).add_entity_message_handler(
2088            move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::JoinProject>, cx| {
2089                match entity.read_with(&cx, |entity, _| entity.id).unwrap() {
2090                    1 => done_tx1.try_send(()).unwrap(),
2091                    2 => done_tx2.try_send(()).unwrap(),
2092                    _ => unreachable!(),
2093                }
2094                async { Ok(()) }
2095            },
2096        );
2097        let entity1 = cx.new(|_| TestEntity {
2098            id: 1,
2099            subscription: None,
2100        });
2101        let entity2 = cx.new(|_| TestEntity {
2102            id: 2,
2103            subscription: None,
2104        });
2105        let entity3 = cx.new(|_| TestEntity {
2106            id: 3,
2107            subscription: None,
2108        });
2109
2110        let _subscription1 = client
2111            .subscribe_to_entity(1)
2112            .unwrap()
2113            .set_entity(&entity1, &cx.to_async());
2114        let _subscription2 = client
2115            .subscribe_to_entity(2)
2116            .unwrap()
2117            .set_entity(&entity2, &cx.to_async());
2118        // Ensure dropping a subscription for the same entity type still allows receiving of
2119        // messages for other entity IDs of the same type.
2120        let subscription3 = client
2121            .subscribe_to_entity(3)
2122            .unwrap()
2123            .set_entity(&entity3, &cx.to_async());
2124        drop(subscription3);
2125
2126        server.send(proto::JoinProject {
2127            project_id: 1,
2128            committer_name: None,
2129            committer_email: None,
2130        });
2131        server.send(proto::JoinProject {
2132            project_id: 2,
2133            committer_name: None,
2134            committer_email: None,
2135        });
2136        done_rx1.recv().await.unwrap();
2137        done_rx2.recv().await.unwrap();
2138    }
2139
2140    #[gpui::test]
2141    async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
2142        init_test(cx);
2143        let user_id = 5;
2144        let client = cx.update(|cx| {
2145            Client::new(
2146                Arc::new(FakeSystemClock::new()),
2147                FakeHttpClient::with_404_response(),
2148                cx,
2149            )
2150        });
2151        let server = FakeServer::for_client(user_id, &client, cx).await;
2152
2153        let entity = cx.new(|_| TestEntity::default());
2154        let (done_tx1, _done_rx1) = smol::channel::unbounded();
2155        let (done_tx2, done_rx2) = smol::channel::unbounded();
2156        let subscription1 = client.add_message_handler(
2157            entity.downgrade(),
2158            move |_, _: TypedEnvelope<proto::Ping>, _| {
2159                done_tx1.try_send(()).unwrap();
2160                async { Ok(()) }
2161            },
2162        );
2163        drop(subscription1);
2164        let _subscription2 = client.add_message_handler(
2165            entity.downgrade(),
2166            move |_, _: TypedEnvelope<proto::Ping>, _| {
2167                done_tx2.try_send(()).unwrap();
2168                async { Ok(()) }
2169            },
2170        );
2171        server.send(proto::Ping {});
2172        done_rx2.recv().await.unwrap();
2173    }
2174
2175    #[gpui::test]
2176    async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
2177        init_test(cx);
2178        let user_id = 5;
2179        let client = cx.update(|cx| {
2180            Client::new(
2181                Arc::new(FakeSystemClock::new()),
2182                FakeHttpClient::with_404_response(),
2183                cx,
2184            )
2185        });
2186        let server = FakeServer::for_client(user_id, &client, cx).await;
2187
2188        let entity = cx.new(|_| TestEntity::default());
2189        let (done_tx, done_rx) = smol::channel::unbounded();
2190        let subscription = client.add_message_handler(
2191            entity.clone().downgrade(),
2192            move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::Ping>, mut cx| {
2193                entity
2194                    .update(&mut cx, |entity, _| entity.subscription.take())
2195                    .unwrap();
2196                done_tx.try_send(()).unwrap();
2197                async { Ok(()) }
2198            },
2199        );
2200        entity.update(cx, |entity, _| {
2201            entity.subscription = Some(subscription);
2202        });
2203        server.send(proto::Ping {});
2204        done_rx.recv().await.unwrap();
2205    }
2206
2207    #[derive(Default)]
2208    struct TestEntity {
2209        id: usize,
2210        subscription: Option<Subscription>,
2211    }
2212
2213    fn init_test(cx: &mut TestAppContext) {
2214        cx.update(|cx| {
2215            let settings_store = SettingsStore::test(cx);
2216            cx.set_global(settings_store);
2217            init_settings(cx);
2218        });
2219    }
2220}