client.rs

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