client.rs

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