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