client.rs

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