client.rs

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