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