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