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>> {
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 = rpc_url.into_client_request()?;
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 client_config = {
1141                        let mut root_store = rustls::RootCertStore::empty();
1142
1143                        let root_certs = rustls_native_certs::load_native_certs();
1144                        for error in root_certs.errors {
1145                            log::warn!("error loading native certs: {:?}", error);
1146                        }
1147                        root_store.add_parsable_certificates(
1148                            &root_certs
1149                                .certs
1150                                .into_iter()
1151                                .map(|cert| cert.as_ref().to_owned())
1152                                .collect::<Vec<_>>(),
1153                        );
1154                        rustls::ClientConfig::builder()
1155                            .with_safe_defaults()
1156                            .with_root_certificates(root_store)
1157                            .with_no_client_auth()
1158                    };
1159                    let (stream, _) =
1160                        async_tungstenite::async_tls::client_async_tls_with_connector(
1161                            request,
1162                            stream,
1163                            Some(client_config.into()),
1164                        )
1165                        .await?;
1166                    Ok(Connection::new(
1167                        stream
1168                            .map_err(|error| anyhow!(error))
1169                            .sink_map_err(|error| anyhow!(error)),
1170                    ))
1171                }
1172                Http => {
1173                    let (stream, _) = async_tungstenite::client_async(request, stream).await?;
1174                    Ok(Connection::new(
1175                        stream
1176                            .map_err(|error| anyhow!(error))
1177                            .sink_map_err(|error| anyhow!(error)),
1178                    ))
1179                }
1180            }
1181        })
1182    }
1183
1184    pub fn authenticate_with_browser(
1185        self: &Arc<Self>,
1186        cx: &AsyncAppContext,
1187    ) -> Task<Result<Credentials>> {
1188        let http = self.http.clone();
1189        let this = self.clone();
1190        cx.spawn(|cx| async move {
1191            let background = cx.background_executor().clone();
1192
1193            let (open_url_tx, open_url_rx) = oneshot::channel::<String>();
1194            cx.update(|cx| {
1195                cx.spawn(move |cx| async move {
1196                    let url = open_url_rx.await?;
1197                    cx.update(|cx| cx.open_url(&url))
1198                })
1199                .detach_and_log_err(cx);
1200            })
1201            .log_err();
1202
1203            let credentials = background
1204                .clone()
1205                .spawn(async move {
1206                    // Generate a pair of asymmetric encryption keys. The public key will be used by the
1207                    // zed server to encrypt the user's access token, so that it can'be intercepted by
1208                    // any other app running on the user's device.
1209                    let (public_key, private_key) =
1210                        rpc::auth::keypair().expect("failed to generate keypair for auth");
1211                    let public_key_string = String::try_from(public_key)
1212                        .expect("failed to serialize public key for auth");
1213
1214                    if let Some((login, token)) =
1215                        IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref())
1216                    {
1217                        eprintln!("authenticate as admin {login}, {token}");
1218
1219                        return this
1220                            .authenticate_as_admin(http, login.clone(), token.clone())
1221                            .await;
1222                    }
1223
1224                    // Start an HTTP server to receive the redirect from Zed's sign-in page.
1225                    let server =
1226                        tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1227                    let port = server.server_addr().port();
1228
1229                    // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1230                    // that the user is signing in from a Zed app running on the same device.
1231                    let mut url = http.build_url(&format!(
1232                        "/native_app_signin?native_app_port={}&native_app_public_key={}",
1233                        port, public_key_string
1234                    ));
1235
1236                    if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1237                        log::info!("impersonating user @{}", impersonate_login);
1238                        write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1239                    }
1240
1241                    open_url_tx.send(url).log_err();
1242
1243                    // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1244                    // access token from the query params.
1245                    //
1246                    // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1247                    // custom URL scheme instead of this local HTTP server.
1248                    let (user_id, access_token) = background
1249                        .spawn(async move {
1250                            for _ in 0..100 {
1251                                if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1252                                    let path = req.url();
1253                                    let mut user_id = None;
1254                                    let mut access_token = None;
1255                                    let url = Url::parse(&format!("http://example.com{}", path))
1256                                        .context("failed to parse login notification url")?;
1257                                    for (key, value) in url.query_pairs() {
1258                                        if key == "access_token" {
1259                                            access_token = Some(value.to_string());
1260                                        } else if key == "user_id" {
1261                                            user_id = Some(value.to_string());
1262                                        }
1263                                    }
1264
1265                                    let post_auth_url =
1266                                        http.build_url("/native_app_signin_succeeded");
1267                                    req.respond(
1268                                        tiny_http::Response::empty(302).with_header(
1269                                            tiny_http::Header::from_bytes(
1270                                                &b"Location"[..],
1271                                                post_auth_url.as_bytes(),
1272                                            )
1273                                            .unwrap(),
1274                                        ),
1275                                    )
1276                                    .context("failed to respond to login http request")?;
1277                                    return Ok((
1278                                        user_id
1279                                            .ok_or_else(|| anyhow!("missing user_id parameter"))?,
1280                                        access_token.ok_or_else(|| {
1281                                            anyhow!("missing access_token parameter")
1282                                        })?,
1283                                    ));
1284                                }
1285                            }
1286
1287                            Err(anyhow!("didn't receive login redirect"))
1288                        })
1289                        .await?;
1290
1291                    let access_token = private_key
1292                        .decrypt_string(&access_token)
1293                        .context("failed to decrypt access token")?;
1294
1295                    Ok(Credentials::User {
1296                        user_id: user_id.parse()?,
1297                        access_token,
1298                    })
1299                })
1300                .await?;
1301
1302            cx.update(|cx| cx.activate(true))?;
1303            Ok(credentials)
1304        })
1305    }
1306
1307    async fn authenticate_as_admin(
1308        self: &Arc<Self>,
1309        http: Arc<HttpClientWithUrl>,
1310        login: String,
1311        mut api_token: String,
1312    ) -> Result<Credentials> {
1313        #[derive(Deserialize)]
1314        struct AuthenticatedUserResponse {
1315            user: User,
1316        }
1317
1318        #[derive(Deserialize)]
1319        struct User {
1320            id: u64,
1321        }
1322
1323        let github_user = {
1324            #[derive(Deserialize)]
1325            struct GithubUser {
1326                id: i32,
1327                login: String,
1328                created_at: DateTime<Utc>,
1329            }
1330
1331            let request = {
1332                let mut request_builder =
1333                    Request::get(&format!("https://api.github.com/users/{login}"));
1334                if let Ok(github_token) = std::env::var("GITHUB_TOKEN") {
1335                    request_builder =
1336                        request_builder.header("Authorization", format!("Bearer {}", github_token));
1337                }
1338
1339                request_builder.body(AsyncBody::empty())?
1340            };
1341
1342            let mut response = http
1343                .send(request)
1344                .await
1345                .context("error fetching GitHub user")?;
1346
1347            let mut body = Vec::new();
1348            response
1349                .body_mut()
1350                .read_to_end(&mut body)
1351                .await
1352                .context("error reading GitHub user")?;
1353
1354            if !response.status().is_success() {
1355                let text = String::from_utf8_lossy(body.as_slice());
1356                bail!(
1357                    "status error {}, response: {text:?}",
1358                    response.status().as_u16()
1359                );
1360            }
1361
1362            serde_json::from_slice::<GithubUser>(body.as_slice()).map_err(|err| {
1363                log::error!("Error deserializing: {:?}", err);
1364                log::error!(
1365                    "GitHub API response text: {:?}",
1366                    String::from_utf8_lossy(body.as_slice())
1367                );
1368                anyhow!("error deserializing GitHub user")
1369            })?
1370        };
1371
1372        let query_params = [
1373            ("github_login", &github_user.login),
1374            ("github_user_id", &github_user.id.to_string()),
1375            (
1376                "github_user_created_at",
1377                &github_user.created_at.to_rfc3339(),
1378            ),
1379        ];
1380
1381        // Use the collab server's admin API to retrieve the ID
1382        // of the impersonated user.
1383        let mut url = self.rpc_url(http.clone(), None).await?;
1384        url.set_path("/user");
1385        url.set_query(Some(
1386            &query_params
1387                .iter()
1388                .map(|(key, value)| {
1389                    format!(
1390                        "{}={}",
1391                        key,
1392                        url::form_urlencoded::byte_serialize(value.as_bytes()).collect::<String>()
1393                    )
1394                })
1395                .collect::<Vec<String>>()
1396                .join("&"),
1397        ));
1398        let request: http_client::Request<AsyncBody> = Request::get(url.as_str())
1399            .header("Authorization", format!("token {api_token}"))
1400            .body("".into())?;
1401
1402        let mut response = http.send(request).await?;
1403        let mut body = String::new();
1404        response.body_mut().read_to_string(&mut body).await?;
1405        if !response.status().is_success() {
1406            Err(anyhow!(
1407                "admin user request failed {} - {}",
1408                response.status().as_u16(),
1409                body,
1410            ))?;
1411        }
1412        let response: AuthenticatedUserResponse = serde_json::from_str(&body)?;
1413
1414        // Use the admin API token to authenticate as the impersonated user.
1415        api_token.insert_str(0, "ADMIN_TOKEN:");
1416        Ok(Credentials::User {
1417            user_id: response.user.id,
1418            access_token: api_token,
1419        })
1420    }
1421
1422    pub async fn sign_out(self: &Arc<Self>, cx: &AsyncAppContext) {
1423        self.state.write().credentials = None;
1424        self.disconnect(cx);
1425
1426        if self.has_credentials(cx).await {
1427            self.credentials_provider
1428                .delete_credentials(cx)
1429                .await
1430                .log_err();
1431        }
1432    }
1433
1434    pub fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) {
1435        self.peer.teardown();
1436        self.set_status(Status::SignedOut, cx);
1437    }
1438
1439    pub fn reconnect(self: &Arc<Self>, cx: &AsyncAppContext) {
1440        self.peer.teardown();
1441        self.set_status(Status::ConnectionLost, cx);
1442    }
1443
1444    fn connection_id(&self) -> Result<ConnectionId> {
1445        if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1446            Ok(connection_id)
1447        } else {
1448            Err(anyhow!("not connected"))
1449        }
1450    }
1451
1452    pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1453        log::debug!("rpc send. client_id:{}, name:{}", self.id(), T::NAME);
1454        self.peer.send(self.connection_id()?, message)
1455    }
1456
1457    pub fn request<T: RequestMessage>(
1458        &self,
1459        request: T,
1460    ) -> impl Future<Output = Result<T::Response>> {
1461        self.request_envelope(request)
1462            .map_ok(|envelope| envelope.payload)
1463    }
1464
1465    pub fn request_stream<T: RequestMessage>(
1466        &self,
1467        request: T,
1468    ) -> impl Future<Output = Result<impl Stream<Item = Result<T::Response>>>> {
1469        let client_id = self.id.load(Ordering::SeqCst);
1470        log::debug!(
1471            "rpc request start. client_id:{}. name:{}",
1472            client_id,
1473            T::NAME
1474        );
1475        let response = self
1476            .connection_id()
1477            .map(|conn_id| self.peer.request_stream(conn_id, request));
1478        async move {
1479            let response = response?.await;
1480            log::debug!(
1481                "rpc request finish. client_id:{}. name:{}",
1482                client_id,
1483                T::NAME
1484            );
1485            response
1486        }
1487    }
1488
1489    pub fn request_envelope<T: RequestMessage>(
1490        &self,
1491        request: T,
1492    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> {
1493        let client_id = self.id();
1494        log::debug!(
1495            "rpc request start. client_id:{}. name:{}",
1496            client_id,
1497            T::NAME
1498        );
1499        let response = self
1500            .connection_id()
1501            .map(|conn_id| self.peer.request_envelope(conn_id, request));
1502        async move {
1503            let response = response?.await;
1504            log::debug!(
1505                "rpc request finish. client_id:{}. name:{}",
1506                client_id,
1507                T::NAME
1508            );
1509            response
1510        }
1511    }
1512
1513    pub fn request_dynamic(
1514        &self,
1515        envelope: proto::Envelope,
1516        request_type: &'static str,
1517    ) -> impl Future<Output = Result<proto::Envelope>> {
1518        let client_id = self.id();
1519        log::debug!(
1520            "rpc request start. client_id:{}. name:{}",
1521            client_id,
1522            request_type
1523        );
1524        let response = self
1525            .connection_id()
1526            .map(|conn_id| self.peer.request_dynamic(conn_id, envelope, request_type));
1527        async move {
1528            let response = response?.await;
1529            log::debug!(
1530                "rpc request finish. client_id:{}. name:{}",
1531                client_id,
1532                request_type
1533            );
1534            Ok(response?.0)
1535        }
1536    }
1537
1538    fn handle_message(
1539        self: &Arc<Client>,
1540        message: Box<dyn AnyTypedEnvelope>,
1541        cx: &AsyncAppContext,
1542    ) {
1543        let sender_id = message.sender_id();
1544        let request_id = message.message_id();
1545        let type_name = message.payload_type_name();
1546        let original_sender_id = message.original_sender_id();
1547
1548        if let Some(future) = ProtoMessageHandlerSet::handle_message(
1549            &self.handler_set,
1550            message,
1551            self.clone().into(),
1552            cx.clone(),
1553        ) {
1554            let client_id = self.id();
1555            log::debug!(
1556                "rpc message received. client_id:{}, sender_id:{:?}, type:{}",
1557                client_id,
1558                original_sender_id,
1559                type_name
1560            );
1561            cx.spawn(move |_| async move {
1562                match future.await {
1563                    Ok(()) => {
1564                        log::debug!(
1565                            "rpc message handled. client_id:{}, sender_id:{:?}, type:{}",
1566                            client_id,
1567                            original_sender_id,
1568                            type_name
1569                        );
1570                    }
1571                    Err(error) => {
1572                        log::error!(
1573                            "error handling message. client_id:{}, sender_id:{:?}, type:{}, error:{:?}",
1574                            client_id,
1575                            original_sender_id,
1576                            type_name,
1577                            error
1578                        );
1579                    }
1580                }
1581            })
1582            .detach();
1583        } else {
1584            log::info!("unhandled message {}", type_name);
1585            self.peer
1586                .respond_with_unhandled_message(sender_id.into(), request_id, type_name)
1587                .log_err();
1588        }
1589    }
1590
1591    pub fn telemetry(&self) -> &Arc<Telemetry> {
1592        &self.telemetry
1593    }
1594}
1595
1596impl ProtoClient for Client {
1597    fn request(
1598        &self,
1599        envelope: proto::Envelope,
1600        request_type: &'static str,
1601    ) -> BoxFuture<'static, Result<proto::Envelope>> {
1602        self.request_dynamic(envelope, request_type).boxed()
1603    }
1604
1605    fn send(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1606        log::debug!("rpc send. client_id:{}, name:{}", self.id(), message_type);
1607        let connection_id = self.connection_id()?;
1608        self.peer.send_dynamic(connection_id, envelope)
1609    }
1610
1611    fn send_response(&self, envelope: proto::Envelope, message_type: &'static str) -> Result<()> {
1612        log::debug!(
1613            "rpc respond. client_id:{}, name:{}",
1614            self.id(),
1615            message_type
1616        );
1617        let connection_id = self.connection_id()?;
1618        self.peer.send_dynamic(connection_id, envelope)
1619    }
1620
1621    fn message_handler_set(&self) -> &parking_lot::Mutex<ProtoMessageHandlerSet> {
1622        &self.handler_set
1623    }
1624}
1625
1626#[derive(Serialize, Deserialize)]
1627struct DevelopmentCredentials {
1628    user_id: u64,
1629    access_token: String,
1630}
1631
1632/// A credentials provider that stores credentials in a local file.
1633///
1634/// This MUST only be used in development, as this is not a secure way of storing
1635/// credentials on user machines.
1636///
1637/// Its existence is purely to work around the annoyance of having to constantly
1638/// re-allow access to the system keychain when developing Zed.
1639struct DevelopmentCredentialsProvider {
1640    path: PathBuf,
1641}
1642
1643impl CredentialsProvider for DevelopmentCredentialsProvider {
1644    fn read_credentials<'a>(
1645        &'a self,
1646        _cx: &'a AsyncAppContext,
1647    ) -> Pin<Box<dyn Future<Output = Option<Credentials>> + 'a>> {
1648        async move {
1649            if IMPERSONATE_LOGIN.is_some() {
1650                return None;
1651            }
1652
1653            let json = std::fs::read(&self.path).log_err()?;
1654
1655            let credentials: DevelopmentCredentials = serde_json::from_slice(&json).log_err()?;
1656
1657            Some(Credentials::User {
1658                user_id: credentials.user_id,
1659                access_token: credentials.access_token,
1660            })
1661        }
1662        .boxed_local()
1663    }
1664
1665    fn write_credentials<'a>(
1666        &'a self,
1667        user_id: u64,
1668        access_token: String,
1669        _cx: &'a AsyncAppContext,
1670    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>> {
1671        async move {
1672            let json = serde_json::to_string(&DevelopmentCredentials {
1673                user_id,
1674                access_token,
1675            })?;
1676
1677            std::fs::write(&self.path, json)?;
1678
1679            Ok(())
1680        }
1681        .boxed_local()
1682    }
1683
1684    fn delete_credentials<'a>(
1685        &'a self,
1686        _cx: &'a AsyncAppContext,
1687    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>> {
1688        async move { Ok(std::fs::remove_file(&self.path)?) }.boxed_local()
1689    }
1690}
1691
1692/// A credentials provider that stores credentials in the system keychain.
1693struct KeychainCredentialsProvider;
1694
1695impl CredentialsProvider for KeychainCredentialsProvider {
1696    fn read_credentials<'a>(
1697        &'a self,
1698        cx: &'a AsyncAppContext,
1699    ) -> Pin<Box<dyn Future<Output = Option<Credentials>> + 'a>> {
1700        async move {
1701            if IMPERSONATE_LOGIN.is_some() {
1702                return None;
1703            }
1704
1705            let (user_id, access_token) = cx
1706                .update(|cx| cx.read_credentials(&ClientSettings::get_global(cx).server_url))
1707                .log_err()?
1708                .await
1709                .log_err()??;
1710
1711            Some(Credentials::User {
1712                user_id: user_id.parse().ok()?,
1713                access_token: String::from_utf8(access_token).ok()?,
1714            })
1715        }
1716        .boxed_local()
1717    }
1718
1719    fn write_credentials<'a>(
1720        &'a self,
1721        user_id: u64,
1722        access_token: String,
1723        cx: &'a AsyncAppContext,
1724    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>> {
1725        async move {
1726            cx.update(move |cx| {
1727                cx.write_credentials(
1728                    &ClientSettings::get_global(cx).server_url,
1729                    &user_id.to_string(),
1730                    access_token.as_bytes(),
1731                )
1732            })?
1733            .await
1734        }
1735        .boxed_local()
1736    }
1737
1738    fn delete_credentials<'a>(
1739        &'a self,
1740        cx: &'a AsyncAppContext,
1741    ) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>> {
1742        async move {
1743            cx.update(move |cx| cx.delete_credentials(&ClientSettings::get_global(cx).server_url))?
1744                .await
1745        }
1746        .boxed_local()
1747    }
1748}
1749
1750/// prefix for the zed:// url scheme
1751pub static ZED_URL_SCHEME: &str = "zed";
1752
1753/// Parses the given link into a Zed link.
1754///
1755/// Returns a [`Some`] containing the unprefixed link if the link is a Zed link.
1756/// Returns [`None`] otherwise.
1757pub fn parse_zed_link<'a>(link: &'a str, cx: &AppContext) -> Option<&'a str> {
1758    let server_url = &ClientSettings::get_global(cx).server_url;
1759    if let Some(stripped) = link
1760        .strip_prefix(server_url)
1761        .and_then(|result| result.strip_prefix('/'))
1762    {
1763        return Some(stripped);
1764    }
1765    if let Some(stripped) = link
1766        .strip_prefix(ZED_URL_SCHEME)
1767        .and_then(|result| result.strip_prefix("://"))
1768    {
1769        return Some(stripped);
1770    }
1771
1772    None
1773}
1774
1775#[cfg(test)]
1776mod tests {
1777    use super::*;
1778    use crate::test::FakeServer;
1779
1780    use clock::FakeSystemClock;
1781    use gpui::{BackgroundExecutor, Context, TestAppContext};
1782    use http_client::FakeHttpClient;
1783    use parking_lot::Mutex;
1784    use proto::TypedEnvelope;
1785    use settings::SettingsStore;
1786    use std::future;
1787
1788    #[gpui::test(iterations = 10)]
1789    async fn test_reconnection(cx: &mut TestAppContext) {
1790        init_test(cx);
1791        let user_id = 5;
1792        let client = cx.update(|cx| {
1793            Client::new(
1794                Arc::new(FakeSystemClock::default()),
1795                FakeHttpClient::with_404_response(),
1796                cx,
1797            )
1798        });
1799        let server = FakeServer::for_client(user_id, &client, cx).await;
1800        let mut status = client.status();
1801        assert!(matches!(
1802            status.next().await,
1803            Some(Status::Connected { .. })
1804        ));
1805        assert_eq!(server.auth_count(), 1);
1806
1807        server.forbid_connections();
1808        server.disconnect();
1809        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1810
1811        server.allow_connections();
1812        cx.executor().advance_clock(Duration::from_secs(10));
1813        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1814        assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1815
1816        server.forbid_connections();
1817        server.disconnect();
1818        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1819
1820        // Clear cached credentials after authentication fails
1821        server.roll_access_token();
1822        server.allow_connections();
1823        cx.executor().run_until_parked();
1824        cx.executor().advance_clock(Duration::from_secs(10));
1825        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1826        assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1827    }
1828
1829    #[gpui::test(iterations = 10)]
1830    async fn test_connection_timeout(executor: BackgroundExecutor, cx: &mut TestAppContext) {
1831        init_test(cx);
1832        let user_id = 5;
1833        let client = cx.update(|cx| {
1834            Client::new(
1835                Arc::new(FakeSystemClock::default()),
1836                FakeHttpClient::with_404_response(),
1837                cx,
1838            )
1839        });
1840        let mut status = client.status();
1841
1842        // Time out when client tries to connect.
1843        client.override_authenticate(move |cx| {
1844            cx.background_executor().spawn(async move {
1845                Ok(Credentials::User {
1846                    user_id,
1847                    access_token: "token".into(),
1848                })
1849            })
1850        });
1851        client.override_establish_connection(|_, cx| {
1852            cx.background_executor().spawn(async move {
1853                future::pending::<()>().await;
1854                unreachable!()
1855            })
1856        });
1857        let auth_and_connect = cx.spawn({
1858            let client = client.clone();
1859            |cx| async move { client.authenticate_and_connect(false, &cx).await }
1860        });
1861        executor.run_until_parked();
1862        assert!(matches!(status.next().await, Some(Status::Connecting)));
1863
1864        executor.advance_clock(CONNECTION_TIMEOUT);
1865        assert!(matches!(
1866            status.next().await,
1867            Some(Status::ConnectionError { .. })
1868        ));
1869        auth_and_connect.await.unwrap_err();
1870
1871        // Allow the connection to be established.
1872        let server = FakeServer::for_client(user_id, &client, cx).await;
1873        assert!(matches!(
1874            status.next().await,
1875            Some(Status::Connected { .. })
1876        ));
1877
1878        // Disconnect client.
1879        server.forbid_connections();
1880        server.disconnect();
1881        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1882
1883        // Time out when re-establishing the connection.
1884        server.allow_connections();
1885        client.override_establish_connection(|_, cx| {
1886            cx.background_executor().spawn(async move {
1887                future::pending::<()>().await;
1888                unreachable!()
1889            })
1890        });
1891        executor.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1892        assert!(matches!(
1893            status.next().await,
1894            Some(Status::Reconnecting { .. })
1895        ));
1896
1897        executor.advance_clock(CONNECTION_TIMEOUT);
1898        assert!(matches!(
1899            status.next().await,
1900            Some(Status::ReconnectionError { .. })
1901        ));
1902    }
1903
1904    #[gpui::test(iterations = 10)]
1905    async fn test_authenticating_more_than_once(
1906        cx: &mut TestAppContext,
1907        executor: BackgroundExecutor,
1908    ) {
1909        init_test(cx);
1910        let auth_count = Arc::new(Mutex::new(0));
1911        let dropped_auth_count = Arc::new(Mutex::new(0));
1912        let client = cx.update(|cx| {
1913            Client::new(
1914                Arc::new(FakeSystemClock::default()),
1915                FakeHttpClient::with_404_response(),
1916                cx,
1917            )
1918        });
1919        client.override_authenticate({
1920            let auth_count = auth_count.clone();
1921            let dropped_auth_count = dropped_auth_count.clone();
1922            move |cx| {
1923                let auth_count = auth_count.clone();
1924                let dropped_auth_count = dropped_auth_count.clone();
1925                cx.background_executor().spawn(async move {
1926                    *auth_count.lock() += 1;
1927                    let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
1928                    future::pending::<()>().await;
1929                    unreachable!()
1930                })
1931            }
1932        });
1933
1934        let _authenticate = cx.spawn({
1935            let client = client.clone();
1936            move |cx| async move { client.authenticate_and_connect(false, &cx).await }
1937        });
1938        executor.run_until_parked();
1939        assert_eq!(*auth_count.lock(), 1);
1940        assert_eq!(*dropped_auth_count.lock(), 0);
1941
1942        let _authenticate = cx.spawn({
1943            let client = client.clone();
1944            |cx| async move { client.authenticate_and_connect(false, &cx).await }
1945        });
1946        executor.run_until_parked();
1947        assert_eq!(*auth_count.lock(), 2);
1948        assert_eq!(*dropped_auth_count.lock(), 1);
1949    }
1950
1951    #[gpui::test]
1952    async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1953        init_test(cx);
1954        let user_id = 5;
1955        let client = cx.update(|cx| {
1956            Client::new(
1957                Arc::new(FakeSystemClock::default()),
1958                FakeHttpClient::with_404_response(),
1959                cx,
1960            )
1961        });
1962        let server = FakeServer::for_client(user_id, &client, cx).await;
1963
1964        let (done_tx1, mut done_rx1) = smol::channel::unbounded();
1965        let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1966        AnyProtoClient::from(client.clone()).add_model_message_handler(
1967            move |model: Model<TestModel>, _: TypedEnvelope<proto::JoinProject>, mut cx| {
1968                match model.update(&mut cx, |model, _| model.id).unwrap() {
1969                    1 => done_tx1.try_send(()).unwrap(),
1970                    2 => done_tx2.try_send(()).unwrap(),
1971                    _ => unreachable!(),
1972                }
1973                async { Ok(()) }
1974            },
1975        );
1976        let model1 = cx.new_model(|_| TestModel {
1977            id: 1,
1978            subscription: None,
1979        });
1980        let model2 = cx.new_model(|_| TestModel {
1981            id: 2,
1982            subscription: None,
1983        });
1984        let model3 = cx.new_model(|_| TestModel {
1985            id: 3,
1986            subscription: None,
1987        });
1988
1989        let _subscription1 = client
1990            .subscribe_to_entity(1)
1991            .unwrap()
1992            .set_model(&model1, &mut cx.to_async());
1993        let _subscription2 = client
1994            .subscribe_to_entity(2)
1995            .unwrap()
1996            .set_model(&model2, &mut cx.to_async());
1997        // Ensure dropping a subscription for the same entity type still allows receiving of
1998        // messages for other entity IDs of the same type.
1999        let subscription3 = client
2000            .subscribe_to_entity(3)
2001            .unwrap()
2002            .set_model(&model3, &mut cx.to_async());
2003        drop(subscription3);
2004
2005        server.send(proto::JoinProject { project_id: 1 });
2006        server.send(proto::JoinProject { project_id: 2 });
2007        done_rx1.next().await.unwrap();
2008        done_rx2.next().await.unwrap();
2009    }
2010
2011    #[gpui::test]
2012    async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
2013        init_test(cx);
2014        let user_id = 5;
2015        let client = cx.update(|cx| {
2016            Client::new(
2017                Arc::new(FakeSystemClock::default()),
2018                FakeHttpClient::with_404_response(),
2019                cx,
2020            )
2021        });
2022        let server = FakeServer::for_client(user_id, &client, cx).await;
2023
2024        let model = cx.new_model(|_| TestModel::default());
2025        let (done_tx1, _done_rx1) = smol::channel::unbounded();
2026        let (done_tx2, mut done_rx2) = smol::channel::unbounded();
2027        let subscription1 = client.add_message_handler(
2028            model.downgrade(),
2029            move |_, _: TypedEnvelope<proto::Ping>, _| {
2030                done_tx1.try_send(()).unwrap();
2031                async { Ok(()) }
2032            },
2033        );
2034        drop(subscription1);
2035        let _subscription2 = client.add_message_handler(
2036            model.downgrade(),
2037            move |_, _: TypedEnvelope<proto::Ping>, _| {
2038                done_tx2.try_send(()).unwrap();
2039                async { Ok(()) }
2040            },
2041        );
2042        server.send(proto::Ping {});
2043        done_rx2.next().await.unwrap();
2044    }
2045
2046    #[gpui::test]
2047    async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
2048        init_test(cx);
2049        let user_id = 5;
2050        let client = cx.update(|cx| {
2051            Client::new(
2052                Arc::new(FakeSystemClock::default()),
2053                FakeHttpClient::with_404_response(),
2054                cx,
2055            )
2056        });
2057        let server = FakeServer::for_client(user_id, &client, cx).await;
2058
2059        let model = cx.new_model(|_| TestModel::default());
2060        let (done_tx, mut done_rx) = smol::channel::unbounded();
2061        let subscription = client.add_message_handler(
2062            model.clone().downgrade(),
2063            move |model: Model<TestModel>, _: TypedEnvelope<proto::Ping>, mut cx| {
2064                model
2065                    .update(&mut cx, |model, _| model.subscription.take())
2066                    .unwrap();
2067                done_tx.try_send(()).unwrap();
2068                async { Ok(()) }
2069            },
2070        );
2071        model.update(cx, |model, _| {
2072            model.subscription = Some(subscription);
2073        });
2074        server.send(proto::Ping {});
2075        done_rx.next().await.unwrap();
2076    }
2077
2078    #[derive(Default)]
2079    struct TestModel {
2080        id: usize,
2081        subscription: Option<Subscription>,
2082    }
2083
2084    fn init_test(cx: &mut TestAppContext) {
2085        cx.update(|cx| {
2086            let settings_store = SettingsStore::test(cx);
2087            cx.set_global(settings_store);
2088            init_settings(cx);
2089        });
2090    }
2091}