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