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