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