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(async move |cx| {
 148                    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(async move |cx| {
 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(async move |cx| {
 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(async move |cx| {
 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            async move |cx| {
 968                while let Some(message) = incoming.next().await {
 969                    this.handle_message(message, &cx);
 970                    // Don't starve the main thread when receiving lots of messages at once.
 971                    smol::future::yield_now().await;
 972                }
 973            }
 974        })
 975        .detach();
 976
 977        cx.spawn({
 978            let this = self.clone();
 979            async move |cx| match handle_io.await {
 980                Ok(()) => {
 981                    if *this.status().borrow()
 982                        == (Status::Connected {
 983                            connection_id,
 984                            peer_id,
 985                        })
 986                    {
 987                        this.set_status(Status::SignedOut, &cx);
 988                    }
 989                }
 990                Err(err) => {
 991                    log::error!("connection error: {:?}", err);
 992                    this.set_status(Status::ConnectionLost, &cx);
 993                }
 994            }
 995        })
 996        .detach();
 997
 998        Ok(())
 999    }
1000
1001    fn authenticate(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1002        #[cfg(any(test, feature = "test-support"))]
1003        if let Some(callback) = self.authenticate.read().as_ref() {
1004            return callback(cx);
1005        }
1006
1007        self.authenticate_with_browser(cx)
1008    }
1009
1010    fn establish_connection(
1011        self: &Arc<Self>,
1012        credentials: &Credentials,
1013        cx: &AsyncApp,
1014    ) -> Task<Result<Connection, EstablishConnectionError>> {
1015        #[cfg(any(test, feature = "test-support"))]
1016        if let Some(callback) = self.establish_connection.read().as_ref() {
1017            return callback(credentials, cx);
1018        }
1019
1020        self.establish_websocket_connection(credentials, cx)
1021    }
1022
1023    fn rpc_url(
1024        &self,
1025        http: Arc<HttpClientWithUrl>,
1026        release_channel: Option<ReleaseChannel>,
1027    ) -> impl Future<Output = Result<url::Url>> + use<> {
1028        #[cfg(any(test, feature = "test-support"))]
1029        let url_override = self.rpc_url.read().clone();
1030
1031        async move {
1032            #[cfg(any(test, feature = "test-support"))]
1033            if let Some(url) = url_override {
1034                return Ok(url);
1035            }
1036
1037            if let Some(url) = &*ZED_RPC_URL {
1038                return Url::parse(url).context("invalid rpc url");
1039            }
1040
1041            let mut url = http.build_url("/rpc");
1042            if let Some(preview_param) =
1043                release_channel.and_then(|channel| channel.release_query_param())
1044            {
1045                url += "?";
1046                url += preview_param;
1047            }
1048
1049            let response = http.get(&url, Default::default(), false).await?;
1050            let collab_url = if response.status().is_redirection() {
1051                response
1052                    .headers()
1053                    .get("Location")
1054                    .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
1055                    .to_str()
1056                    .map_err(EstablishConnectionError::other)?
1057                    .to_string()
1058            } else {
1059                Err(anyhow!(
1060                    "unexpected /rpc response status {}",
1061                    response.status()
1062                ))?
1063            };
1064
1065            Url::parse(&collab_url).context("invalid rpc url")
1066        }
1067    }
1068
1069    fn establish_websocket_connection(
1070        self: &Arc<Self>,
1071        credentials: &Credentials,
1072        cx: &AsyncApp,
1073    ) -> Task<Result<Connection, EstablishConnectionError>> {
1074        let release_channel = cx
1075            .update(|cx| ReleaseChannel::try_global(cx))
1076            .ok()
1077            .flatten();
1078        let app_version = cx
1079            .update(|cx| AppVersion::global(cx).to_string())
1080            .ok()
1081            .unwrap_or_default();
1082
1083        let http = self.http.clone();
1084        let proxy = http.proxy().cloned();
1085        let credentials = credentials.clone();
1086        let rpc_url = self.rpc_url(http, release_channel);
1087        let system_id = self.telemetry.system_id();
1088        let metrics_id = self.telemetry.metrics_id();
1089        cx.background_spawn(async move {
1090            use HttpOrHttps::*;
1091
1092            #[derive(Debug)]
1093            enum HttpOrHttps {
1094                Http,
1095                Https,
1096            }
1097
1098            let mut rpc_url = rpc_url.await?;
1099            let url_scheme = match rpc_url.scheme() {
1100                "https" => Https,
1101                "http" => Http,
1102                _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1103            };
1104            let rpc_host = rpc_url
1105                .host_str()
1106                .zip(rpc_url.port_or_known_default())
1107                .ok_or_else(|| anyhow!("missing host in rpc url"))?;
1108            let stream = connect_socks_proxy_stream(proxy.as_ref(), rpc_host).await?;
1109
1110            log::info!("connected to rpc endpoint {}", rpc_url);
1111
1112            rpc_url
1113                .set_scheme(match url_scheme {
1114                    Https => "wss",
1115                    Http => "ws",
1116                })
1117                .unwrap();
1118
1119            // We call `into_client_request` to let `tungstenite` construct the WebSocket request
1120            // for us from the RPC URL.
1121            //
1122            // Among other things, it will generate and set a `Sec-WebSocket-Key` header for us.
1123            let mut request = IntoClientRequest::into_client_request(rpc_url.as_str())?;
1124
1125            // We then modify the request to add our desired headers.
1126            let request_headers = request.headers_mut();
1127            request_headers.insert(
1128                "Authorization",
1129                HeaderValue::from_str(&credentials.authorization_header())?,
1130            );
1131            request_headers.insert(
1132                "x-zed-protocol-version",
1133                HeaderValue::from_str(&rpc::PROTOCOL_VERSION.to_string())?,
1134            );
1135            request_headers.insert("x-zed-app-version", HeaderValue::from_str(&app_version)?);
1136            request_headers.insert(
1137                "x-zed-release-channel",
1138                HeaderValue::from_str(release_channel.map(|r| r.dev_name()).unwrap_or("unknown"))?,
1139            );
1140            if let Some(system_id) = system_id {
1141                request_headers.insert("x-zed-system-id", HeaderValue::from_str(&system_id)?);
1142            }
1143            if let Some(metrics_id) = metrics_id {
1144                request_headers.insert("x-zed-metrics-id", HeaderValue::from_str(&metrics_id)?);
1145            }
1146
1147            match url_scheme {
1148                Https => {
1149                    let (stream, _) =
1150                        async_tungstenite::async_tls::client_async_tls_with_connector(
1151                            request,
1152                            stream,
1153                            Some(http_client_tls::tls_config().into()),
1154                        )
1155                        .await?;
1156                    Ok(Connection::new(
1157                        stream
1158                            .map_err(|error| anyhow!(error))
1159                            .sink_map_err(|error| anyhow!(error)),
1160                    ))
1161                }
1162                Http => {
1163                    let (stream, _) = async_tungstenite::client_async(request, stream).await?;
1164                    Ok(Connection::new(
1165                        stream
1166                            .map_err(|error| anyhow!(error))
1167                            .sink_map_err(|error| anyhow!(error)),
1168                    ))
1169                }
1170            }
1171        })
1172    }
1173
1174    pub fn authenticate_with_browser(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1175        let http = self.http.clone();
1176        let this = self.clone();
1177        cx.spawn(async move |cx| {
1178            let background = cx.background_executor().clone();
1179
1180            let (open_url_tx, open_url_rx) = oneshot::channel::<String>();
1181            cx.update(|cx| {
1182                cx.spawn(async move |cx| {
1183                    let url = open_url_rx.await?;
1184                    cx.update(|cx| cx.open_url(&url))
1185                })
1186                .detach_and_log_err(cx);
1187            })
1188            .log_err();
1189
1190            let credentials = background
1191                .clone()
1192                .spawn(async move {
1193                    // Generate a pair of asymmetric encryption keys. The public key will be used by the
1194                    // zed server to encrypt the user's access token, so that it can'be intercepted by
1195                    // any other app running on the user's device.
1196                    let (public_key, private_key) =
1197                        rpc::auth::keypair().expect("failed to generate keypair for auth");
1198                    let public_key_string = String::try_from(public_key)
1199                        .expect("failed to serialize public key for auth");
1200
1201                    if let Some((login, token)) =
1202                        IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref())
1203                    {
1204                        eprintln!("authenticate as admin {login}, {token}");
1205
1206                        return this
1207                            .authenticate_as_admin(http, login.clone(), token.clone())
1208                            .await;
1209                    }
1210
1211                    // Start an HTTP server to receive the redirect from Zed's sign-in page.
1212                    let server =
1213                        tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1214                    let port = server.server_addr().port();
1215
1216                    // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1217                    // that the user is signing in from a Zed app running on the same device.
1218                    let mut url = http.build_url(&format!(
1219                        "/native_app_signin?native_app_port={}&native_app_public_key={}",
1220                        port, public_key_string
1221                    ));
1222
1223                    if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1224                        log::info!("impersonating user @{}", impersonate_login);
1225                        write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1226                    }
1227
1228                    open_url_tx.send(url).log_err();
1229
1230                    // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1231                    // access token from the query params.
1232                    //
1233                    // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1234                    // custom URL scheme instead of this local HTTP server.
1235                    let (user_id, access_token) = background
1236                        .spawn(async move {
1237                            for _ in 0..100 {
1238                                if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1239                                    let path = req.url();
1240                                    let mut user_id = None;
1241                                    let mut access_token = None;
1242                                    let url = Url::parse(&format!("http://example.com{}", path))
1243                                        .context("failed to parse login notification url")?;
1244                                    for (key, value) in url.query_pairs() {
1245                                        if key == "access_token" {
1246                                            access_token = Some(value.to_string());
1247                                        } else if key == "user_id" {
1248                                            user_id = Some(value.to_string());
1249                                        }
1250                                    }
1251
1252                                    let post_auth_url =
1253                                        http.build_url("/native_app_signin_succeeded");
1254                                    req.respond(
1255                                        tiny_http::Response::empty(302).with_header(
1256                                            tiny_http::Header::from_bytes(
1257                                                &b"Location"[..],
1258                                                post_auth_url.as_bytes(),
1259                                            )
1260                                            .unwrap(),
1261                                        ),
1262                                    )
1263                                    .context("failed to respond to login http request")?;
1264                                    return Ok((
1265                                        user_id
1266                                            .ok_or_else(|| anyhow!("missing user_id parameter"))?,
1267                                        access_token.ok_or_else(|| {
1268                                            anyhow!("missing access_token parameter")
1269                                        })?,
1270                                    ));
1271                                }
1272                            }
1273
1274                            Err(anyhow!("didn't receive login redirect"))
1275                        })
1276                        .await?;
1277
1278                    let access_token = private_key
1279                        .decrypt_string(&access_token)
1280                        .context("failed to decrypt access token")?;
1281
1282                    Ok(Credentials {
1283                        user_id: user_id.parse()?,
1284                        access_token,
1285                    })
1286                })
1287                .await?;
1288
1289            cx.update(|cx| cx.activate(true))?;
1290            Ok(credentials)
1291        })
1292    }
1293
1294    async fn authenticate_as_admin(
1295        self: &Arc<Self>,
1296        http: Arc<HttpClientWithUrl>,
1297        login: String,
1298        mut api_token: String,
1299    ) -> Result<Credentials> {
1300        #[derive(Deserialize)]
1301        struct AuthenticatedUserResponse {
1302            user: User,
1303        }
1304
1305        #[derive(Deserialize)]
1306        struct User {
1307            id: u64,
1308        }
1309
1310        let github_user = {
1311            #[derive(Deserialize)]
1312            struct GithubUser {
1313                id: i32,
1314                login: String,
1315                created_at: DateTime<Utc>,
1316            }
1317
1318            let request = {
1319                let mut request_builder =
1320                    Request::get(&format!("https://api.github.com/users/{login}"));
1321                if let Ok(github_token) = std::env::var("GITHUB_TOKEN") {
1322                    request_builder =
1323                        request_builder.header("Authorization", format!("Bearer {}", github_token));
1324                }
1325
1326                request_builder.body(AsyncBody::empty())?
1327            };
1328
1329            let mut response = http
1330                .send(request)
1331                .await
1332                .context("error fetching GitHub user")?;
1333
1334            let mut body = Vec::new();
1335            response
1336                .body_mut()
1337                .read_to_end(&mut body)
1338                .await
1339                .context("error reading GitHub user")?;
1340
1341            if !response.status().is_success() {
1342                let text = String::from_utf8_lossy(body.as_slice());
1343                bail!(
1344                    "status error {}, response: {text:?}",
1345                    response.status().as_u16()
1346                );
1347            }
1348
1349            serde_json::from_slice::<GithubUser>(body.as_slice()).map_err(|err| {
1350                log::error!("Error deserializing: {:?}", err);
1351                log::error!(
1352                    "GitHub API response text: {:?}",
1353                    String::from_utf8_lossy(body.as_slice())
1354                );
1355                anyhow!("error deserializing GitHub user")
1356            })?
1357        };
1358
1359        let query_params = [
1360            ("github_login", &github_user.login),
1361            ("github_user_id", &github_user.id.to_string()),
1362            (
1363                "github_user_created_at",
1364                &github_user.created_at.to_rfc3339(),
1365            ),
1366        ];
1367
1368        // Use the collab server's admin API to retrieve the ID
1369        // of the impersonated user.
1370        let mut url = self.rpc_url(http.clone(), None).await?;
1371        url.set_path("/user");
1372        url.set_query(Some(
1373            &query_params
1374                .iter()
1375                .map(|(key, value)| {
1376                    format!(
1377                        "{}={}",
1378                        key,
1379                        url::form_urlencoded::byte_serialize(value.as_bytes()).collect::<String>()
1380                    )
1381                })
1382                .collect::<Vec<String>>()
1383                .join("&"),
1384        ));
1385        let request: http_client::Request<AsyncBody> = Request::get(url.as_str())
1386            .header("Authorization", format!("token {api_token}"))
1387            .body("".into())?;
1388
1389        let mut response = http.send(request).await?;
1390        let mut body = String::new();
1391        response.body_mut().read_to_string(&mut body).await?;
1392        if !response.status().is_success() {
1393            Err(anyhow!(
1394                "admin user request failed {} - {}",
1395                response.status().as_u16(),
1396                body,
1397            ))?;
1398        }
1399        let response: AuthenticatedUserResponse = serde_json::from_str(&body)?;
1400
1401        // Use the admin API token to authenticate as the impersonated user.
1402        api_token.insert_str(0, "ADMIN_TOKEN:");
1403        Ok(Credentials {
1404            user_id: response.user.id,
1405            access_token: api_token,
1406        })
1407    }
1408
1409    pub async fn sign_out(self: &Arc<Self>, cx: &AsyncApp) {
1410        self.state.write().credentials = None;
1411        self.disconnect(cx);
1412
1413        if self.has_credentials(cx).await {
1414            self.credentials_provider
1415                .delete_credentials(cx)
1416                .await
1417                .log_err();
1418        }
1419    }
1420
1421    pub fn disconnect(self: &Arc<Self>, cx: &AsyncApp) {
1422        self.peer.teardown();
1423        self.set_status(Status::SignedOut, cx);
1424    }
1425
1426    pub fn reconnect(self: &Arc<Self>, cx: &AsyncApp) {
1427        self.peer.teardown();
1428        self.set_status(Status::ConnectionLost, cx);
1429    }
1430
1431    fn connection_id(&self) -> Result<ConnectionId> {
1432        if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1433            Ok(connection_id)
1434        } else {
1435            Err(anyhow!("not connected"))
1436        }
1437    }
1438
1439    pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1440        log::debug!("rpc send. client_id:{}, name:{}", self.id(), T::NAME);
1441        self.peer.send(self.connection_id()?, message)
1442    }
1443
1444    pub fn request<T: RequestMessage>(
1445        &self,
1446        request: T,
1447    ) -> impl Future<Output = Result<T::Response>> + use<T> {
1448        self.request_envelope(request)
1449            .map_ok(|envelope| envelope.payload)
1450    }
1451
1452    pub fn request_stream<T: RequestMessage>(
1453        &self,
1454        request: T,
1455    ) -> impl Future<Output = Result<impl Stream<Item = Result<T::Response>>>> {
1456        let client_id = self.id.load(Ordering::SeqCst);
1457        log::debug!(
1458            "rpc request start. client_id:{}. name:{}",
1459            client_id,
1460            T::NAME
1461        );
1462        let response = self
1463            .connection_id()
1464            .map(|conn_id| self.peer.request_stream(conn_id, request));
1465        async move {
1466            let response = response?.await;
1467            log::debug!(
1468                "rpc request finish. client_id:{}. name:{}",
1469                client_id,
1470                T::NAME
1471            );
1472            response
1473        }
1474    }
1475
1476    pub fn request_envelope<T: RequestMessage>(
1477        &self,
1478        request: T,
1479    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> + use<T> {
1480        let client_id = self.id();
1481        log::debug!(
1482            "rpc request start. client_id:{}. name:{}",
1483            client_id,
1484            T::NAME
1485        );
1486        let response = self
1487            .connection_id()
1488            .map(|conn_id| self.peer.request_envelope(conn_id, request));
1489        async move {
1490            let response = response?.await;
1491            log::debug!(
1492                "rpc request finish. client_id:{}. name:{}",
1493                client_id,
1494                T::NAME
1495            );
1496            response
1497        }
1498    }
1499
1500    pub fn request_dynamic(
1501        &self,
1502        envelope: proto::Envelope,
1503        request_type: &'static str,
1504    ) -> impl Future<Output = Result<proto::Envelope>> + use<> {
1505        let client_id = self.id();
1506        log::debug!(
1507            "rpc request start. client_id:{}. name:{}",
1508            client_id,
1509            request_type
1510        );
1511        let response = self
1512            .connection_id()
1513            .map(|conn_id| self.peer.request_dynamic(conn_id, envelope, request_type));
1514        async move {
1515            let response = response?.await;
1516            log::debug!(
1517                "rpc request finish. client_id:{}. name:{}",
1518                client_id,
1519                request_type
1520            );
1521            Ok(response?.0)
1522        }
1523    }
1524
1525    fn handle_message(self: &Arc<Client>, message: Box<dyn AnyTypedEnvelope>, cx: &AsyncApp) {
1526        let sender_id = message.sender_id();
1527        let request_id = message.message_id();
1528        let type_name = message.payload_type_name();
1529        let original_sender_id = message.original_sender_id();
1530
1531        if let Some(future) = ProtoMessageHandlerSet::handle_message(
1532            &self.handler_set,
1533            message,
1534            self.clone().into(),
1535            cx.clone(),
1536        ) {
1537            let client_id = self.id();
1538            log::debug!(
1539                "rpc message received. client_id:{}, sender_id:{:?}, type:{}",
1540                client_id,
1541                original_sender_id,
1542                type_name
1543            );
1544            cx.spawn(async move |_| match future.await {
1545                Ok(()) => {
1546                    log::debug!(
1547                        "rpc message handled. client_id:{}, sender_id:{:?}, type:{}",
1548                        client_id,
1549                        original_sender_id,
1550                        type_name
1551                    );
1552                }
1553                Err(error) => {
1554                    log::error!(
1555                        "error handling message. client_id:{}, sender_id:{:?}, type:{}, error:{:?}",
1556                        client_id,
1557                        original_sender_id,
1558                        type_name,
1559                        error
1560                    );
1561                }
1562            })
1563            .detach();
1564        } else {
1565            log::info!("unhandled message {}", type_name);
1566            self.peer
1567                .respond_with_unhandled_message(sender_id.into(), request_id, type_name)
1568                .log_err();
1569        }
1570    }
1571
1572    pub fn telemetry(&self) -> &Arc<Telemetry> {
1573        &self.telemetry
1574    }
1575}
1576
1577impl ProtoClient for Client {
1578    fn request(
1579        &self,
1580        envelope: proto::Envelope,
1581        request_type: &'static str,
1582    ) -> BoxFuture<'static, Result<proto::Envelope>> {
1583        self.request_dynamic(envelope, request_type).boxed()
1584    }
1585
1586    fn send(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1587        log::debug!("rpc send. client_id:{}, name:{}", self.id(), message_type);
1588        let connection_id = self.connection_id()?;
1589        self.peer.send_dynamic(connection_id, envelope)
1590    }
1591
1592    fn send_response(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1593        log::debug!(
1594            "rpc respond. client_id:{}, name:{}",
1595            self.id(),
1596            message_type
1597        );
1598        let connection_id = self.connection_id()?;
1599        self.peer.send_dynamic(connection_id, envelope)
1600    }
1601
1602    fn message_handler_set(&self) -> &parking_lot::Mutex<ProtoMessageHandlerSet> {
1603        &self.handler_set
1604    }
1605
1606    fn is_via_collab(&self) -> bool {
1607        true
1608    }
1609}
1610
1611/// prefix for the zed:// url scheme
1612pub const ZED_URL_SCHEME: &str = "zed";
1613
1614/// Parses the given link into a Zed link.
1615///
1616/// Returns a [`Some`] containing the unprefixed link if the link is a Zed link.
1617/// Returns [`None`] otherwise.
1618pub fn parse_zed_link<'a>(link: &'a str, cx: &App) -> Option<&'a str> {
1619    let server_url = &ClientSettings::get_global(cx).server_url;
1620    if let Some(stripped) = link
1621        .strip_prefix(server_url)
1622        .and_then(|result| result.strip_prefix('/'))
1623    {
1624        return Some(stripped);
1625    }
1626    if let Some(stripped) = link
1627        .strip_prefix(ZED_URL_SCHEME)
1628        .and_then(|result| result.strip_prefix("://"))
1629    {
1630        return Some(stripped);
1631    }
1632
1633    None
1634}
1635
1636#[cfg(test)]
1637mod tests {
1638    use super::*;
1639    use crate::test::FakeServer;
1640
1641    use clock::FakeSystemClock;
1642    use gpui::{BackgroundExecutor, TestAppContext};
1643    use http_client::FakeHttpClient;
1644    use parking_lot::Mutex;
1645    use proto::TypedEnvelope;
1646    use settings::SettingsStore;
1647    use std::future;
1648
1649    #[gpui::test(iterations = 10)]
1650    async fn test_reconnection(cx: &mut TestAppContext) {
1651        init_test(cx);
1652        let user_id = 5;
1653        let client = cx.update(|cx| {
1654            Client::new(
1655                Arc::new(FakeSystemClock::new()),
1656                FakeHttpClient::with_404_response(),
1657                cx,
1658            )
1659        });
1660        let server = FakeServer::for_client(user_id, &client, cx).await;
1661        let mut status = client.status();
1662        assert!(matches!(
1663            status.next().await,
1664            Some(Status::Connected { .. })
1665        ));
1666        assert_eq!(server.auth_count(), 1);
1667
1668        server.forbid_connections();
1669        server.disconnect();
1670        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1671
1672        server.allow_connections();
1673        cx.executor().advance_clock(Duration::from_secs(10));
1674        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1675        assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1676
1677        server.forbid_connections();
1678        server.disconnect();
1679        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1680
1681        // Clear cached credentials after authentication fails
1682        server.roll_access_token();
1683        server.allow_connections();
1684        cx.executor().run_until_parked();
1685        cx.executor().advance_clock(Duration::from_secs(10));
1686        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1687        assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1688    }
1689
1690    #[gpui::test(iterations = 10)]
1691    async fn test_connection_timeout(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1692        init_test(cx);
1693        let user_id = 5;
1694        let client = cx.update(|cx| {
1695            Client::new(
1696                Arc::new(FakeSystemClock::new()),
1697                FakeHttpClient::with_404_response(),
1698                cx,
1699            )
1700        });
1701        let mut status = client.status();
1702
1703        // Time out when client tries to connect.
1704        client.override_authenticate(move |cx| {
1705            cx.background_spawn(async move {
1706                Ok(Credentials {
1707                    user_id,
1708                    access_token: "token".into(),
1709                })
1710            })
1711        });
1712        client.override_establish_connection(|_, cx| {
1713            cx.background_spawn(async move {
1714                future::pending::<()>().await;
1715                unreachable!()
1716            })
1717        });
1718        let auth_and_connect = cx.spawn({
1719            let client = client.clone();
1720            |cx| async move { client.authenticate_and_connect(false, &cx).await }
1721        });
1722        executor.run_until_parked();
1723        assert!(matches!(status.next().await, Some(Status::Connecting)));
1724
1725        executor.advance_clock(CONNECTION_TIMEOUT);
1726        assert!(matches!(
1727            status.next().await,
1728            Some(Status::ConnectionError { .. })
1729        ));
1730        auth_and_connect.await.unwrap_err();
1731
1732        // Allow the connection to be established.
1733        let server = FakeServer::for_client(user_id, &client, cx).await;
1734        assert!(matches!(
1735            status.next().await,
1736            Some(Status::Connected { .. })
1737        ));
1738
1739        // Disconnect client.
1740        server.forbid_connections();
1741        server.disconnect();
1742        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1743
1744        // Time out when re-establishing the connection.
1745        server.allow_connections();
1746        client.override_establish_connection(|_, cx| {
1747            cx.background_spawn(async move {
1748                future::pending::<()>().await;
1749                unreachable!()
1750            })
1751        });
1752        executor.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1753        assert!(matches!(
1754            status.next().await,
1755            Some(Status::Reconnecting { .. })
1756        ));
1757
1758        executor.advance_clock(CONNECTION_TIMEOUT);
1759        assert!(matches!(
1760            status.next().await,
1761            Some(Status::ReconnectionError { .. })
1762        ));
1763    }
1764
1765    #[gpui::test(iterations = 10)]
1766    async fn test_authenticating_more_than_once(
1767        cx: &mut TestAppContext,
1768        executor: BackgroundExecutor,
1769    ) {
1770        init_test(cx);
1771        let auth_count = Arc::new(Mutex::new(0));
1772        let dropped_auth_count = Arc::new(Mutex::new(0));
1773        let client = cx.update(|cx| {
1774            Client::new(
1775                Arc::new(FakeSystemClock::new()),
1776                FakeHttpClient::with_404_response(),
1777                cx,
1778            )
1779        });
1780        client.override_authenticate({
1781            let auth_count = auth_count.clone();
1782            let dropped_auth_count = dropped_auth_count.clone();
1783            move |cx| {
1784                let auth_count = auth_count.clone();
1785                let dropped_auth_count = dropped_auth_count.clone();
1786                cx.background_spawn(async move {
1787                    *auth_count.lock() += 1;
1788                    let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
1789                    future::pending::<()>().await;
1790                    unreachable!()
1791                })
1792            }
1793        });
1794
1795        let _authenticate = cx.spawn({
1796            let client = client.clone();
1797            move |cx| async move { client.authenticate_and_connect(false, &cx).await }
1798        });
1799        executor.run_until_parked();
1800        assert_eq!(*auth_count.lock(), 1);
1801        assert_eq!(*dropped_auth_count.lock(), 0);
1802
1803        let _authenticate = cx.spawn({
1804            let client = client.clone();
1805            |cx| async move { client.authenticate_and_connect(false, &cx).await }
1806        });
1807        executor.run_until_parked();
1808        assert_eq!(*auth_count.lock(), 2);
1809        assert_eq!(*dropped_auth_count.lock(), 1);
1810    }
1811
1812    #[gpui::test]
1813    async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1814        init_test(cx);
1815        let user_id = 5;
1816        let client = cx.update(|cx| {
1817            Client::new(
1818                Arc::new(FakeSystemClock::new()),
1819                FakeHttpClient::with_404_response(),
1820                cx,
1821            )
1822        });
1823        let server = FakeServer::for_client(user_id, &client, cx).await;
1824
1825        let (done_tx1, done_rx1) = smol::channel::unbounded();
1826        let (done_tx2, done_rx2) = smol::channel::unbounded();
1827        AnyProtoClient::from(client.clone()).add_entity_message_handler(
1828            move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::JoinProject>, mut cx| {
1829                match entity.update(&mut cx, |entity, _| entity.id).unwrap() {
1830                    1 => done_tx1.try_send(()).unwrap(),
1831                    2 => done_tx2.try_send(()).unwrap(),
1832                    _ => unreachable!(),
1833                }
1834                async { Ok(()) }
1835            },
1836        );
1837        let entity1 = cx.new(|_| TestEntity {
1838            id: 1,
1839            subscription: None,
1840        });
1841        let entity2 = cx.new(|_| TestEntity {
1842            id: 2,
1843            subscription: None,
1844        });
1845        let entity3 = cx.new(|_| TestEntity {
1846            id: 3,
1847            subscription: None,
1848        });
1849
1850        let _subscription1 = client
1851            .subscribe_to_entity(1)
1852            .unwrap()
1853            .set_entity(&entity1, &mut cx.to_async());
1854        let _subscription2 = client
1855            .subscribe_to_entity(2)
1856            .unwrap()
1857            .set_entity(&entity2, &mut cx.to_async());
1858        // Ensure dropping a subscription for the same entity type still allows receiving of
1859        // messages for other entity IDs of the same type.
1860        let subscription3 = client
1861            .subscribe_to_entity(3)
1862            .unwrap()
1863            .set_entity(&entity3, &mut cx.to_async());
1864        drop(subscription3);
1865
1866        server.send(proto::JoinProject { project_id: 1 });
1867        server.send(proto::JoinProject { project_id: 2 });
1868        done_rx1.recv().await.unwrap();
1869        done_rx2.recv().await.unwrap();
1870    }
1871
1872    #[gpui::test]
1873    async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
1874        init_test(cx);
1875        let user_id = 5;
1876        let client = cx.update(|cx| {
1877            Client::new(
1878                Arc::new(FakeSystemClock::new()),
1879                FakeHttpClient::with_404_response(),
1880                cx,
1881            )
1882        });
1883        let server = FakeServer::for_client(user_id, &client, cx).await;
1884
1885        let entity = cx.new(|_| TestEntity::default());
1886        let (done_tx1, _done_rx1) = smol::channel::unbounded();
1887        let (done_tx2, done_rx2) = smol::channel::unbounded();
1888        let subscription1 = client.add_message_handler(
1889            entity.downgrade(),
1890            move |_, _: TypedEnvelope<proto::Ping>, _| {
1891                done_tx1.try_send(()).unwrap();
1892                async { Ok(()) }
1893            },
1894        );
1895        drop(subscription1);
1896        let _subscription2 = client.add_message_handler(
1897            entity.downgrade(),
1898            move |_, _: TypedEnvelope<proto::Ping>, _| {
1899                done_tx2.try_send(()).unwrap();
1900                async { Ok(()) }
1901            },
1902        );
1903        server.send(proto::Ping {});
1904        done_rx2.recv().await.unwrap();
1905    }
1906
1907    #[gpui::test]
1908    async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
1909        init_test(cx);
1910        let user_id = 5;
1911        let client = cx.update(|cx| {
1912            Client::new(
1913                Arc::new(FakeSystemClock::new()),
1914                FakeHttpClient::with_404_response(),
1915                cx,
1916            )
1917        });
1918        let server = FakeServer::for_client(user_id, &client, cx).await;
1919
1920        let entity = cx.new(|_| TestEntity::default());
1921        let (done_tx, done_rx) = smol::channel::unbounded();
1922        let subscription = client.add_message_handler(
1923            entity.clone().downgrade(),
1924            move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::Ping>, mut cx| {
1925                entity
1926                    .update(&mut cx, |entity, _| entity.subscription.take())
1927                    .unwrap();
1928                done_tx.try_send(()).unwrap();
1929                async { Ok(()) }
1930            },
1931        );
1932        entity.update(cx, |entity, _| {
1933            entity.subscription = Some(subscription);
1934        });
1935        server.send(proto::Ping {});
1936        done_rx.recv().await.unwrap();
1937    }
1938
1939    #[derive(Default)]
1940    struct TestEntity {
1941        id: usize,
1942        subscription: Option<Subscription>,
1943    }
1944
1945    fn init_test(cx: &mut TestAppContext) {
1946        cx.update(|cx| {
1947            let settings_store = SettingsStore::test(cx);
1948            cx.set_global(settings_store);
1949            init_settings(cx);
1950        });
1951    }
1952}