client.rs

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