client.rs

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