client.rs

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