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