client.rs

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