client.rs

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