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