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