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::pin::Pin;
  35use std::{
  36    any::TypeId,
  37    convert::TryFrom,
  38    fmt::Write as _,
  39    future::Future,
  40    marker::PhantomData,
  41    path::PathBuf,
  42    sync::{
  43        Arc, LazyLock, Weak,
  44        atomic::{AtomicU64, Ordering},
  45    },
  46    time::{Duration, Instant},
  47};
  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(10);
  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                            cx.background_executor().timer(delay).await;
 731                            delay = delay
 732                                .mul_f32(rng.gen_range(0.5..=2.5))
 733                                .max(INITIAL_RECONNECTION_DELAY)
 734                                .min(MAX_RECONNECTION_DELAY);
 735                        } else {
 736                            break;
 737                        }
 738                    }
 739                }));
 740            }
 741            Status::SignedOut | Status::UpgradeRequired => {
 742                self.telemetry.set_authenticated_user_info(None, false);
 743                state._reconnect_task.take();
 744            }
 745            _ => {}
 746        }
 747    }
 748
 749    pub fn subscribe_to_entity<T>(
 750        self: &Arc<Self>,
 751        remote_id: u64,
 752    ) -> Result<PendingEntitySubscription<T>>
 753    where
 754        T: 'static,
 755    {
 756        let id = (TypeId::of::<T>(), remote_id);
 757
 758        let mut state = self.handler_set.lock();
 759        anyhow::ensure!(
 760            !state.entities_by_type_and_remote_id.contains_key(&id),
 761            "already subscribed to entity"
 762        );
 763
 764        state
 765            .entities_by_type_and_remote_id
 766            .insert(id, EntityMessageSubscriber::Pending(Default::default()));
 767
 768        Ok(PendingEntitySubscription {
 769            client: self.clone(),
 770            remote_id,
 771            consumed: false,
 772            _entity_type: PhantomData,
 773        })
 774    }
 775
 776    #[track_caller]
 777    pub fn add_message_handler<M, E, H, F>(
 778        self: &Arc<Self>,
 779        entity: WeakEntity<E>,
 780        handler: H,
 781    ) -> Subscription
 782    where
 783        M: EnvelopedMessage,
 784        E: 'static,
 785        H: 'static + Sync + Fn(Entity<E>, TypedEnvelope<M>, AsyncApp) -> F + Send + Sync,
 786        F: 'static + Future<Output = Result<()>>,
 787    {
 788        self.add_message_handler_impl(entity, move |entity, message, _, cx| {
 789            handler(entity, message, cx)
 790        })
 791    }
 792
 793    fn add_message_handler_impl<M, E, H, F>(
 794        self: &Arc<Self>,
 795        entity: WeakEntity<E>,
 796        handler: H,
 797    ) -> Subscription
 798    where
 799        M: EnvelopedMessage,
 800        E: 'static,
 801        H: 'static
 802            + Sync
 803            + Fn(Entity<E>, TypedEnvelope<M>, AnyProtoClient, AsyncApp) -> F
 804            + Send
 805            + Sync,
 806        F: 'static + Future<Output = Result<()>>,
 807    {
 808        let message_type_id = TypeId::of::<M>();
 809        let mut state = self.handler_set.lock();
 810        state
 811            .entities_by_message_type
 812            .insert(message_type_id, entity.into());
 813
 814        let prev_handler = state.message_handlers.insert(
 815            message_type_id,
 816            Arc::new(move |subscriber, envelope, client, cx| {
 817                let subscriber = subscriber.downcast::<E>().unwrap();
 818                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 819                handler(subscriber, *envelope, client.clone(), cx).boxed_local()
 820            }),
 821        );
 822        if prev_handler.is_some() {
 823            let location = std::panic::Location::caller();
 824            panic!(
 825                "{}:{} registered handler for the same message {} twice",
 826                location.file(),
 827                location.line(),
 828                std::any::type_name::<M>()
 829            );
 830        }
 831
 832        Subscription::Message {
 833            client: Arc::downgrade(self),
 834            id: message_type_id,
 835        }
 836    }
 837
 838    pub fn add_request_handler<M, E, H, F>(
 839        self: &Arc<Self>,
 840        entity: WeakEntity<E>,
 841        handler: H,
 842    ) -> Subscription
 843    where
 844        M: RequestMessage,
 845        E: 'static,
 846        H: 'static + Sync + Fn(Entity<E>, TypedEnvelope<M>, AsyncApp) -> F + Send + Sync,
 847        F: 'static + Future<Output = Result<M::Response>>,
 848    {
 849        self.add_message_handler_impl(entity, move |handle, envelope, this, cx| {
 850            Self::respond_to_request(envelope.receipt(), handler(handle, envelope, cx), this)
 851        })
 852    }
 853
 854    async fn respond_to_request<T: RequestMessage, F: Future<Output = Result<T::Response>>>(
 855        receipt: Receipt<T>,
 856        response: F,
 857        client: AnyProtoClient,
 858    ) -> Result<()> {
 859        match response.await {
 860            Ok(response) => {
 861                client.send_response(receipt.message_id, response)?;
 862                Ok(())
 863            }
 864            Err(error) => {
 865                client.send_response(receipt.message_id, error.to_proto())?;
 866                Err(error)
 867            }
 868        }
 869    }
 870
 871    pub async fn has_credentials(&self, cx: &AsyncApp) -> bool {
 872        self.credentials_provider
 873            .read_credentials(cx)
 874            .await
 875            .is_some()
 876    }
 877
 878    #[async_recursion(?Send)]
 879    pub async fn authenticate_and_connect(
 880        self: &Arc<Self>,
 881        try_provider: bool,
 882        cx: &AsyncApp,
 883    ) -> ConnectionResult<()> {
 884        let was_disconnected = match *self.status().borrow() {
 885            Status::SignedOut => true,
 886            Status::ConnectionError
 887            | Status::ConnectionLost
 888            | Status::Authenticating { .. }
 889            | Status::Reauthenticating { .. }
 890            | Status::ReconnectionError { .. } => false,
 891            Status::Connected { .. } | Status::Connecting { .. } | Status::Reconnecting { .. } => {
 892                return ConnectionResult::Result(Ok(()));
 893            }
 894            Status::UpgradeRequired => {
 895                return ConnectionResult::Result(
 896                    Err(EstablishConnectionError::UpgradeRequired)
 897                        .context("client auth and connect"),
 898                );
 899            }
 900        };
 901        if was_disconnected {
 902            self.set_status(Status::Authenticating, cx);
 903        } else {
 904            self.set_status(Status::Reauthenticating, cx)
 905        }
 906
 907        let mut read_from_provider = false;
 908        let mut credentials = self.state.read().credentials.clone();
 909        if credentials.is_none() && try_provider {
 910            credentials = self.credentials_provider.read_credentials(cx).await;
 911            read_from_provider = credentials.is_some();
 912        }
 913
 914        if credentials.is_none() {
 915            let mut status_rx = self.status();
 916            let _ = status_rx.next().await;
 917            futures::select_biased! {
 918                authenticate = self.authenticate(cx).fuse() => {
 919                    match authenticate {
 920                        Ok(creds) => credentials = Some(creds),
 921                        Err(err) => {
 922                            self.set_status(Status::ConnectionError, cx);
 923                            return ConnectionResult::Result(Err(err));
 924                        }
 925                    }
 926                }
 927                _ = status_rx.next().fuse() => {
 928                    return ConnectionResult::Result(Err(anyhow!("authentication canceled")));
 929                }
 930            }
 931        }
 932        let credentials = credentials.unwrap();
 933        self.set_id(credentials.user_id);
 934
 935        if was_disconnected {
 936            self.set_status(Status::Connecting, cx);
 937        } else {
 938            self.set_status(Status::Reconnecting, cx);
 939        }
 940
 941        let mut timeout =
 942            futures::FutureExt::fuse(cx.background_executor().timer(CONNECTION_TIMEOUT));
 943        futures::select_biased! {
 944            connection = self.establish_connection(&credentials, cx).fuse() => {
 945                match connection {
 946                    Ok(conn) => {
 947                        self.state.write().credentials = Some(credentials.clone());
 948                        if !read_from_provider && IMPERSONATE_LOGIN.is_none() {
 949                            self.credentials_provider.write_credentials(credentials.user_id, credentials.access_token, cx).await.log_err();
 950                        }
 951
 952                        futures::select_biased! {
 953                            result = self.set_connection(conn, cx).fuse() => {
 954                                match result.context("client auth and connect") {
 955                                    Ok(()) => ConnectionResult::Result(Ok(())),
 956                                    Err(err) => {
 957                                        self.set_status(Status::ConnectionError, cx);
 958                                        ConnectionResult::Result(Err(err))
 959                                    },
 960                                }
 961                            },
 962                            _ = timeout => {
 963                                self.set_status(Status::ConnectionError, cx);
 964                                ConnectionResult::Timeout
 965                            }
 966                        }
 967                    }
 968                    Err(EstablishConnectionError::Unauthorized) => {
 969                        self.state.write().credentials.take();
 970                        if read_from_provider {
 971                            self.credentials_provider.delete_credentials(cx).await.log_err();
 972                            self.set_status(Status::SignedOut, cx);
 973                            self.authenticate_and_connect(false, cx).await
 974                        } else {
 975                            self.set_status(Status::ConnectionError, cx);
 976                            ConnectionResult::Result(Err(EstablishConnectionError::Unauthorized).context("client auth and connect"))
 977                        }
 978                    }
 979                    Err(EstablishConnectionError::UpgradeRequired) => {
 980                        self.set_status(Status::UpgradeRequired, cx);
 981                        ConnectionResult::Result(Err(EstablishConnectionError::UpgradeRequired).context("client auth and connect"))
 982                    }
 983                    Err(error) => {
 984                        self.set_status(Status::ConnectionError, cx);
 985                        ConnectionResult::Result(Err(error).context("client auth and connect"))
 986                    }
 987                }
 988            }
 989            _ = &mut timeout => {
 990                self.set_status(Status::ConnectionError, cx);
 991                ConnectionResult::Timeout
 992            }
 993        }
 994    }
 995
 996    async fn set_connection(self: &Arc<Self>, conn: Connection, cx: &AsyncApp) -> Result<()> {
 997        let executor = cx.background_executor();
 998        log::debug!("add connection to peer");
 999        let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn, {
1000            let executor = executor.clone();
1001            move |duration| executor.timer(duration)
1002        });
1003        let handle_io = executor.spawn(handle_io);
1004
1005        let peer_id = async {
1006            log::debug!("waiting for server hello");
1007            let message = incoming.next().await.context("no hello message received")?;
1008            log::debug!("got server hello");
1009            let hello_message_type_name = message.payload_type_name().to_string();
1010            let hello = message
1011                .into_any()
1012                .downcast::<TypedEnvelope<proto::Hello>>()
1013                .map_err(|_| {
1014                    anyhow!(
1015                        "invalid hello message received: {:?}",
1016                        hello_message_type_name
1017                    )
1018                })?;
1019            let peer_id = hello.payload.peer_id.context("invalid peer id")?;
1020            Ok(peer_id)
1021        };
1022
1023        let peer_id = match peer_id.await {
1024            Ok(peer_id) => peer_id,
1025            Err(error) => {
1026                self.peer.disconnect(connection_id);
1027                return Err(error);
1028            }
1029        };
1030
1031        log::debug!(
1032            "set status to connected (connection id: {:?}, peer id: {:?})",
1033            connection_id,
1034            peer_id
1035        );
1036        self.set_status(
1037            Status::Connected {
1038                peer_id,
1039                connection_id,
1040            },
1041            cx,
1042        );
1043
1044        cx.spawn({
1045            let this = self.clone();
1046            async move |cx| {
1047                while let Some(message) = incoming.next().await {
1048                    this.handle_message(message, &cx);
1049                    // Don't starve the main thread when receiving lots of messages at once.
1050                    smol::future::yield_now().await;
1051                }
1052            }
1053        })
1054        .detach();
1055
1056        cx.spawn({
1057            let this = self.clone();
1058            async move |cx| match handle_io.await {
1059                Ok(()) => {
1060                    if *this.status().borrow()
1061                        == (Status::Connected {
1062                            connection_id,
1063                            peer_id,
1064                        })
1065                    {
1066                        this.set_status(Status::SignedOut, &cx);
1067                    }
1068                }
1069                Err(err) => {
1070                    log::error!("connection error: {:?}", err);
1071                    this.set_status(Status::ConnectionLost, &cx);
1072                }
1073            }
1074        })
1075        .detach();
1076
1077        Ok(())
1078    }
1079
1080    fn authenticate(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1081        #[cfg(any(test, feature = "test-support"))]
1082        if let Some(callback) = self.authenticate.read().as_ref() {
1083            return callback(cx);
1084        }
1085
1086        self.authenticate_with_browser(cx)
1087    }
1088
1089    fn establish_connection(
1090        self: &Arc<Self>,
1091        credentials: &Credentials,
1092        cx: &AsyncApp,
1093    ) -> Task<Result<Connection, EstablishConnectionError>> {
1094        #[cfg(any(test, feature = "test-support"))]
1095        if let Some(callback) = self.establish_connection.read().as_ref() {
1096            return callback(credentials, cx);
1097        }
1098
1099        self.establish_websocket_connection(credentials, cx)
1100    }
1101
1102    fn rpc_url(
1103        &self,
1104        http: Arc<HttpClientWithUrl>,
1105        release_channel: Option<ReleaseChannel>,
1106    ) -> impl Future<Output = Result<url::Url>> + use<> {
1107        #[cfg(any(test, feature = "test-support"))]
1108        let url_override = self.rpc_url.read().clone();
1109
1110        async move {
1111            #[cfg(any(test, feature = "test-support"))]
1112            if let Some(url) = url_override {
1113                return Ok(url);
1114            }
1115
1116            if let Some(url) = &*ZED_RPC_URL {
1117                return Url::parse(url).context("invalid rpc url");
1118            }
1119
1120            let mut url = http.build_url("/rpc");
1121            if let Some(preview_param) =
1122                release_channel.and_then(|channel| channel.release_query_param())
1123            {
1124                url += "?";
1125                url += preview_param;
1126            }
1127
1128            let response = http.get(&url, Default::default(), false).await?;
1129            anyhow::ensure!(
1130                response.status().is_redirection(),
1131                "unexpected /rpc response status {}",
1132                response.status()
1133            );
1134            let collab_url = response
1135                .headers()
1136                .get("Location")
1137                .context("missing location header in /rpc response")?
1138                .to_str()
1139                .map_err(EstablishConnectionError::other)?
1140                .to_string();
1141            Url::parse(&collab_url).with_context(|| format!("parsing collab rpc url {collab_url}"))
1142        }
1143    }
1144
1145    fn establish_websocket_connection(
1146        self: &Arc<Self>,
1147        credentials: &Credentials,
1148        cx: &AsyncApp,
1149    ) -> Task<Result<Connection, EstablishConnectionError>> {
1150        let release_channel = cx
1151            .update(|cx| ReleaseChannel::try_global(cx))
1152            .ok()
1153            .flatten();
1154        let app_version = cx
1155            .update(|cx| AppVersion::global(cx).to_string())
1156            .ok()
1157            .unwrap_or_default();
1158
1159        let http = self.http.clone();
1160        let proxy = http.proxy().cloned();
1161        let user_agent = http.user_agent().cloned();
1162        let credentials = credentials.clone();
1163        let rpc_url = self.rpc_url(http, release_channel);
1164        let system_id = self.telemetry.system_id();
1165        let metrics_id = self.telemetry.metrics_id();
1166        cx.spawn(async move |cx| {
1167            use HttpOrHttps::*;
1168
1169            #[derive(Debug)]
1170            enum HttpOrHttps {
1171                Http,
1172                Https,
1173            }
1174
1175            let mut rpc_url = rpc_url.await?;
1176            let url_scheme = match rpc_url.scheme() {
1177                "https" => Https,
1178                "http" => Http,
1179                _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1180            };
1181            let rpc_host = rpc_url
1182                .host_str()
1183                .zip(rpc_url.port_or_known_default())
1184                .context("missing host in rpc url")?;
1185
1186            let stream = {
1187                let handle = cx.update(|cx| gpui_tokio::Tokio::handle(cx)).ok().unwrap();
1188                let _guard = handle.enter();
1189                match proxy {
1190                    Some(proxy) => connect_proxy_stream(&proxy, rpc_host).await?,
1191                    None => Box::new(TcpStream::connect(rpc_host).await?),
1192                }
1193            };
1194
1195            log::info!("connected to rpc endpoint {}", rpc_url);
1196
1197            rpc_url
1198                .set_scheme(match url_scheme {
1199                    Https => "wss",
1200                    Http => "ws",
1201                })
1202                .unwrap();
1203
1204            // We call `into_client_request` to let `tungstenite` construct the WebSocket request
1205            // for us from the RPC URL.
1206            //
1207            // Among other things, it will generate and set a `Sec-WebSocket-Key` header for us.
1208            let mut request = IntoClientRequest::into_client_request(rpc_url.as_str())?;
1209
1210            // We then modify the request to add our desired headers.
1211            let request_headers = request.headers_mut();
1212            request_headers.insert(
1213                http::header::AUTHORIZATION,
1214                HeaderValue::from_str(&credentials.authorization_header())?,
1215            );
1216            request_headers.insert(
1217                "x-zed-protocol-version",
1218                HeaderValue::from_str(&rpc::PROTOCOL_VERSION.to_string())?,
1219            );
1220            request_headers.insert("x-zed-app-version", HeaderValue::from_str(&app_version)?);
1221            request_headers.insert(
1222                "x-zed-release-channel",
1223                HeaderValue::from_str(release_channel.map(|r| r.dev_name()).unwrap_or("unknown"))?,
1224            );
1225            if let Some(user_agent) = user_agent {
1226                request_headers.insert(http::header::USER_AGENT, user_agent);
1227            }
1228            if let Some(system_id) = system_id {
1229                request_headers.insert("x-zed-system-id", HeaderValue::from_str(&system_id)?);
1230            }
1231            if let Some(metrics_id) = metrics_id {
1232                request_headers.insert("x-zed-metrics-id", HeaderValue::from_str(&metrics_id)?);
1233            }
1234
1235            let (stream, _) = async_tungstenite::tokio::client_async_tls_with_connector_and_config(
1236                request,
1237                stream,
1238                Some(Arc::new(http_client_tls::tls_config()).into()),
1239                None,
1240            )
1241            .await?;
1242
1243            Ok(Connection::new(
1244                stream
1245                    .map_err(|error| anyhow!(error))
1246                    .sink_map_err(|error| anyhow!(error)),
1247            ))
1248        })
1249    }
1250
1251    pub fn authenticate_with_browser(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1252        let http = self.http.clone();
1253        let this = self.clone();
1254        cx.spawn(async move |cx| {
1255            let background = cx.background_executor().clone();
1256
1257            let (open_url_tx, open_url_rx) = oneshot::channel::<String>();
1258            cx.update(|cx| {
1259                cx.spawn(async move |cx| {
1260                    let url = open_url_rx.await?;
1261                    cx.update(|cx| cx.open_url(&url))
1262                })
1263                .detach_and_log_err(cx);
1264            })
1265            .log_err();
1266
1267            let credentials = background
1268                .clone()
1269                .spawn(async move {
1270                    // Generate a pair of asymmetric encryption keys. The public key will be used by the
1271                    // zed server to encrypt the user's access token, so that it can'be intercepted by
1272                    // any other app running on the user's device.
1273                    let (public_key, private_key) =
1274                        rpc::auth::keypair().expect("failed to generate keypair for auth");
1275                    let public_key_string = String::try_from(public_key)
1276                        .expect("failed to serialize public key for auth");
1277
1278                    if let Some((login, token)) =
1279                        IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref())
1280                    {
1281                        eprintln!("authenticate as admin {login}, {token}");
1282
1283                        return this
1284                            .authenticate_as_admin(http, login.clone(), token.clone())
1285                            .await;
1286                    }
1287
1288                    // Start an HTTP server to receive the redirect from Zed's sign-in page.
1289                    let server =
1290                        tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1291                    let port = server.server_addr().port();
1292
1293                    // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1294                    // that the user is signing in from a Zed app running on the same device.
1295                    let mut url = http.build_url(&format!(
1296                        "/native_app_signin?native_app_port={}&native_app_public_key={}",
1297                        port, public_key_string
1298                    ));
1299
1300                    if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1301                        log::info!("impersonating user @{}", impersonate_login);
1302                        write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1303                    }
1304
1305                    open_url_tx.send(url).log_err();
1306
1307                    // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1308                    // access token from the query params.
1309                    //
1310                    // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1311                    // custom URL scheme instead of this local HTTP server.
1312                    let (user_id, access_token) = background
1313                        .spawn(async move {
1314                            for _ in 0..100 {
1315                                if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1316                                    let path = req.url();
1317                                    let mut user_id = None;
1318                                    let mut access_token = None;
1319                                    let url = Url::parse(&format!("http://example.com{}", path))
1320                                        .context("failed to parse login notification url")?;
1321                                    for (key, value) in url.query_pairs() {
1322                                        if key == "access_token" {
1323                                            access_token = Some(value.to_string());
1324                                        } else if key == "user_id" {
1325                                            user_id = Some(value.to_string());
1326                                        }
1327                                    }
1328
1329                                    let post_auth_url =
1330                                        http.build_url("/native_app_signin_succeeded");
1331                                    req.respond(
1332                                        tiny_http::Response::empty(302).with_header(
1333                                            tiny_http::Header::from_bytes(
1334                                                &b"Location"[..],
1335                                                post_auth_url.as_bytes(),
1336                                            )
1337                                            .unwrap(),
1338                                        ),
1339                                    )
1340                                    .context("failed to respond to login http request")?;
1341                                    return Ok((
1342                                        user_id.context("missing user_id parameter")?,
1343                                        access_token.context("missing access_token parameter")?,
1344                                    ));
1345                                }
1346                            }
1347
1348                            anyhow::bail!("didn't receive login redirect");
1349                        })
1350                        .await?;
1351
1352                    let access_token = private_key
1353                        .decrypt_string(&access_token)
1354                        .context("failed to decrypt access token")?;
1355
1356                    Ok(Credentials {
1357                        user_id: user_id.parse()?,
1358                        access_token,
1359                    })
1360                })
1361                .await?;
1362
1363            cx.update(|cx| cx.activate(true))?;
1364            Ok(credentials)
1365        })
1366    }
1367
1368    async fn authenticate_as_admin(
1369        self: &Arc<Self>,
1370        http: Arc<HttpClientWithUrl>,
1371        login: String,
1372        mut api_token: String,
1373    ) -> Result<Credentials> {
1374        #[derive(Deserialize)]
1375        struct AuthenticatedUserResponse {
1376            user: User,
1377        }
1378
1379        #[derive(Deserialize)]
1380        struct User {
1381            id: u64,
1382        }
1383
1384        let github_user = {
1385            #[derive(Deserialize)]
1386            struct GithubUser {
1387                id: i32,
1388                login: String,
1389                created_at: DateTime<Utc>,
1390            }
1391
1392            let request = {
1393                let mut request_builder =
1394                    Request::get(&format!("https://api.github.com/users/{login}"));
1395                if let Ok(github_token) = std::env::var("GITHUB_TOKEN") {
1396                    request_builder =
1397                        request_builder.header("Authorization", format!("Bearer {}", github_token));
1398                }
1399
1400                request_builder.body(AsyncBody::empty())?
1401            };
1402
1403            let mut response = http
1404                .send(request)
1405                .await
1406                .context("error fetching GitHub user")?;
1407
1408            let mut body = Vec::new();
1409            response
1410                .body_mut()
1411                .read_to_end(&mut body)
1412                .await
1413                .context("error reading GitHub user")?;
1414
1415            if !response.status().is_success() {
1416                let text = String::from_utf8_lossy(body.as_slice());
1417                bail!(
1418                    "status error {}, response: {text:?}",
1419                    response.status().as_u16()
1420                );
1421            }
1422
1423            serde_json::from_slice::<GithubUser>(body.as_slice()).map_err(|err| {
1424                log::error!("Error deserializing: {:?}", err);
1425                log::error!(
1426                    "GitHub API response text: {:?}",
1427                    String::from_utf8_lossy(body.as_slice())
1428                );
1429                anyhow!("error deserializing GitHub user")
1430            })?
1431        };
1432
1433        let query_params = [
1434            ("github_login", &github_user.login),
1435            ("github_user_id", &github_user.id.to_string()),
1436            (
1437                "github_user_created_at",
1438                &github_user.created_at.to_rfc3339(),
1439            ),
1440        ];
1441
1442        // Use the collab server's admin API to retrieve the ID
1443        // of the impersonated user.
1444        let mut url = self.rpc_url(http.clone(), None).await?;
1445        url.set_path("/user");
1446        url.set_query(Some(
1447            &query_params
1448                .iter()
1449                .map(|(key, value)| {
1450                    format!(
1451                        "{}={}",
1452                        key,
1453                        url::form_urlencoded::byte_serialize(value.as_bytes()).collect::<String>()
1454                    )
1455                })
1456                .collect::<Vec<String>>()
1457                .join("&"),
1458        ));
1459        let request: http_client::Request<AsyncBody> = Request::get(url.as_str())
1460            .header("Authorization", format!("token {api_token}"))
1461            .body("".into())?;
1462
1463        let mut response = http.send(request).await?;
1464        let mut body = String::new();
1465        response.body_mut().read_to_string(&mut body).await?;
1466        anyhow::ensure!(
1467            response.status().is_success(),
1468            "admin user request failed {} - {}",
1469            response.status().as_u16(),
1470            body,
1471        );
1472        let response: AuthenticatedUserResponse = serde_json::from_str(&body)?;
1473
1474        // Use the admin API token to authenticate as the impersonated user.
1475        api_token.insert_str(0, "ADMIN_TOKEN:");
1476        Ok(Credentials {
1477            user_id: response.user.id,
1478            access_token: api_token,
1479        })
1480    }
1481
1482    pub async fn sign_out(self: &Arc<Self>, cx: &AsyncApp) {
1483        self.state.write().credentials = None;
1484        self.disconnect(cx);
1485
1486        if self.has_credentials(cx).await {
1487            self.credentials_provider
1488                .delete_credentials(cx)
1489                .await
1490                .log_err();
1491        }
1492    }
1493
1494    pub fn disconnect(self: &Arc<Self>, cx: &AsyncApp) {
1495        self.peer.teardown();
1496        self.set_status(Status::SignedOut, cx);
1497    }
1498
1499    pub fn reconnect(self: &Arc<Self>, cx: &AsyncApp) {
1500        self.peer.teardown();
1501        self.set_status(Status::ConnectionLost, cx);
1502    }
1503
1504    fn connection_id(&self) -> Result<ConnectionId> {
1505        if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1506            Ok(connection_id)
1507        } else {
1508            anyhow::bail!("not connected");
1509        }
1510    }
1511
1512    pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1513        log::debug!("rpc send. client_id:{}, name:{}", self.id(), T::NAME);
1514        self.peer.send(self.connection_id()?, message)
1515    }
1516
1517    pub fn request<T: RequestMessage>(
1518        &self,
1519        request: T,
1520    ) -> impl Future<Output = Result<T::Response>> + use<T> {
1521        self.request_envelope(request)
1522            .map_ok(|envelope| envelope.payload)
1523    }
1524
1525    pub fn request_stream<T: RequestMessage>(
1526        &self,
1527        request: T,
1528    ) -> impl Future<Output = Result<impl Stream<Item = Result<T::Response>>>> {
1529        let client_id = self.id.load(Ordering::SeqCst);
1530        log::debug!(
1531            "rpc request start. client_id:{}. name:{}",
1532            client_id,
1533            T::NAME
1534        );
1535        let response = self
1536            .connection_id()
1537            .map(|conn_id| self.peer.request_stream(conn_id, request));
1538        async move {
1539            let response = response?.await;
1540            log::debug!(
1541                "rpc request finish. client_id:{}. name:{}",
1542                client_id,
1543                T::NAME
1544            );
1545            response
1546        }
1547    }
1548
1549    pub fn request_envelope<T: RequestMessage>(
1550        &self,
1551        request: T,
1552    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> + use<T> {
1553        let client_id = self.id();
1554        log::debug!(
1555            "rpc request start. client_id:{}. name:{}",
1556            client_id,
1557            T::NAME
1558        );
1559        let response = self
1560            .connection_id()
1561            .map(|conn_id| self.peer.request_envelope(conn_id, request));
1562        async move {
1563            let response = response?.await;
1564            log::debug!(
1565                "rpc request finish. client_id:{}. name:{}",
1566                client_id,
1567                T::NAME
1568            );
1569            response
1570        }
1571    }
1572
1573    pub fn request_dynamic(
1574        &self,
1575        envelope: proto::Envelope,
1576        request_type: &'static str,
1577    ) -> impl Future<Output = Result<proto::Envelope>> + use<> {
1578        let client_id = self.id();
1579        log::debug!(
1580            "rpc request start. client_id:{}. name:{}",
1581            client_id,
1582            request_type
1583        );
1584        let response = self
1585            .connection_id()
1586            .map(|conn_id| self.peer.request_dynamic(conn_id, envelope, request_type));
1587        async move {
1588            let response = response?.await;
1589            log::debug!(
1590                "rpc request finish. client_id:{}. name:{}",
1591                client_id,
1592                request_type
1593            );
1594            Ok(response?.0)
1595        }
1596    }
1597
1598    fn handle_message(self: &Arc<Client>, message: Box<dyn AnyTypedEnvelope>, cx: &AsyncApp) {
1599        let sender_id = message.sender_id();
1600        let request_id = message.message_id();
1601        let type_name = message.payload_type_name();
1602        let original_sender_id = message.original_sender_id();
1603
1604        if let Some(future) = ProtoMessageHandlerSet::handle_message(
1605            &self.handler_set,
1606            message,
1607            self.clone().into(),
1608            cx.clone(),
1609        ) {
1610            let client_id = self.id();
1611            log::debug!(
1612                "rpc message received. client_id:{}, sender_id:{:?}, type:{}",
1613                client_id,
1614                original_sender_id,
1615                type_name
1616            );
1617            cx.spawn(async move |_| match future.await {
1618                Ok(()) => {
1619                    log::debug!(
1620                        "rpc message handled. client_id:{}, sender_id:{:?}, type:{}",
1621                        client_id,
1622                        original_sender_id,
1623                        type_name
1624                    );
1625                }
1626                Err(error) => {
1627                    log::error!(
1628                        "error handling message. client_id:{}, sender_id:{:?}, type:{}, error:{:?}",
1629                        client_id,
1630                        original_sender_id,
1631                        type_name,
1632                        error
1633                    );
1634                }
1635            })
1636            .detach();
1637        } else {
1638            log::info!("unhandled message {}", type_name);
1639            self.peer
1640                .respond_with_unhandled_message(sender_id.into(), request_id, type_name)
1641                .log_err();
1642        }
1643    }
1644
1645    pub fn telemetry(&self) -> &Arc<Telemetry> {
1646        &self.telemetry
1647    }
1648}
1649
1650impl ProtoClient for Client {
1651    fn request(
1652        &self,
1653        envelope: proto::Envelope,
1654        request_type: &'static str,
1655    ) -> BoxFuture<'static, Result<proto::Envelope>> {
1656        self.request_dynamic(envelope, request_type).boxed()
1657    }
1658
1659    fn send(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1660        log::debug!("rpc send. client_id:{}, name:{}", self.id(), message_type);
1661        let connection_id = self.connection_id()?;
1662        self.peer.send_dynamic(connection_id, envelope)
1663    }
1664
1665    fn send_response(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1666        log::debug!(
1667            "rpc respond. client_id:{}, name:{}",
1668            self.id(),
1669            message_type
1670        );
1671        let connection_id = self.connection_id()?;
1672        self.peer.send_dynamic(connection_id, envelope)
1673    }
1674
1675    fn message_handler_set(&self) -> &parking_lot::Mutex<ProtoMessageHandlerSet> {
1676        &self.handler_set
1677    }
1678
1679    fn is_via_collab(&self) -> bool {
1680        true
1681    }
1682}
1683
1684/// prefix for the zed:// url scheme
1685pub const ZED_URL_SCHEME: &str = "zed";
1686
1687/// Parses the given link into a Zed link.
1688///
1689/// Returns a [`Some`] containing the unprefixed link if the link is a Zed link.
1690/// Returns [`None`] otherwise.
1691pub fn parse_zed_link<'a>(link: &'a str, cx: &App) -> Option<&'a str> {
1692    let server_url = &ClientSettings::get_global(cx).server_url;
1693    if let Some(stripped) = link
1694        .strip_prefix(server_url)
1695        .and_then(|result| result.strip_prefix('/'))
1696    {
1697        return Some(stripped);
1698    }
1699    if let Some(stripped) = link
1700        .strip_prefix(ZED_URL_SCHEME)
1701        .and_then(|result| result.strip_prefix("://"))
1702    {
1703        return Some(stripped);
1704    }
1705
1706    None
1707}
1708
1709#[cfg(test)]
1710mod tests {
1711    use super::*;
1712    use crate::test::FakeServer;
1713
1714    use clock::FakeSystemClock;
1715    use gpui::{AppContext as _, BackgroundExecutor, TestAppContext};
1716    use http_client::FakeHttpClient;
1717    use parking_lot::Mutex;
1718    use proto::TypedEnvelope;
1719    use settings::SettingsStore;
1720    use std::future;
1721
1722    #[gpui::test(iterations = 10)]
1723    async fn test_reconnection(cx: &mut TestAppContext) {
1724        init_test(cx);
1725        let user_id = 5;
1726        let client = cx.update(|cx| {
1727            Client::new(
1728                Arc::new(FakeSystemClock::new()),
1729                FakeHttpClient::with_404_response(),
1730                cx,
1731            )
1732        });
1733        let server = FakeServer::for_client(user_id, &client, cx).await;
1734        let mut status = client.status();
1735        assert!(matches!(
1736            status.next().await,
1737            Some(Status::Connected { .. })
1738        ));
1739        assert_eq!(server.auth_count(), 1);
1740
1741        server.forbid_connections();
1742        server.disconnect();
1743        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1744
1745        server.allow_connections();
1746        cx.executor().advance_clock(Duration::from_secs(10));
1747        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1748        assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1749
1750        server.forbid_connections();
1751        server.disconnect();
1752        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1753
1754        // Clear cached credentials after authentication fails
1755        server.roll_access_token();
1756        server.allow_connections();
1757        cx.executor().run_until_parked();
1758        cx.executor().advance_clock(Duration::from_secs(10));
1759        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1760        assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1761    }
1762
1763    #[gpui::test(iterations = 10)]
1764    async fn test_connection_timeout(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1765        init_test(cx);
1766        let user_id = 5;
1767        let client = cx.update(|cx| {
1768            Client::new(
1769                Arc::new(FakeSystemClock::new()),
1770                FakeHttpClient::with_404_response(),
1771                cx,
1772            )
1773        });
1774        let mut status = client.status();
1775
1776        // Time out when client tries to connect.
1777        client.override_authenticate(move |cx| {
1778            cx.background_spawn(async move {
1779                Ok(Credentials {
1780                    user_id,
1781                    access_token: "token".into(),
1782                })
1783            })
1784        });
1785        client.override_establish_connection(|_, cx| {
1786            cx.background_spawn(async move {
1787                future::pending::<()>().await;
1788                unreachable!()
1789            })
1790        });
1791        let auth_and_connect = cx.spawn({
1792            let client = client.clone();
1793            |cx| async move { client.authenticate_and_connect(false, &cx).await }
1794        });
1795        executor.run_until_parked();
1796        assert!(matches!(status.next().await, Some(Status::Connecting)));
1797
1798        executor.advance_clock(CONNECTION_TIMEOUT);
1799        assert!(matches!(
1800            status.next().await,
1801            Some(Status::ConnectionError { .. })
1802        ));
1803        auth_and_connect.await.into_response().unwrap_err();
1804
1805        // Allow the connection to be established.
1806        let server = FakeServer::for_client(user_id, &client, cx).await;
1807        assert!(matches!(
1808            status.next().await,
1809            Some(Status::Connected { .. })
1810        ));
1811
1812        // Disconnect client.
1813        server.forbid_connections();
1814        server.disconnect();
1815        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1816
1817        // Time out when re-establishing the connection.
1818        server.allow_connections();
1819        client.override_establish_connection(|_, cx| {
1820            cx.background_spawn(async move {
1821                future::pending::<()>().await;
1822                unreachable!()
1823            })
1824        });
1825        executor.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1826        assert!(matches!(
1827            status.next().await,
1828            Some(Status::Reconnecting { .. })
1829        ));
1830
1831        executor.advance_clock(CONNECTION_TIMEOUT);
1832        assert!(matches!(
1833            status.next().await,
1834            Some(Status::ReconnectionError { .. })
1835        ));
1836    }
1837
1838    #[gpui::test(iterations = 10)]
1839    async fn test_authenticating_more_than_once(
1840        cx: &mut TestAppContext,
1841        executor: BackgroundExecutor,
1842    ) {
1843        init_test(cx);
1844        let auth_count = Arc::new(Mutex::new(0));
1845        let dropped_auth_count = Arc::new(Mutex::new(0));
1846        let client = cx.update(|cx| {
1847            Client::new(
1848                Arc::new(FakeSystemClock::new()),
1849                FakeHttpClient::with_404_response(),
1850                cx,
1851            )
1852        });
1853        client.override_authenticate({
1854            let auth_count = auth_count.clone();
1855            let dropped_auth_count = dropped_auth_count.clone();
1856            move |cx| {
1857                let auth_count = auth_count.clone();
1858                let dropped_auth_count = dropped_auth_count.clone();
1859                cx.background_spawn(async move {
1860                    *auth_count.lock() += 1;
1861                    let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
1862                    future::pending::<()>().await;
1863                    unreachable!()
1864                })
1865            }
1866        });
1867
1868        let _authenticate = cx.spawn({
1869            let client = client.clone();
1870            move |cx| async move { client.authenticate_and_connect(false, &cx).await }
1871        });
1872        executor.run_until_parked();
1873        assert_eq!(*auth_count.lock(), 1);
1874        assert_eq!(*dropped_auth_count.lock(), 0);
1875
1876        let _authenticate = cx.spawn({
1877            let client = client.clone();
1878            |cx| async move { client.authenticate_and_connect(false, &cx).await }
1879        });
1880        executor.run_until_parked();
1881        assert_eq!(*auth_count.lock(), 2);
1882        assert_eq!(*dropped_auth_count.lock(), 1);
1883    }
1884
1885    #[gpui::test]
1886    async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1887        init_test(cx);
1888        let user_id = 5;
1889        let client = cx.update(|cx| {
1890            Client::new(
1891                Arc::new(FakeSystemClock::new()),
1892                FakeHttpClient::with_404_response(),
1893                cx,
1894            )
1895        });
1896        let server = FakeServer::for_client(user_id, &client, cx).await;
1897
1898        let (done_tx1, done_rx1) = smol::channel::unbounded();
1899        let (done_tx2, done_rx2) = smol::channel::unbounded();
1900        AnyProtoClient::from(client.clone()).add_entity_message_handler(
1901            move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::JoinProject>, mut cx| {
1902                match entity.read_with(&mut cx, |entity, _| entity.id).unwrap() {
1903                    1 => done_tx1.try_send(()).unwrap(),
1904                    2 => done_tx2.try_send(()).unwrap(),
1905                    _ => unreachable!(),
1906                }
1907                async { Ok(()) }
1908            },
1909        );
1910        let entity1 = cx.new(|_| TestEntity {
1911            id: 1,
1912            subscription: None,
1913        });
1914        let entity2 = cx.new(|_| TestEntity {
1915            id: 2,
1916            subscription: None,
1917        });
1918        let entity3 = cx.new(|_| TestEntity {
1919            id: 3,
1920            subscription: None,
1921        });
1922
1923        let _subscription1 = client
1924            .subscribe_to_entity(1)
1925            .unwrap()
1926            .set_entity(&entity1, &mut cx.to_async());
1927        let _subscription2 = client
1928            .subscribe_to_entity(2)
1929            .unwrap()
1930            .set_entity(&entity2, &mut cx.to_async());
1931        // Ensure dropping a subscription for the same entity type still allows receiving of
1932        // messages for other entity IDs of the same type.
1933        let subscription3 = client
1934            .subscribe_to_entity(3)
1935            .unwrap()
1936            .set_entity(&entity3, &mut cx.to_async());
1937        drop(subscription3);
1938
1939        server.send(proto::JoinProject {
1940            project_id: 1,
1941            committer_name: None,
1942            committer_email: None,
1943        });
1944        server.send(proto::JoinProject {
1945            project_id: 2,
1946            committer_name: None,
1947            committer_email: None,
1948        });
1949        done_rx1.recv().await.unwrap();
1950        done_rx2.recv().await.unwrap();
1951    }
1952
1953    #[gpui::test]
1954    async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
1955        init_test(cx);
1956        let user_id = 5;
1957        let client = cx.update(|cx| {
1958            Client::new(
1959                Arc::new(FakeSystemClock::new()),
1960                FakeHttpClient::with_404_response(),
1961                cx,
1962            )
1963        });
1964        let server = FakeServer::for_client(user_id, &client, cx).await;
1965
1966        let entity = cx.new(|_| TestEntity::default());
1967        let (done_tx1, _done_rx1) = smol::channel::unbounded();
1968        let (done_tx2, done_rx2) = smol::channel::unbounded();
1969        let subscription1 = client.add_message_handler(
1970            entity.downgrade(),
1971            move |_, _: TypedEnvelope<proto::Ping>, _| {
1972                done_tx1.try_send(()).unwrap();
1973                async { Ok(()) }
1974            },
1975        );
1976        drop(subscription1);
1977        let _subscription2 = client.add_message_handler(
1978            entity.downgrade(),
1979            move |_, _: TypedEnvelope<proto::Ping>, _| {
1980                done_tx2.try_send(()).unwrap();
1981                async { Ok(()) }
1982            },
1983        );
1984        server.send(proto::Ping {});
1985        done_rx2.recv().await.unwrap();
1986    }
1987
1988    #[gpui::test]
1989    async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
1990        init_test(cx);
1991        let user_id = 5;
1992        let client = cx.update(|cx| {
1993            Client::new(
1994                Arc::new(FakeSystemClock::new()),
1995                FakeHttpClient::with_404_response(),
1996                cx,
1997            )
1998        });
1999        let server = FakeServer::for_client(user_id, &client, cx).await;
2000
2001        let entity = cx.new(|_| TestEntity::default());
2002        let (done_tx, done_rx) = smol::channel::unbounded();
2003        let subscription = client.add_message_handler(
2004            entity.clone().downgrade(),
2005            move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::Ping>, mut cx| {
2006                entity
2007                    .update(&mut cx, |entity, _| entity.subscription.take())
2008                    .unwrap();
2009                done_tx.try_send(()).unwrap();
2010                async { Ok(()) }
2011            },
2012        );
2013        entity.update(cx, |entity, _| {
2014            entity.subscription = Some(subscription);
2015        });
2016        server.send(proto::Ping {});
2017        done_rx.recv().await.unwrap();
2018    }
2019
2020    #[derive(Default)]
2021    struct TestEntity {
2022        id: usize,
2023        subscription: Option<Subscription>,
2024    }
2025
2026    fn init_test(cx: &mut TestAppContext) {
2027        cx.update(|cx| {
2028            let settings_store = SettingsStore::test(cx);
2029            cx.set_global(settings_store);
2030            init_settings(cx);
2031        });
2032    }
2033}