client.rs

   1#[cfg(any(test, feature = "test-support"))]
   2pub mod test;
   3
   4mod proxy;
   5pub mod telemetry;
   6pub mod user;
   7pub mod zed_urls;
   8
   9use anyhow::{Context as _, Result, anyhow, bail};
  10use async_recursion::async_recursion;
  11use async_tungstenite::tungstenite::{
  12    client::IntoClientRequest,
  13    error::Error as WebsocketError,
  14    http::{HeaderValue, Request, StatusCode},
  15};
  16use chrono::{DateTime, Utc};
  17use clock::SystemClock;
  18use credentials_provider::CredentialsProvider;
  19use futures::{
  20    AsyncReadExt, FutureExt, SinkExt, Stream, StreamExt, TryFutureExt as _, TryStreamExt,
  21    channel::oneshot, future::BoxFuture,
  22};
  23use gpui::{App, AsyncApp, Entity, Global, Task, WeakEntity, actions};
  24use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
  25use parking_lot::RwLock;
  26use postage::watch;
  27use proxy::connect_proxy_stream;
  28use rand::prelude::*;
  29use release_channel::{AppVersion, ReleaseChannel};
  30use rpc::proto::{AnyTypedEnvelope, EnvelopedMessage, PeerId, RequestMessage};
  31use schemars::JsonSchema;
  32use serde::{Deserialize, Serialize};
  33use settings::{Settings, SettingsSources};
  34use std::pin::Pin;
  35use std::{
  36    any::TypeId,
  37    convert::TryFrom,
  38    fmt::Write as _,
  39    future::Future,
  40    marker::PhantomData,
  41    path::PathBuf,
  42    sync::{
  43        Arc, LazyLock, Weak,
  44        atomic::{AtomicU64, Ordering},
  45    },
  46    time::{Duration, Instant},
  47};
  48use telemetry::Telemetry;
  49use thiserror::Error;
  50use tokio::net::TcpStream;
  51use url::Url;
  52use util::{ConnectionResult, ResultExt};
  53
  54pub use rpc::*;
  55pub use telemetry_events::Event;
  56pub use user::*;
  57
  58static ZED_SERVER_URL: LazyLock<Option<String>> =
  59    LazyLock::new(|| std::env::var("ZED_SERVER_URL").ok());
  60static ZED_RPC_URL: LazyLock<Option<String>> = LazyLock::new(|| std::env::var("ZED_RPC_URL").ok());
  61
  62pub static IMPERSONATE_LOGIN: LazyLock<Option<String>> = LazyLock::new(|| {
  63    std::env::var("ZED_IMPERSONATE")
  64        .ok()
  65        .and_then(|s| if s.is_empty() { None } else { Some(s) })
  66});
  67
  68pub static ADMIN_API_TOKEN: LazyLock<Option<String>> = LazyLock::new(|| {
  69    std::env::var("ZED_ADMIN_API_TOKEN")
  70        .ok()
  71        .and_then(|s| if s.is_empty() { None } else { Some(s) })
  72});
  73
  74pub static ZED_APP_PATH: LazyLock<Option<PathBuf>> =
  75    LazyLock::new(|| std::env::var("ZED_APP_PATH").ok().map(PathBuf::from));
  76
  77pub static ZED_ALWAYS_ACTIVE: LazyLock<bool> =
  78    LazyLock::new(|| std::env::var("ZED_ALWAYS_ACTIVE").map_or(false, |e| !e.is_empty()));
  79
  80pub const INITIAL_RECONNECTION_DELAY: Duration = Duration::from_millis(500);
  81pub const MAX_RECONNECTION_DELAY: Duration = Duration::from_secs(10);
  82pub const CONNECTION_TIMEOUT: Duration = Duration::from_secs(20);
  83
  84actions!(
  85    client,
  86    [
  87        /// Signs in to Zed account.
  88        SignIn,
  89        /// Signs out of Zed account.
  90        SignOut,
  91        /// Reconnects to the collaboration server.
  92        Reconnect
  93    ]
  94);
  95
  96#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  97pub struct ClientSettingsContent {
  98    server_url: Option<String>,
  99}
 100
 101#[derive(Deserialize)]
 102pub struct ClientSettings {
 103    pub server_url: String,
 104}
 105
 106impl Settings for ClientSettings {
 107    const KEY: Option<&'static str> = None;
 108
 109    type FileContent = ClientSettingsContent;
 110
 111    fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
 112        let mut result = sources.json_merge::<Self>()?;
 113        if let Some(server_url) = &*ZED_SERVER_URL {
 114            result.server_url.clone_from(server_url)
 115        }
 116        Ok(result)
 117    }
 118
 119    fn import_from_vscode(_vscode: &settings::VsCodeSettings, _current: &mut Self::FileContent) {}
 120}
 121
 122#[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
 123pub struct ProxySettingsContent {
 124    proxy: Option<String>,
 125}
 126
 127#[derive(Deserialize, Default)]
 128pub struct ProxySettings {
 129    pub proxy: Option<String>,
 130}
 131
 132impl Settings for ProxySettings {
 133    const KEY: Option<&'static str> = None;
 134
 135    type FileContent = ProxySettingsContent;
 136
 137    fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
 138        Ok(Self {
 139            proxy: sources
 140                .user
 141                .or(sources.server)
 142                .and_then(|value| value.proxy.clone())
 143                .or(sources.default.proxy.clone()),
 144        })
 145    }
 146
 147    fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
 148        vscode.string_setting("http.proxy", &mut current.proxy);
 149    }
 150}
 151
 152pub fn init_settings(cx: &mut App) {
 153    TelemetrySettings::register(cx);
 154    ClientSettings::register(cx);
 155    ProxySettings::register(cx);
 156}
 157
 158pub fn init(client: &Arc<Client>, cx: &mut App) {
 159    let client = Arc::downgrade(client);
 160    cx.on_action({
 161        let client = client.clone();
 162        move |_: &SignIn, cx| {
 163            if let Some(client) = client.upgrade() {
 164                cx.spawn(
 165                    async move |cx| match client.authenticate_and_connect(true, &cx).await {
 166                        ConnectionResult::Timeout => {
 167                            log::error!("Initial authentication timed out");
 168                        }
 169                        ConnectionResult::ConnectionReset => {
 170                            log::error!("Initial authentication connection reset");
 171                        }
 172                        ConnectionResult::Result(r) => {
 173                            r.log_err();
 174                        }
 175                    },
 176                )
 177                .detach();
 178            }
 179        }
 180    });
 181
 182    cx.on_action({
 183        let client = client.clone();
 184        move |_: &SignOut, cx| {
 185            if let Some(client) = client.upgrade() {
 186                cx.spawn(async move |cx| {
 187                    client.sign_out(&cx).await;
 188                })
 189                .detach();
 190            }
 191        }
 192    });
 193
 194    cx.on_action({
 195        let client = client.clone();
 196        move |_: &Reconnect, cx| {
 197            if let Some(client) = client.upgrade() {
 198                cx.spawn(async move |cx| {
 199                    client.reconnect(&cx);
 200                })
 201                .detach();
 202            }
 203        }
 204    });
 205}
 206
 207struct GlobalClient(Arc<Client>);
 208
 209impl Global for GlobalClient {}
 210
 211pub struct Client {
 212    id: AtomicU64,
 213    peer: Arc<Peer>,
 214    http: Arc<HttpClientWithUrl>,
 215    telemetry: Arc<Telemetry>,
 216    credentials_provider: ClientCredentialsProvider,
 217    state: RwLock<ClientState>,
 218    handler_set: parking_lot::Mutex<ProtoMessageHandlerSet>,
 219
 220    #[allow(clippy::type_complexity)]
 221    #[cfg(any(test, feature = "test-support"))]
 222    authenticate:
 223        RwLock<Option<Box<dyn 'static + Send + Sync + Fn(&AsyncApp) -> Task<Result<Credentials>>>>>,
 224
 225    #[allow(clippy::type_complexity)]
 226    #[cfg(any(test, feature = "test-support"))]
 227    establish_connection: RwLock<
 228        Option<
 229            Box<
 230                dyn 'static
 231                    + Send
 232                    + Sync
 233                    + Fn(
 234                        &Credentials,
 235                        &AsyncApp,
 236                    ) -> Task<Result<Connection, EstablishConnectionError>>,
 237            >,
 238        >,
 239    >,
 240
 241    #[cfg(any(test, feature = "test-support"))]
 242    rpc_url: RwLock<Option<Url>>,
 243}
 244
 245#[derive(Error, Debug)]
 246pub enum EstablishConnectionError {
 247    #[error("upgrade required")]
 248    UpgradeRequired,
 249    #[error("unauthorized")]
 250    Unauthorized,
 251    #[error("{0}")]
 252    Other(#[from] anyhow::Error),
 253    #[error("{0}")]
 254    InvalidHeaderValue(#[from] async_tungstenite::tungstenite::http::header::InvalidHeaderValue),
 255    #[error("{0}")]
 256    Io(#[from] std::io::Error),
 257    #[error("{0}")]
 258    Websocket(#[from] async_tungstenite::tungstenite::http::Error),
 259}
 260
 261impl From<WebsocketError> for EstablishConnectionError {
 262    fn from(error: WebsocketError) -> Self {
 263        if let WebsocketError::Http(response) = &error {
 264            match response.status() {
 265                StatusCode::UNAUTHORIZED => return EstablishConnectionError::Unauthorized,
 266                StatusCode::UPGRADE_REQUIRED => return EstablishConnectionError::UpgradeRequired,
 267                _ => {}
 268            }
 269        }
 270        EstablishConnectionError::Other(error.into())
 271    }
 272}
 273
 274impl EstablishConnectionError {
 275    pub fn other(error: impl Into<anyhow::Error> + Send + Sync) -> Self {
 276        Self::Other(error.into())
 277    }
 278}
 279
 280#[derive(Copy, Clone, Debug, PartialEq)]
 281pub enum Status {
 282    SignedOut,
 283    UpgradeRequired,
 284    Authenticating,
 285    Connecting,
 286    ConnectionError,
 287    Connected {
 288        peer_id: PeerId,
 289        connection_id: ConnectionId,
 290    },
 291    ConnectionLost,
 292    Reauthenticating,
 293    Reconnecting,
 294    ReconnectionError {
 295        next_reconnection: Instant,
 296    },
 297}
 298
 299impl Status {
 300    pub fn is_connected(&self) -> bool {
 301        matches!(self, Self::Connected { .. })
 302    }
 303
 304    pub fn is_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 credentials = credentials.clone();
1127        let rpc_url = self.rpc_url(http, release_channel);
1128        let system_id = self.telemetry.system_id();
1129        let metrics_id = self.telemetry.metrics_id();
1130        cx.spawn(async move |cx| {
1131            use HttpOrHttps::*;
1132
1133            #[derive(Debug)]
1134            enum HttpOrHttps {
1135                Http,
1136                Https,
1137            }
1138
1139            let mut rpc_url = rpc_url.await?;
1140            let url_scheme = match rpc_url.scheme() {
1141                "https" => Https,
1142                "http" => Http,
1143                _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1144            };
1145            let rpc_host = rpc_url
1146                .host_str()
1147                .zip(rpc_url.port_or_known_default())
1148                .context("missing host in rpc url")?;
1149
1150            let stream = {
1151                let handle = cx.update(|cx| gpui_tokio::Tokio::handle(cx)).ok().unwrap();
1152                let _guard = handle.enter();
1153                match proxy {
1154                    Some(proxy) => connect_proxy_stream(&proxy, rpc_host).await?,
1155                    None => Box::new(TcpStream::connect(rpc_host).await?),
1156                }
1157            };
1158
1159            log::info!("connected to rpc endpoint {}", rpc_url);
1160
1161            rpc_url
1162                .set_scheme(match url_scheme {
1163                    Https => "wss",
1164                    Http => "ws",
1165                })
1166                .unwrap();
1167
1168            // We call `into_client_request` to let `tungstenite` construct the WebSocket request
1169            // for us from the RPC URL.
1170            //
1171            // Among other things, it will generate and set a `Sec-WebSocket-Key` header for us.
1172            let mut request = IntoClientRequest::into_client_request(rpc_url.as_str())?;
1173
1174            // We then modify the request to add our desired headers.
1175            let request_headers = request.headers_mut();
1176            request_headers.insert(
1177                "Authorization",
1178                HeaderValue::from_str(&credentials.authorization_header())?,
1179            );
1180            request_headers.insert(
1181                "x-zed-protocol-version",
1182                HeaderValue::from_str(&rpc::PROTOCOL_VERSION.to_string())?,
1183            );
1184            request_headers.insert("x-zed-app-version", HeaderValue::from_str(&app_version)?);
1185            request_headers.insert(
1186                "x-zed-release-channel",
1187                HeaderValue::from_str(release_channel.map(|r| r.dev_name()).unwrap_or("unknown"))?,
1188            );
1189            if let Some(system_id) = system_id {
1190                request_headers.insert("x-zed-system-id", HeaderValue::from_str(&system_id)?);
1191            }
1192            if let Some(metrics_id) = metrics_id {
1193                request_headers.insert("x-zed-metrics-id", HeaderValue::from_str(&metrics_id)?);
1194            }
1195
1196            let (stream, _) = async_tungstenite::tokio::client_async_tls_with_connector_and_config(
1197                request,
1198                stream,
1199                Some(Arc::new(http_client_tls::tls_config()).into()),
1200                None,
1201            )
1202            .await?;
1203
1204            Ok(Connection::new(
1205                stream
1206                    .map_err(|error| anyhow!(error))
1207                    .sink_map_err(|error| anyhow!(error)),
1208            ))
1209        })
1210    }
1211
1212    pub fn authenticate_with_browser(self: &Arc<Self>, cx: &AsyncApp) -> Task<Result<Credentials>> {
1213        let http = self.http.clone();
1214        let this = self.clone();
1215        cx.spawn(async move |cx| {
1216            let background = cx.background_executor().clone();
1217
1218            let (open_url_tx, open_url_rx) = oneshot::channel::<String>();
1219            cx.update(|cx| {
1220                cx.spawn(async move |cx| {
1221                    let url = open_url_rx.await?;
1222                    cx.update(|cx| cx.open_url(&url))
1223                })
1224                .detach_and_log_err(cx);
1225            })
1226            .log_err();
1227
1228            let credentials = background
1229                .clone()
1230                .spawn(async move {
1231                    // Generate a pair of asymmetric encryption keys. The public key will be used by the
1232                    // zed server to encrypt the user's access token, so that it can'be intercepted by
1233                    // any other app running on the user's device.
1234                    let (public_key, private_key) =
1235                        rpc::auth::keypair().expect("failed to generate keypair for auth");
1236                    let public_key_string = String::try_from(public_key)
1237                        .expect("failed to serialize public key for auth");
1238
1239                    if let Some((login, token)) =
1240                        IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref())
1241                    {
1242                        eprintln!("authenticate as admin {login}, {token}");
1243
1244                        return this
1245                            .authenticate_as_admin(http, login.clone(), token.clone())
1246                            .await;
1247                    }
1248
1249                    // Start an HTTP server to receive the redirect from Zed's sign-in page.
1250                    let server =
1251                        tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1252                    let port = server.server_addr().port();
1253
1254                    // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1255                    // that the user is signing in from a Zed app running on the same device.
1256                    let mut url = http.build_url(&format!(
1257                        "/native_app_signin?native_app_port={}&native_app_public_key={}",
1258                        port, public_key_string
1259                    ));
1260
1261                    if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1262                        log::info!("impersonating user @{}", impersonate_login);
1263                        write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1264                    }
1265
1266                    open_url_tx.send(url).log_err();
1267
1268                    // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1269                    // access token from the query params.
1270                    //
1271                    // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1272                    // custom URL scheme instead of this local HTTP server.
1273                    let (user_id, access_token) = background
1274                        .spawn(async move {
1275                            for _ in 0..100 {
1276                                if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1277                                    let path = req.url();
1278                                    let mut user_id = None;
1279                                    let mut access_token = None;
1280                                    let url = Url::parse(&format!("http://example.com{}", path))
1281                                        .context("failed to parse login notification url")?;
1282                                    for (key, value) in url.query_pairs() {
1283                                        if key == "access_token" {
1284                                            access_token = Some(value.to_string());
1285                                        } else if key == "user_id" {
1286                                            user_id = Some(value.to_string());
1287                                        }
1288                                    }
1289
1290                                    let post_auth_url =
1291                                        http.build_url("/native_app_signin_succeeded");
1292                                    req.respond(
1293                                        tiny_http::Response::empty(302).with_header(
1294                                            tiny_http::Header::from_bytes(
1295                                                &b"Location"[..],
1296                                                post_auth_url.as_bytes(),
1297                                            )
1298                                            .unwrap(),
1299                                        ),
1300                                    )
1301                                    .context("failed to respond to login http request")?;
1302                                    return Ok((
1303                                        user_id.context("missing user_id parameter")?,
1304                                        access_token.context("missing access_token parameter")?,
1305                                    ));
1306                                }
1307                            }
1308
1309                            anyhow::bail!("didn't receive login redirect");
1310                        })
1311                        .await?;
1312
1313                    let access_token = private_key
1314                        .decrypt_string(&access_token)
1315                        .context("failed to decrypt access token")?;
1316
1317                    Ok(Credentials {
1318                        user_id: user_id.parse()?,
1319                        access_token,
1320                    })
1321                })
1322                .await?;
1323
1324            cx.update(|cx| cx.activate(true))?;
1325            Ok(credentials)
1326        })
1327    }
1328
1329    async fn authenticate_as_admin(
1330        self: &Arc<Self>,
1331        http: Arc<HttpClientWithUrl>,
1332        login: String,
1333        mut api_token: String,
1334    ) -> Result<Credentials> {
1335        #[derive(Deserialize)]
1336        struct AuthenticatedUserResponse {
1337            user: User,
1338        }
1339
1340        #[derive(Deserialize)]
1341        struct User {
1342            id: u64,
1343        }
1344
1345        let github_user = {
1346            #[derive(Deserialize)]
1347            struct GithubUser {
1348                id: i32,
1349                login: String,
1350                created_at: DateTime<Utc>,
1351            }
1352
1353            let request = {
1354                let mut request_builder =
1355                    Request::get(&format!("https://api.github.com/users/{login}"));
1356                if let Ok(github_token) = std::env::var("GITHUB_TOKEN") {
1357                    request_builder =
1358                        request_builder.header("Authorization", format!("Bearer {}", github_token));
1359                }
1360
1361                request_builder.body(AsyncBody::empty())?
1362            };
1363
1364            let mut response = http
1365                .send(request)
1366                .await
1367                .context("error fetching GitHub user")?;
1368
1369            let mut body = Vec::new();
1370            response
1371                .body_mut()
1372                .read_to_end(&mut body)
1373                .await
1374                .context("error reading GitHub user")?;
1375
1376            if !response.status().is_success() {
1377                let text = String::from_utf8_lossy(body.as_slice());
1378                bail!(
1379                    "status error {}, response: {text:?}",
1380                    response.status().as_u16()
1381                );
1382            }
1383
1384            serde_json::from_slice::<GithubUser>(body.as_slice()).map_err(|err| {
1385                log::error!("Error deserializing: {:?}", err);
1386                log::error!(
1387                    "GitHub API response text: {:?}",
1388                    String::from_utf8_lossy(body.as_slice())
1389                );
1390                anyhow!("error deserializing GitHub user")
1391            })?
1392        };
1393
1394        let query_params = [
1395            ("github_login", &github_user.login),
1396            ("github_user_id", &github_user.id.to_string()),
1397            (
1398                "github_user_created_at",
1399                &github_user.created_at.to_rfc3339(),
1400            ),
1401        ];
1402
1403        // Use the collab server's admin API to retrieve the ID
1404        // of the impersonated user.
1405        let mut url = self.rpc_url(http.clone(), None).await?;
1406        url.set_path("/user");
1407        url.set_query(Some(
1408            &query_params
1409                .iter()
1410                .map(|(key, value)| {
1411                    format!(
1412                        "{}={}",
1413                        key,
1414                        url::form_urlencoded::byte_serialize(value.as_bytes()).collect::<String>()
1415                    )
1416                })
1417                .collect::<Vec<String>>()
1418                .join("&"),
1419        ));
1420        let request: http_client::Request<AsyncBody> = Request::get(url.as_str())
1421            .header("Authorization", format!("token {api_token}"))
1422            .body("".into())?;
1423
1424        let mut response = http.send(request).await?;
1425        let mut body = String::new();
1426        response.body_mut().read_to_string(&mut body).await?;
1427        anyhow::ensure!(
1428            response.status().is_success(),
1429            "admin user request failed {} - {}",
1430            response.status().as_u16(),
1431            body,
1432        );
1433        let response: AuthenticatedUserResponse = serde_json::from_str(&body)?;
1434
1435        // Use the admin API token to authenticate as the impersonated user.
1436        api_token.insert_str(0, "ADMIN_TOKEN:");
1437        Ok(Credentials {
1438            user_id: response.user.id,
1439            access_token: api_token,
1440        })
1441    }
1442
1443    pub async fn sign_out(self: &Arc<Self>, cx: &AsyncApp) {
1444        self.state.write().credentials = None;
1445        self.disconnect(cx);
1446
1447        if self.has_credentials(cx).await {
1448            self.credentials_provider
1449                .delete_credentials(cx)
1450                .await
1451                .log_err();
1452        }
1453    }
1454
1455    pub fn disconnect(self: &Arc<Self>, cx: &AsyncApp) {
1456        self.peer.teardown();
1457        self.set_status(Status::SignedOut, cx);
1458    }
1459
1460    pub fn reconnect(self: &Arc<Self>, cx: &AsyncApp) {
1461        self.peer.teardown();
1462        self.set_status(Status::ConnectionLost, cx);
1463    }
1464
1465    fn connection_id(&self) -> Result<ConnectionId> {
1466        if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1467            Ok(connection_id)
1468        } else {
1469            anyhow::bail!("not connected");
1470        }
1471    }
1472
1473    pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1474        log::debug!("rpc send. client_id:{}, name:{}", self.id(), T::NAME);
1475        self.peer.send(self.connection_id()?, message)
1476    }
1477
1478    pub fn request<T: RequestMessage>(
1479        &self,
1480        request: T,
1481    ) -> impl Future<Output = Result<T::Response>> + use<T> {
1482        self.request_envelope(request)
1483            .map_ok(|envelope| envelope.payload)
1484    }
1485
1486    pub fn request_stream<T: RequestMessage>(
1487        &self,
1488        request: T,
1489    ) -> impl Future<Output = Result<impl Stream<Item = Result<T::Response>>>> {
1490        let client_id = self.id.load(Ordering::SeqCst);
1491        log::debug!(
1492            "rpc request start. client_id:{}. name:{}",
1493            client_id,
1494            T::NAME
1495        );
1496        let response = self
1497            .connection_id()
1498            .map(|conn_id| self.peer.request_stream(conn_id, request));
1499        async move {
1500            let response = response?.await;
1501            log::debug!(
1502                "rpc request finish. client_id:{}. name:{}",
1503                client_id,
1504                T::NAME
1505            );
1506            response
1507        }
1508    }
1509
1510    pub fn request_envelope<T: RequestMessage>(
1511        &self,
1512        request: T,
1513    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> + use<T> {
1514        let client_id = self.id();
1515        log::debug!(
1516            "rpc request start. client_id:{}. name:{}",
1517            client_id,
1518            T::NAME
1519        );
1520        let response = self
1521            .connection_id()
1522            .map(|conn_id| self.peer.request_envelope(conn_id, request));
1523        async move {
1524            let response = response?.await;
1525            log::debug!(
1526                "rpc request finish. client_id:{}. name:{}",
1527                client_id,
1528                T::NAME
1529            );
1530            response
1531        }
1532    }
1533
1534    pub fn request_dynamic(
1535        &self,
1536        envelope: proto::Envelope,
1537        request_type: &'static str,
1538    ) -> impl Future<Output = Result<proto::Envelope>> + use<> {
1539        let client_id = self.id();
1540        log::debug!(
1541            "rpc request start. client_id:{}. name:{}",
1542            client_id,
1543            request_type
1544        );
1545        let response = self
1546            .connection_id()
1547            .map(|conn_id| self.peer.request_dynamic(conn_id, envelope, request_type));
1548        async move {
1549            let response = response?.await;
1550            log::debug!(
1551                "rpc request finish. client_id:{}. name:{}",
1552                client_id,
1553                request_type
1554            );
1555            Ok(response?.0)
1556        }
1557    }
1558
1559    fn handle_message(self: &Arc<Client>, message: Box<dyn AnyTypedEnvelope>, cx: &AsyncApp) {
1560        let sender_id = message.sender_id();
1561        let request_id = message.message_id();
1562        let type_name = message.payload_type_name();
1563        let original_sender_id = message.original_sender_id();
1564
1565        if let Some(future) = ProtoMessageHandlerSet::handle_message(
1566            &self.handler_set,
1567            message,
1568            self.clone().into(),
1569            cx.clone(),
1570        ) {
1571            let client_id = self.id();
1572            log::debug!(
1573                "rpc message received. client_id:{}, sender_id:{:?}, type:{}",
1574                client_id,
1575                original_sender_id,
1576                type_name
1577            );
1578            cx.spawn(async move |_| match future.await {
1579                Ok(()) => {
1580                    log::debug!(
1581                        "rpc message handled. client_id:{}, sender_id:{:?}, type:{}",
1582                        client_id,
1583                        original_sender_id,
1584                        type_name
1585                    );
1586                }
1587                Err(error) => {
1588                    log::error!(
1589                        "error handling message. client_id:{}, sender_id:{:?}, type:{}, error:{:?}",
1590                        client_id,
1591                        original_sender_id,
1592                        type_name,
1593                        error
1594                    );
1595                }
1596            })
1597            .detach();
1598        } else {
1599            log::info!("unhandled message {}", type_name);
1600            self.peer
1601                .respond_with_unhandled_message(sender_id.into(), request_id, type_name)
1602                .log_err();
1603        }
1604    }
1605
1606    pub fn telemetry(&self) -> &Arc<Telemetry> {
1607        &self.telemetry
1608    }
1609}
1610
1611impl ProtoClient for Client {
1612    fn request(
1613        &self,
1614        envelope: proto::Envelope,
1615        request_type: &'static str,
1616    ) -> BoxFuture<'static, Result<proto::Envelope>> {
1617        self.request_dynamic(envelope, request_type).boxed()
1618    }
1619
1620    fn send(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1621        log::debug!("rpc send. client_id:{}, name:{}", self.id(), message_type);
1622        let connection_id = self.connection_id()?;
1623        self.peer.send_dynamic(connection_id, envelope)
1624    }
1625
1626    fn send_response(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1627        log::debug!(
1628            "rpc respond. client_id:{}, name:{}",
1629            self.id(),
1630            message_type
1631        );
1632        let connection_id = self.connection_id()?;
1633        self.peer.send_dynamic(connection_id, envelope)
1634    }
1635
1636    fn message_handler_set(&self) -> &parking_lot::Mutex<ProtoMessageHandlerSet> {
1637        &self.handler_set
1638    }
1639
1640    fn is_via_collab(&self) -> bool {
1641        true
1642    }
1643}
1644
1645/// prefix for the zed:// url scheme
1646pub const ZED_URL_SCHEME: &str = "zed";
1647
1648/// Parses the given link into a Zed link.
1649///
1650/// Returns a [`Some`] containing the unprefixed link if the link is a Zed link.
1651/// Returns [`None`] otherwise.
1652pub fn parse_zed_link<'a>(link: &'a str, cx: &App) -> Option<&'a str> {
1653    let server_url = &ClientSettings::get_global(cx).server_url;
1654    if let Some(stripped) = link
1655        .strip_prefix(server_url)
1656        .and_then(|result| result.strip_prefix('/'))
1657    {
1658        return Some(stripped);
1659    }
1660    if let Some(stripped) = link
1661        .strip_prefix(ZED_URL_SCHEME)
1662        .and_then(|result| result.strip_prefix("://"))
1663    {
1664        return Some(stripped);
1665    }
1666
1667    None
1668}
1669
1670#[cfg(test)]
1671mod tests {
1672    use super::*;
1673    use crate::test::FakeServer;
1674
1675    use clock::FakeSystemClock;
1676    use gpui::{AppContext as _, BackgroundExecutor, TestAppContext};
1677    use http_client::FakeHttpClient;
1678    use parking_lot::Mutex;
1679    use proto::TypedEnvelope;
1680    use settings::SettingsStore;
1681    use std::future;
1682
1683    #[gpui::test(iterations = 10)]
1684    async fn test_reconnection(cx: &mut TestAppContext) {
1685        init_test(cx);
1686        let user_id = 5;
1687        let client = cx.update(|cx| {
1688            Client::new(
1689                Arc::new(FakeSystemClock::new()),
1690                FakeHttpClient::with_404_response(),
1691                cx,
1692            )
1693        });
1694        let server = FakeServer::for_client(user_id, &client, cx).await;
1695        let mut status = client.status();
1696        assert!(matches!(
1697            status.next().await,
1698            Some(Status::Connected { .. })
1699        ));
1700        assert_eq!(server.auth_count(), 1);
1701
1702        server.forbid_connections();
1703        server.disconnect();
1704        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1705
1706        server.allow_connections();
1707        cx.executor().advance_clock(Duration::from_secs(10));
1708        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1709        assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1710
1711        server.forbid_connections();
1712        server.disconnect();
1713        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1714
1715        // Clear cached credentials after authentication fails
1716        server.roll_access_token();
1717        server.allow_connections();
1718        cx.executor().run_until_parked();
1719        cx.executor().advance_clock(Duration::from_secs(10));
1720        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1721        assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1722    }
1723
1724    #[gpui::test(iterations = 10)]
1725    async fn test_connection_timeout(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1726        init_test(cx);
1727        let user_id = 5;
1728        let client = cx.update(|cx| {
1729            Client::new(
1730                Arc::new(FakeSystemClock::new()),
1731                FakeHttpClient::with_404_response(),
1732                cx,
1733            )
1734        });
1735        let mut status = client.status();
1736
1737        // Time out when client tries to connect.
1738        client.override_authenticate(move |cx| {
1739            cx.background_spawn(async move {
1740                Ok(Credentials {
1741                    user_id,
1742                    access_token: "token".into(),
1743                })
1744            })
1745        });
1746        client.override_establish_connection(|_, cx| {
1747            cx.background_spawn(async move {
1748                future::pending::<()>().await;
1749                unreachable!()
1750            })
1751        });
1752        let auth_and_connect = cx.spawn({
1753            let client = client.clone();
1754            |cx| async move { client.authenticate_and_connect(false, &cx).await }
1755        });
1756        executor.run_until_parked();
1757        assert!(matches!(status.next().await, Some(Status::Connecting)));
1758
1759        executor.advance_clock(CONNECTION_TIMEOUT);
1760        assert!(matches!(
1761            status.next().await,
1762            Some(Status::ConnectionError { .. })
1763        ));
1764        auth_and_connect.await.into_response().unwrap_err();
1765
1766        // Allow the connection to be established.
1767        let server = FakeServer::for_client(user_id, &client, cx).await;
1768        assert!(matches!(
1769            status.next().await,
1770            Some(Status::Connected { .. })
1771        ));
1772
1773        // Disconnect client.
1774        server.forbid_connections();
1775        server.disconnect();
1776        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1777
1778        // Time out when re-establishing the connection.
1779        server.allow_connections();
1780        client.override_establish_connection(|_, cx| {
1781            cx.background_spawn(async move {
1782                future::pending::<()>().await;
1783                unreachable!()
1784            })
1785        });
1786        executor.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1787        assert!(matches!(
1788            status.next().await,
1789            Some(Status::Reconnecting { .. })
1790        ));
1791
1792        executor.advance_clock(CONNECTION_TIMEOUT);
1793        assert!(matches!(
1794            status.next().await,
1795            Some(Status::ReconnectionError { .. })
1796        ));
1797    }
1798
1799    #[gpui::test(iterations = 10)]
1800    async fn test_authenticating_more_than_once(
1801        cx: &mut TestAppContext,
1802        executor: BackgroundExecutor,
1803    ) {
1804        init_test(cx);
1805        let auth_count = Arc::new(Mutex::new(0));
1806        let dropped_auth_count = Arc::new(Mutex::new(0));
1807        let client = cx.update(|cx| {
1808            Client::new(
1809                Arc::new(FakeSystemClock::new()),
1810                FakeHttpClient::with_404_response(),
1811                cx,
1812            )
1813        });
1814        client.override_authenticate({
1815            let auth_count = auth_count.clone();
1816            let dropped_auth_count = dropped_auth_count.clone();
1817            move |cx| {
1818                let auth_count = auth_count.clone();
1819                let dropped_auth_count = dropped_auth_count.clone();
1820                cx.background_spawn(async move {
1821                    *auth_count.lock() += 1;
1822                    let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
1823                    future::pending::<()>().await;
1824                    unreachable!()
1825                })
1826            }
1827        });
1828
1829        let _authenticate = cx.spawn({
1830            let client = client.clone();
1831            move |cx| async move { client.authenticate_and_connect(false, &cx).await }
1832        });
1833        executor.run_until_parked();
1834        assert_eq!(*auth_count.lock(), 1);
1835        assert_eq!(*dropped_auth_count.lock(), 0);
1836
1837        let _authenticate = cx.spawn({
1838            let client = client.clone();
1839            |cx| async move { client.authenticate_and_connect(false, &cx).await }
1840        });
1841        executor.run_until_parked();
1842        assert_eq!(*auth_count.lock(), 2);
1843        assert_eq!(*dropped_auth_count.lock(), 1);
1844    }
1845
1846    #[gpui::test]
1847    async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1848        init_test(cx);
1849        let user_id = 5;
1850        let client = cx.update(|cx| {
1851            Client::new(
1852                Arc::new(FakeSystemClock::new()),
1853                FakeHttpClient::with_404_response(),
1854                cx,
1855            )
1856        });
1857        let server = FakeServer::for_client(user_id, &client, cx).await;
1858
1859        let (done_tx1, done_rx1) = smol::channel::unbounded();
1860        let (done_tx2, done_rx2) = smol::channel::unbounded();
1861        AnyProtoClient::from(client.clone()).add_entity_message_handler(
1862            move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::JoinProject>, mut cx| {
1863                match entity.read_with(&mut cx, |entity, _| entity.id).unwrap() {
1864                    1 => done_tx1.try_send(()).unwrap(),
1865                    2 => done_tx2.try_send(()).unwrap(),
1866                    _ => unreachable!(),
1867                }
1868                async { Ok(()) }
1869            },
1870        );
1871        let entity1 = cx.new(|_| TestEntity {
1872            id: 1,
1873            subscription: None,
1874        });
1875        let entity2 = cx.new(|_| TestEntity {
1876            id: 2,
1877            subscription: None,
1878        });
1879        let entity3 = cx.new(|_| TestEntity {
1880            id: 3,
1881            subscription: None,
1882        });
1883
1884        let _subscription1 = client
1885            .subscribe_to_entity(1)
1886            .unwrap()
1887            .set_entity(&entity1, &mut cx.to_async());
1888        let _subscription2 = client
1889            .subscribe_to_entity(2)
1890            .unwrap()
1891            .set_entity(&entity2, &mut cx.to_async());
1892        // Ensure dropping a subscription for the same entity type still allows receiving of
1893        // messages for other entity IDs of the same type.
1894        let subscription3 = client
1895            .subscribe_to_entity(3)
1896            .unwrap()
1897            .set_entity(&entity3, &mut cx.to_async());
1898        drop(subscription3);
1899
1900        server.send(proto::JoinProject {
1901            project_id: 1,
1902            committer_name: None,
1903            committer_email: None,
1904        });
1905        server.send(proto::JoinProject {
1906            project_id: 2,
1907            committer_name: None,
1908            committer_email: None,
1909        });
1910        done_rx1.recv().await.unwrap();
1911        done_rx2.recv().await.unwrap();
1912    }
1913
1914    #[gpui::test]
1915    async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
1916        init_test(cx);
1917        let user_id = 5;
1918        let client = cx.update(|cx| {
1919            Client::new(
1920                Arc::new(FakeSystemClock::new()),
1921                FakeHttpClient::with_404_response(),
1922                cx,
1923            )
1924        });
1925        let server = FakeServer::for_client(user_id, &client, cx).await;
1926
1927        let entity = cx.new(|_| TestEntity::default());
1928        let (done_tx1, _done_rx1) = smol::channel::unbounded();
1929        let (done_tx2, done_rx2) = smol::channel::unbounded();
1930        let subscription1 = client.add_message_handler(
1931            entity.downgrade(),
1932            move |_, _: TypedEnvelope<proto::Ping>, _| {
1933                done_tx1.try_send(()).unwrap();
1934                async { Ok(()) }
1935            },
1936        );
1937        drop(subscription1);
1938        let _subscription2 = client.add_message_handler(
1939            entity.downgrade(),
1940            move |_, _: TypedEnvelope<proto::Ping>, _| {
1941                done_tx2.try_send(()).unwrap();
1942                async { Ok(()) }
1943            },
1944        );
1945        server.send(proto::Ping {});
1946        done_rx2.recv().await.unwrap();
1947    }
1948
1949    #[gpui::test]
1950    async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
1951        init_test(cx);
1952        let user_id = 5;
1953        let client = cx.update(|cx| {
1954            Client::new(
1955                Arc::new(FakeSystemClock::new()),
1956                FakeHttpClient::with_404_response(),
1957                cx,
1958            )
1959        });
1960        let server = FakeServer::for_client(user_id, &client, cx).await;
1961
1962        let entity = cx.new(|_| TestEntity::default());
1963        let (done_tx, done_rx) = smol::channel::unbounded();
1964        let subscription = client.add_message_handler(
1965            entity.clone().downgrade(),
1966            move |entity: Entity<TestEntity>, _: TypedEnvelope<proto::Ping>, mut cx| {
1967                entity
1968                    .update(&mut cx, |entity, _| entity.subscription.take())
1969                    .unwrap();
1970                done_tx.try_send(()).unwrap();
1971                async { Ok(()) }
1972            },
1973        );
1974        entity.update(cx, |entity, _| {
1975            entity.subscription = Some(subscription);
1976        });
1977        server.send(proto::Ping {});
1978        done_rx.recv().await.unwrap();
1979    }
1980
1981    #[derive(Default)]
1982    struct TestEntity {
1983        id: usize,
1984        subscription: Option<Subscription>,
1985    }
1986
1987    fn init_test(cx: &mut TestAppContext) {
1988        cx.update(|cx| {
1989            let settings_store = SettingsStore::test(cx);
1990            cx.set_global(settings_store);
1991            init_settings(cx);
1992        });
1993    }
1994}