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