client.rs

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