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, 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(
 101        default_value: &Self::FileContent,
 102        user_values: &[&Self::FileContent],
 103        _: &mut AppContext,
 104    ) -> Result<Self>
 105    where
 106        Self: Sized,
 107    {
 108        let mut result = Self::load_via_json_merge(default_value, user_values)?;
 109        if let Some(server_url) = &*ZED_SERVER_URL {
 110            result.server_url = server_url.clone()
 111        }
 112        Ok(result)
 113    }
 114}
 115
 116pub fn init_settings(cx: &mut AppContext) {
 117    TelemetrySettings::register(cx);
 118    cx.update_global(|store: &mut SettingsStore, cx| {
 119        store.register_setting::<ClientSettings>(cx);
 120    });
 121}
 122
 123pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
 124    let client = Arc::downgrade(client);
 125    cx.on_action({
 126        let client = client.clone();
 127        move |_: &SignIn, cx| {
 128            if let Some(client) = client.upgrade() {
 129                cx.spawn(
 130                    |cx| async move { client.authenticate_and_connect(true, &cx).log_err().await },
 131                )
 132                .detach();
 133            }
 134        }
 135    });
 136
 137    cx.on_action({
 138        let client = client.clone();
 139        move |_: &SignOut, cx| {
 140            if let Some(client) = client.upgrade() {
 141                cx.spawn(|cx| async move {
 142                    client.disconnect(&cx);
 143                })
 144                .detach();
 145            }
 146        }
 147    });
 148
 149    cx.on_action({
 150        let client = client.clone();
 151        move |_: &Reconnect, cx| {
 152            if let Some(client) = client.upgrade() {
 153                cx.spawn(|cx| async move {
 154                    client.reconnect(&cx);
 155                })
 156                .detach();
 157            }
 158        }
 159    });
 160}
 161
 162struct GlobalClient(Arc<Client>);
 163
 164impl Global for GlobalClient {}
 165
 166pub struct Client {
 167    id: AtomicU64,
 168    peer: Arc<Peer>,
 169    http: Arc<HttpClientWithUrl>,
 170    telemetry: Arc<Telemetry>,
 171    state: RwLock<ClientState>,
 172
 173    #[allow(clippy::type_complexity)]
 174    #[cfg(any(test, feature = "test-support"))]
 175    authenticate: RwLock<
 176        Option<Box<dyn 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>>>,
 177    >,
 178
 179    #[allow(clippy::type_complexity)]
 180    #[cfg(any(test, feature = "test-support"))]
 181    establish_connection: RwLock<
 182        Option<
 183            Box<
 184                dyn 'static
 185                    + Send
 186                    + Sync
 187                    + Fn(
 188                        &Credentials,
 189                        &AsyncAppContext,
 190                    ) -> Task<Result<Connection, EstablishConnectionError>>,
 191            >,
 192        >,
 193    >,
 194}
 195
 196#[derive(Error, Debug)]
 197pub enum EstablishConnectionError {
 198    #[error("upgrade required")]
 199    UpgradeRequired,
 200    #[error("unauthorized")]
 201    Unauthorized,
 202    #[error("{0}")]
 203    Other(#[from] anyhow::Error),
 204    #[error("{0}")]
 205    Http(#[from] util::http::Error),
 206    #[error("{0}")]
 207    Io(#[from] std::io::Error),
 208    #[error("{0}")]
 209    Websocket(#[from] async_tungstenite::tungstenite::http::Error),
 210}
 211
 212impl From<WebsocketError> for EstablishConnectionError {
 213    fn from(error: WebsocketError) -> Self {
 214        if let WebsocketError::Http(response) = &error {
 215            match response.status() {
 216                StatusCode::UNAUTHORIZED => return EstablishConnectionError::Unauthorized,
 217                StatusCode::UPGRADE_REQUIRED => return EstablishConnectionError::UpgradeRequired,
 218                _ => {}
 219            }
 220        }
 221        EstablishConnectionError::Other(error.into())
 222    }
 223}
 224
 225impl EstablishConnectionError {
 226    pub fn other(error: impl Into<anyhow::Error> + Send + Sync) -> Self {
 227        Self::Other(error.into())
 228    }
 229}
 230
 231#[derive(Copy, Clone, Debug, PartialEq)]
 232pub enum Status {
 233    SignedOut,
 234    UpgradeRequired,
 235    Authenticating,
 236    Connecting,
 237    ConnectionError,
 238    Connected {
 239        peer_id: PeerId,
 240        connection_id: ConnectionId,
 241    },
 242    ConnectionLost,
 243    Reauthenticating,
 244    Reconnecting,
 245    ReconnectionError {
 246        next_reconnection: Instant,
 247    },
 248}
 249
 250impl Status {
 251    pub fn is_connected(&self) -> bool {
 252        matches!(self, Self::Connected { .. })
 253    }
 254
 255    pub fn is_signed_out(&self) -> bool {
 256        matches!(self, Self::SignedOut | Self::UpgradeRequired)
 257    }
 258}
 259
 260struct ClientState {
 261    credentials: Option<Credentials>,
 262    status: (watch::Sender<Status>, watch::Receiver<Status>),
 263    entity_id_extractors: HashMap<TypeId, fn(&dyn AnyTypedEnvelope) -> u64>,
 264    _reconnect_task: Option<Task<()>>,
 265    reconnect_interval: Duration,
 266    entities_by_type_and_remote_id: HashMap<(TypeId, u64), WeakSubscriber>,
 267    models_by_message_type: HashMap<TypeId, AnyWeakModel>,
 268    entity_types_by_message_type: HashMap<TypeId, TypeId>,
 269    #[allow(clippy::type_complexity)]
 270    message_handlers: HashMap<
 271        TypeId,
 272        Arc<
 273            dyn Send
 274                + Sync
 275                + Fn(
 276                    AnyModel,
 277                    Box<dyn AnyTypedEnvelope>,
 278                    &Arc<Client>,
 279                    AsyncAppContext,
 280                ) -> LocalBoxFuture<'static, Result<()>>,
 281        >,
 282    >,
 283}
 284
 285enum WeakSubscriber {
 286    Entity { handle: AnyWeakModel },
 287    Pending(Vec<Box<dyn AnyTypedEnvelope>>),
 288}
 289
 290#[derive(Clone, Debug, Eq, PartialEq)]
 291pub enum Credentials {
 292    DevServer { token: DevServerToken },
 293    User { user_id: u64, access_token: String },
 294}
 295
 296impl Credentials {
 297    pub fn authorization_header(&self) -> String {
 298        match self {
 299            Credentials::DevServer { token } => format!("dev-server-token {}", token),
 300            Credentials::User {
 301                user_id,
 302                access_token,
 303            } => format!("{} {}", user_id, access_token),
 304        }
 305    }
 306}
 307
 308impl Default for ClientState {
 309    fn default() -> Self {
 310        Self {
 311            credentials: None,
 312            status: watch::channel_with(Status::SignedOut),
 313            entity_id_extractors: Default::default(),
 314            _reconnect_task: None,
 315            reconnect_interval: Duration::from_secs(5),
 316            models_by_message_type: Default::default(),
 317            entities_by_type_and_remote_id: Default::default(),
 318            entity_types_by_message_type: Default::default(),
 319            message_handlers: Default::default(),
 320        }
 321    }
 322}
 323
 324pub enum Subscription {
 325    Entity {
 326        client: Weak<Client>,
 327        id: (TypeId, u64),
 328    },
 329    Message {
 330        client: Weak<Client>,
 331        id: TypeId,
 332    },
 333}
 334
 335impl Drop for Subscription {
 336    fn drop(&mut self) {
 337        match self {
 338            Subscription::Entity { client, id } => {
 339                if let Some(client) = client.upgrade() {
 340                    let mut state = client.state.write();
 341                    let _ = state.entities_by_type_and_remote_id.remove(id);
 342                }
 343            }
 344            Subscription::Message { client, id } => {
 345                if let Some(client) = client.upgrade() {
 346                    let mut state = client.state.write();
 347                    let _ = state.entity_types_by_message_type.remove(id);
 348                    let _ = state.message_handlers.remove(id);
 349                }
 350            }
 351        }
 352    }
 353}
 354
 355pub struct PendingEntitySubscription<T: 'static> {
 356    client: Arc<Client>,
 357    remote_id: u64,
 358    _entity_type: PhantomData<T>,
 359    consumed: bool,
 360}
 361
 362impl<T: 'static> PendingEntitySubscription<T> {
 363    pub fn set_model(mut self, model: &Model<T>, cx: &mut AsyncAppContext) -> Subscription {
 364        self.consumed = true;
 365        let mut state = self.client.state.write();
 366        let id = (TypeId::of::<T>(), self.remote_id);
 367        let Some(WeakSubscriber::Pending(messages)) =
 368            state.entities_by_type_and_remote_id.remove(&id)
 369        else {
 370            unreachable!()
 371        };
 372
 373        state.entities_by_type_and_remote_id.insert(
 374            id,
 375            WeakSubscriber::Entity {
 376                handle: model.downgrade().into(),
 377            },
 378        );
 379        drop(state);
 380        for message in messages {
 381            self.client.handle_message(message, cx);
 382        }
 383        Subscription::Entity {
 384            client: Arc::downgrade(&self.client),
 385            id,
 386        }
 387    }
 388}
 389
 390impl<T: 'static> Drop for PendingEntitySubscription<T> {
 391    fn drop(&mut self) {
 392        if !self.consumed {
 393            let mut state = self.client.state.write();
 394            if let Some(WeakSubscriber::Pending(messages)) = state
 395                .entities_by_type_and_remote_id
 396                .remove(&(TypeId::of::<T>(), self.remote_id))
 397            {
 398                for message in messages {
 399                    log::info!("unhandled message {}", message.payload_type_name());
 400                }
 401            }
 402        }
 403    }
 404}
 405
 406#[derive(Copy, Clone)]
 407pub struct TelemetrySettings {
 408    pub diagnostics: bool,
 409    pub metrics: bool,
 410}
 411
 412/// Control what info is collected by Zed.
 413#[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
 414pub struct TelemetrySettingsContent {
 415    /// Send debug info like crash reports.
 416    ///
 417    /// Default: true
 418    pub diagnostics: Option<bool>,
 419    /// Send anonymized usage data like what languages you're using Zed with.
 420    ///
 421    /// Default: true
 422    pub metrics: Option<bool>,
 423}
 424
 425impl settings::Settings for TelemetrySettings {
 426    const KEY: Option<&'static str> = Some("telemetry");
 427
 428    type FileContent = TelemetrySettingsContent;
 429
 430    fn load(
 431        default_value: &Self::FileContent,
 432        user_values: &[&Self::FileContent],
 433        _: &mut AppContext,
 434    ) -> Result<Self> {
 435        Ok(Self {
 436            diagnostics: user_values.first().and_then(|v| v.diagnostics).unwrap_or(
 437                default_value
 438                    .diagnostics
 439                    .ok_or_else(Self::missing_default)?,
 440            ),
 441            metrics: user_values
 442                .first()
 443                .and_then(|v| v.metrics)
 444                .unwrap_or(default_value.metrics.ok_or_else(Self::missing_default)?),
 445        })
 446    }
 447}
 448
 449impl Client {
 450    pub fn new(
 451        clock: Arc<dyn SystemClock>,
 452        http: Arc<HttpClientWithUrl>,
 453        cx: &mut AppContext,
 454    ) -> Arc<Self> {
 455        Arc::new(Self {
 456            id: AtomicU64::new(0),
 457            peer: Peer::new(0),
 458            telemetry: Telemetry::new(clock, http.clone(), cx),
 459            http,
 460            state: Default::default(),
 461
 462            #[cfg(any(test, feature = "test-support"))]
 463            authenticate: Default::default(),
 464            #[cfg(any(test, feature = "test-support"))]
 465            establish_connection: Default::default(),
 466        })
 467    }
 468
 469    pub fn id(&self) -> u64 {
 470        self.id.load(Ordering::SeqCst)
 471    }
 472
 473    pub fn http_client(&self) -> Arc<HttpClientWithUrl> {
 474        self.http.clone()
 475    }
 476
 477    pub fn set_id(&self, id: u64) -> &Self {
 478        self.id.store(id, Ordering::SeqCst);
 479        self
 480    }
 481
 482    #[cfg(any(test, feature = "test-support"))]
 483    pub fn teardown(&self) {
 484        let mut state = self.state.write();
 485        state._reconnect_task.take();
 486        state.message_handlers.clear();
 487        state.models_by_message_type.clear();
 488        state.entities_by_type_and_remote_id.clear();
 489        state.entity_id_extractors.clear();
 490        self.peer.teardown();
 491    }
 492
 493    #[cfg(any(test, feature = "test-support"))]
 494    pub fn override_authenticate<F>(&self, authenticate: F) -> &Self
 495    where
 496        F: 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>,
 497    {
 498        *self.authenticate.write() = Some(Box::new(authenticate));
 499        self
 500    }
 501
 502    #[cfg(any(test, feature = "test-support"))]
 503    pub fn override_establish_connection<F>(&self, connect: F) -> &Self
 504    where
 505        F: 'static
 506            + Send
 507            + Sync
 508            + Fn(&Credentials, &AsyncAppContext) -> Task<Result<Connection, EstablishConnectionError>>,
 509    {
 510        *self.establish_connection.write() = Some(Box::new(connect));
 511        self
 512    }
 513
 514    pub fn global(cx: &AppContext) -> Arc<Self> {
 515        cx.global::<GlobalClient>().0.clone()
 516    }
 517    pub fn set_global(client: Arc<Client>, cx: &mut AppContext) {
 518        cx.set_global(GlobalClient(client))
 519    }
 520
 521    pub fn user_id(&self) -> Option<u64> {
 522        if let Some(Credentials::User { user_id, .. }) = self.state.read().credentials.as_ref() {
 523            Some(*user_id)
 524        } else {
 525            None
 526        }
 527    }
 528
 529    pub fn peer_id(&self) -> Option<PeerId> {
 530        if let Status::Connected { peer_id, .. } = &*self.status().borrow() {
 531            Some(*peer_id)
 532        } else {
 533            None
 534        }
 535    }
 536
 537    pub fn status(&self) -> watch::Receiver<Status> {
 538        self.state.read().status.1.clone()
 539    }
 540
 541    fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncAppContext) {
 542        log::info!("set status on client {}: {:?}", self.id(), status);
 543        let mut state = self.state.write();
 544        *state.status.0.borrow_mut() = status;
 545
 546        match status {
 547            Status::Connected { .. } => {
 548                state._reconnect_task = None;
 549            }
 550            Status::ConnectionLost => {
 551                let this = self.clone();
 552                let reconnect_interval = state.reconnect_interval;
 553                state._reconnect_task = Some(cx.spawn(move |cx| async move {
 554                    #[cfg(any(test, feature = "test-support"))]
 555                    let mut rng = StdRng::seed_from_u64(0);
 556                    #[cfg(not(any(test, feature = "test-support")))]
 557                    let mut rng = StdRng::from_entropy();
 558
 559                    let mut delay = INITIAL_RECONNECTION_DELAY;
 560                    while let Err(error) = this.authenticate_and_connect(true, &cx).await {
 561                        log::error!("failed to connect {}", error);
 562                        if matches!(*this.status().borrow(), Status::ConnectionError) {
 563                            this.set_status(
 564                                Status::ReconnectionError {
 565                                    next_reconnection: Instant::now() + delay,
 566                                },
 567                                &cx,
 568                            );
 569                            cx.background_executor().timer(delay).await;
 570                            delay = delay
 571                                .mul_f32(rng.gen_range(1.0..=2.0))
 572                                .min(reconnect_interval);
 573                        } else {
 574                            break;
 575                        }
 576                    }
 577                }));
 578            }
 579            Status::SignedOut | Status::UpgradeRequired => {
 580                self.telemetry.set_authenticated_user_info(None, false);
 581                state._reconnect_task.take();
 582            }
 583            _ => {}
 584        }
 585    }
 586
 587    pub fn subscribe_to_entity<T>(
 588        self: &Arc<Self>,
 589        remote_id: u64,
 590    ) -> Result<PendingEntitySubscription<T>>
 591    where
 592        T: 'static,
 593    {
 594        let id = (TypeId::of::<T>(), remote_id);
 595
 596        let mut state = self.state.write();
 597        if state.entities_by_type_and_remote_id.contains_key(&id) {
 598            return Err(anyhow!("already subscribed to entity"));
 599        }
 600
 601        state
 602            .entities_by_type_and_remote_id
 603            .insert(id, WeakSubscriber::Pending(Default::default()));
 604
 605        Ok(PendingEntitySubscription {
 606            client: self.clone(),
 607            remote_id,
 608            consumed: false,
 609            _entity_type: PhantomData,
 610        })
 611    }
 612
 613    #[track_caller]
 614    pub fn add_message_handler<M, E, H, F>(
 615        self: &Arc<Self>,
 616        entity: WeakModel<E>,
 617        handler: H,
 618    ) -> Subscription
 619    where
 620        M: EnvelopedMessage,
 621        E: 'static,
 622        H: 'static
 623            + Sync
 624            + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F
 625            + Send
 626            + Sync,
 627        F: 'static + Future<Output = Result<()>>,
 628    {
 629        let message_type_id = TypeId::of::<M>();
 630        let mut state = self.state.write();
 631        state
 632            .models_by_message_type
 633            .insert(message_type_id, entity.into());
 634
 635        let prev_handler = state.message_handlers.insert(
 636            message_type_id,
 637            Arc::new(move |subscriber, envelope, client, cx| {
 638                let subscriber = subscriber.downcast::<E>().unwrap();
 639                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 640                handler(subscriber, *envelope, client.clone(), cx).boxed_local()
 641            }),
 642        );
 643        if prev_handler.is_some() {
 644            let location = std::panic::Location::caller();
 645            panic!(
 646                "{}:{} registered handler for the same message {} twice",
 647                location.file(),
 648                location.line(),
 649                std::any::type_name::<M>()
 650            );
 651        }
 652
 653        Subscription::Message {
 654            client: Arc::downgrade(self),
 655            id: message_type_id,
 656        }
 657    }
 658
 659    pub fn add_request_handler<M, E, H, F>(
 660        self: &Arc<Self>,
 661        model: WeakModel<E>,
 662        handler: H,
 663    ) -> Subscription
 664    where
 665        M: RequestMessage,
 666        E: 'static,
 667        H: 'static
 668            + Sync
 669            + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F
 670            + Send
 671            + Sync,
 672        F: 'static + Future<Output = Result<M::Response>>,
 673    {
 674        self.add_message_handler(model, move |handle, envelope, this, cx| {
 675            Self::respond_to_request(
 676                envelope.receipt(),
 677                handler(handle, envelope, this.clone(), cx),
 678                this,
 679            )
 680        })
 681    }
 682
 683    pub fn add_model_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
 684    where
 685        M: EntityMessage,
 686        E: 'static,
 687        H: 'static + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F + Send + Sync,
 688        F: 'static + Future<Output = Result<()>>,
 689    {
 690        self.add_entity_message_handler::<M, E, _, _>(move |subscriber, message, client, cx| {
 691            handler(subscriber.downcast::<E>().unwrap(), message, client, cx)
 692        })
 693    }
 694
 695    fn add_entity_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
 696    where
 697        M: EntityMessage,
 698        E: 'static,
 699        H: 'static + Fn(AnyModel, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F + Send + Sync,
 700        F: 'static + Future<Output = Result<()>>,
 701    {
 702        let model_type_id = TypeId::of::<E>();
 703        let message_type_id = TypeId::of::<M>();
 704
 705        let mut state = self.state.write();
 706        state
 707            .entity_types_by_message_type
 708            .insert(message_type_id, model_type_id);
 709        state
 710            .entity_id_extractors
 711            .entry(message_type_id)
 712            .or_insert_with(|| {
 713                |envelope| {
 714                    envelope
 715                        .as_any()
 716                        .downcast_ref::<TypedEnvelope<M>>()
 717                        .unwrap()
 718                        .payload
 719                        .remote_entity_id()
 720                }
 721            });
 722        let prev_handler = state.message_handlers.insert(
 723            message_type_id,
 724            Arc::new(move |handle, envelope, client, cx| {
 725                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 726                handler(handle, *envelope, client.clone(), cx).boxed_local()
 727            }),
 728        );
 729        if prev_handler.is_some() {
 730            panic!("registered handler for the same message twice");
 731        }
 732    }
 733
 734    pub fn add_model_request_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
 735    where
 736        M: EntityMessage + RequestMessage,
 737        E: 'static,
 738        H: 'static + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F + Send + Sync,
 739        F: 'static + Future<Output = Result<M::Response>>,
 740    {
 741        self.add_model_message_handler(move |entity, envelope, client, cx| {
 742            Self::respond_to_request::<M, _>(
 743                envelope.receipt(),
 744                handler(entity, envelope, client.clone(), cx),
 745                client,
 746            )
 747        })
 748    }
 749
 750    async fn respond_to_request<T: RequestMessage, F: Future<Output = Result<T::Response>>>(
 751        receipt: Receipt<T>,
 752        response: F,
 753        client: Arc<Self>,
 754    ) -> Result<()> {
 755        match response.await {
 756            Ok(response) => {
 757                client.respond(receipt, response)?;
 758                Ok(())
 759            }
 760            Err(error) => {
 761                client.respond_with_error(receipt, error.to_proto())?;
 762                Err(error)
 763            }
 764        }
 765    }
 766
 767    pub async fn has_keychain_credentials(&self, cx: &AsyncAppContext) -> bool {
 768        read_credentials_from_keychain(cx).await.is_some()
 769    }
 770
 771    pub fn set_dev_server_token(&self, token: DevServerToken) {
 772        self.state.write().credentials = Some(Credentials::DevServer { token });
 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
 794        if was_disconnected {
 795            self.set_status(Status::Authenticating, cx);
 796        } else {
 797            self.set_status(Status::Reauthenticating, cx)
 798        }
 799
 800        let mut read_from_keychain = false;
 801        let mut credentials = self.state.read().credentials.clone();
 802        if credentials.is_none() && try_keychain {
 803            credentials = read_credentials_from_keychain(cx).await;
 804            read_from_keychain = credentials.is_some();
 805        }
 806        if credentials.is_none() {
 807            let mut status_rx = self.status();
 808            let _ = status_rx.next().await;
 809            futures::select_biased! {
 810                authenticate = self.authenticate(cx).fuse() => {
 811                    match authenticate {
 812                        Ok(creds) => credentials = Some(creds),
 813                        Err(err) => {
 814                            self.set_status(Status::ConnectionError, cx);
 815                            return Err(err);
 816                        }
 817                    }
 818                }
 819                _ = status_rx.next().fuse() => {
 820                    return Err(anyhow!("authentication canceled"));
 821                }
 822            }
 823        }
 824        let credentials = credentials.unwrap();
 825        if let Credentials::User { user_id, .. } = &credentials {
 826            self.set_id(*user_id);
 827        }
 828
 829        if was_disconnected {
 830            self.set_status(Status::Connecting, cx);
 831        } else {
 832            self.set_status(Status::Reconnecting, cx);
 833        }
 834
 835        let mut timeout =
 836            futures::FutureExt::fuse(cx.background_executor().timer(CONNECTION_TIMEOUT));
 837        futures::select_biased! {
 838            connection = self.establish_connection(&credentials, cx).fuse() => {
 839                match connection {
 840                    Ok(conn) => {
 841                        self.state.write().credentials = Some(credentials.clone());
 842                        if !read_from_keychain && IMPERSONATE_LOGIN.is_none() {
 843                            if let Credentials::User{user_id, access_token} = credentials {
 844                                write_credentials_to_keychain(user_id, access_token, cx).await.log_err();
 845                            }
 846                        }
 847
 848                        futures::select_biased! {
 849                            result = self.set_connection(conn, cx).fuse() => result,
 850                            _ = timeout => {
 851                                self.set_status(Status::ConnectionError, cx);
 852                                Err(anyhow!("timed out waiting on hello message from server"))
 853                            }
 854                        }
 855                    }
 856                    Err(EstablishConnectionError::Unauthorized) => {
 857                        self.state.write().credentials.take();
 858                        if read_from_keychain {
 859                            delete_credentials_from_keychain(cx).await.log_err();
 860                            self.set_status(Status::SignedOut, cx);
 861                            self.authenticate_and_connect(false, cx).await
 862                        } else {
 863                            self.set_status(Status::ConnectionError, cx);
 864                            Err(EstablishConnectionError::Unauthorized)?
 865                        }
 866                    }
 867                    Err(EstablishConnectionError::UpgradeRequired) => {
 868                        self.set_status(Status::UpgradeRequired, cx);
 869                        Err(EstablishConnectionError::UpgradeRequired)?
 870                    }
 871                    Err(error) => {
 872                        self.set_status(Status::ConnectionError, cx);
 873                        Err(error)?
 874                    }
 875                }
 876            }
 877            _ = &mut timeout => {
 878                self.set_status(Status::ConnectionError, cx);
 879                Err(anyhow!("timed out trying to establish connection"))
 880            }
 881        }
 882    }
 883
 884    async fn set_connection(
 885        self: &Arc<Self>,
 886        conn: Connection,
 887        cx: &AsyncAppContext,
 888    ) -> Result<()> {
 889        let executor = cx.background_executor();
 890        log::info!("add connection to peer");
 891        let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn, {
 892            let executor = executor.clone();
 893            move |duration| executor.timer(duration)
 894        });
 895        let handle_io = executor.spawn(handle_io);
 896
 897        let peer_id = async {
 898            log::info!("waiting for server hello");
 899            let message = incoming
 900                .next()
 901                .await
 902                .ok_or_else(|| anyhow!("no hello message received"))?;
 903            log::info!("got server hello");
 904            let hello_message_type_name = message.payload_type_name().to_string();
 905            let hello = message
 906                .into_any()
 907                .downcast::<TypedEnvelope<proto::Hello>>()
 908                .map_err(|_| {
 909                    anyhow!(
 910                        "invalid hello message received: {:?}",
 911                        hello_message_type_name
 912                    )
 913                })?;
 914            let peer_id = hello
 915                .payload
 916                .peer_id
 917                .ok_or_else(|| anyhow!("invalid peer id"))?;
 918            Ok(peer_id)
 919        };
 920
 921        let peer_id = match peer_id.await {
 922            Ok(peer_id) => peer_id,
 923            Err(error) => {
 924                self.peer.disconnect(connection_id);
 925                return Err(error);
 926            }
 927        };
 928
 929        log::info!(
 930            "set status to connected (connection id: {:?}, peer id: {:?})",
 931            connection_id,
 932            peer_id
 933        );
 934        self.set_status(
 935            Status::Connected {
 936                peer_id,
 937                connection_id,
 938            },
 939            cx,
 940        );
 941
 942        cx.spawn({
 943            let this = self.clone();
 944            |cx| {
 945                async move {
 946                    while let Some(message) = incoming.next().await {
 947                        this.handle_message(message, &cx);
 948                        // Don't starve the main thread when receiving lots of messages at once.
 949                        smol::future::yield_now().await;
 950                    }
 951                }
 952            }
 953        })
 954        .detach();
 955
 956        cx.spawn({
 957            let this = self.clone();
 958            move |cx| async move {
 959                match handle_io.await {
 960                    Ok(()) => {
 961                        if *this.status().borrow()
 962                            == (Status::Connected {
 963                                connection_id,
 964                                peer_id,
 965                            })
 966                        {
 967                            this.set_status(Status::SignedOut, &cx);
 968                        }
 969                    }
 970                    Err(err) => {
 971                        log::error!("connection error: {:?}", err);
 972                        this.set_status(Status::ConnectionLost, &cx);
 973                    }
 974                }
 975            }
 976        })
 977        .detach();
 978
 979        Ok(())
 980    }
 981
 982    fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
 983        #[cfg(any(test, feature = "test-support"))]
 984        if let Some(callback) = self.authenticate.read().as_ref() {
 985            return callback(cx);
 986        }
 987
 988        self.authenticate_with_browser(cx)
 989    }
 990
 991    fn establish_connection(
 992        self: &Arc<Self>,
 993        credentials: &Credentials,
 994        cx: &AsyncAppContext,
 995    ) -> Task<Result<Connection, EstablishConnectionError>> {
 996        #[cfg(any(test, feature = "test-support"))]
 997        if let Some(callback) = self.establish_connection.read().as_ref() {
 998            return callback(credentials, cx);
 999        }
1000
1001        self.establish_websocket_connection(credentials, cx)
1002    }
1003
1004    async fn get_rpc_url(
1005        http: Arc<HttpClientWithUrl>,
1006        release_channel: Option<ReleaseChannel>,
1007    ) -> Result<Url> {
1008        if let Some(url) = &*ZED_RPC_URL {
1009            return Url::parse(url).context("invalid rpc url");
1010        }
1011
1012        let mut url = http.build_url("/rpc");
1013        if let Some(preview_param) =
1014            release_channel.and_then(|channel| channel.release_query_param())
1015        {
1016            url += "?";
1017            url += preview_param;
1018        }
1019        let response = http.get(&url, Default::default(), false).await?;
1020        let collab_url = if response.status().is_redirection() {
1021            response
1022                .headers()
1023                .get("Location")
1024                .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
1025                .to_str()
1026                .map_err(EstablishConnectionError::other)?
1027                .to_string()
1028        } else {
1029            Err(anyhow!(
1030                "unexpected /rpc response status {}",
1031                response.status()
1032            ))?
1033        };
1034
1035        Url::parse(&collab_url).context("invalid rpc url")
1036    }
1037
1038    fn establish_websocket_connection(
1039        self: &Arc<Self>,
1040        credentials: &Credentials,
1041        cx: &AsyncAppContext,
1042    ) -> Task<Result<Connection, EstablishConnectionError>> {
1043        let release_channel = cx
1044            .update(|cx| ReleaseChannel::try_global(cx))
1045            .ok()
1046            .flatten();
1047        let app_version = cx
1048            .update(|cx| AppVersion::global(cx).to_string())
1049            .ok()
1050            .unwrap_or_default();
1051
1052        let request = Request::builder()
1053            .header("Authorization", credentials.authorization_header())
1054            .header("x-zed-protocol-version", rpc::PROTOCOL_VERSION)
1055            .header("x-zed-app-version", app_version)
1056            .header(
1057                "x-zed-release-channel",
1058                release_channel.map(|r| r.dev_name()).unwrap_or("unknown"),
1059            );
1060
1061        let http = self.http.clone();
1062        cx.background_executor().spawn(async move {
1063            let mut rpc_url = Self::get_rpc_url(http, release_channel).await?;
1064            let rpc_host = rpc_url
1065                .host_str()
1066                .zip(rpc_url.port_or_known_default())
1067                .ok_or_else(|| anyhow!("missing host in rpc url"))?;
1068            let stream = smol::net::TcpStream::connect(rpc_host).await?;
1069
1070            log::info!("connected to rpc endpoint {}", rpc_url);
1071
1072            match rpc_url.scheme() {
1073                "https" => {
1074                    rpc_url.set_scheme("wss").unwrap();
1075                    let request = request.uri(rpc_url.as_str()).body(())?;
1076                    let (stream, _) =
1077                        async_tungstenite::async_std::client_async_tls(request, stream).await?;
1078                    Ok(Connection::new(
1079                        stream
1080                            .map_err(|error| anyhow!(error))
1081                            .sink_map_err(|error| anyhow!(error)),
1082                    ))
1083                }
1084                "http" => {
1085                    rpc_url.set_scheme("ws").unwrap();
1086                    let request = request.uri(rpc_url.as_str()).body(())?;
1087                    let (stream, _) = async_tungstenite::client_async(request, stream).await?;
1088                    Ok(Connection::new(
1089                        stream
1090                            .map_err(|error| anyhow!(error))
1091                            .sink_map_err(|error| anyhow!(error)),
1092                    ))
1093                }
1094                _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1095            }
1096        })
1097    }
1098
1099    pub fn authenticate_with_browser(
1100        self: &Arc<Self>,
1101        cx: &AsyncAppContext,
1102    ) -> Task<Result<Credentials>> {
1103        let http = self.http.clone();
1104        cx.spawn(|cx| async move {
1105            let background = cx.background_executor().clone();
1106
1107            let (open_url_tx, open_url_rx) = oneshot::channel::<String>();
1108            cx.update(|cx| {
1109                cx.spawn(move |cx| async move {
1110                    let url = open_url_rx.await?;
1111                    cx.update(|cx| cx.open_url(&url))
1112                })
1113                .detach_and_log_err(cx);
1114            })
1115            .log_err();
1116
1117            let credentials = background
1118                .clone()
1119                .spawn(async move {
1120                    // Generate a pair of asymmetric encryption keys. The public key will be used by the
1121                    // zed server to encrypt the user's access token, so that it can'be intercepted by
1122                    // any other app running on the user's device.
1123                    let (public_key, private_key) =
1124                        rpc::auth::keypair().expect("failed to generate keypair for auth");
1125                    let public_key_string = String::try_from(public_key)
1126                        .expect("failed to serialize public key for auth");
1127
1128                    if let Some((login, token)) =
1129                        IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref())
1130                    {
1131                        return Self::authenticate_as_admin(http, login.clone(), token.clone())
1132                            .await;
1133                    }
1134
1135                    // Start an HTTP server to receive the redirect from Zed's sign-in page.
1136                    let server =
1137                        tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1138                    let port = server.server_addr().port();
1139
1140                    // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1141                    // that the user is signing in from a Zed app running on the same device.
1142                    let mut url = http.build_url(&format!(
1143                        "/native_app_signin?native_app_port={}&native_app_public_key={}",
1144                        port, public_key_string
1145                    ));
1146
1147                    if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1148                        log::info!("impersonating user @{}", impersonate_login);
1149                        write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1150                    }
1151
1152                    open_url_tx.send(url).log_err();
1153
1154                    // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1155                    // access token from the query params.
1156                    //
1157                    // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1158                    // custom URL scheme instead of this local HTTP server.
1159                    let (user_id, access_token) = background
1160                        .spawn(async move {
1161                            for _ in 0..100 {
1162                                if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1163                                    let path = req.url();
1164                                    let mut user_id = None;
1165                                    let mut access_token = None;
1166                                    let url = Url::parse(&format!("http://example.com{}", path))
1167                                        .context("failed to parse login notification url")?;
1168                                    for (key, value) in url.query_pairs() {
1169                                        if key == "access_token" {
1170                                            access_token = Some(value.to_string());
1171                                        } else if key == "user_id" {
1172                                            user_id = Some(value.to_string());
1173                                        }
1174                                    }
1175
1176                                    let post_auth_url =
1177                                        http.build_url("/native_app_signin_succeeded");
1178                                    req.respond(
1179                                        tiny_http::Response::empty(302).with_header(
1180                                            tiny_http::Header::from_bytes(
1181                                                &b"Location"[..],
1182                                                post_auth_url.as_bytes(),
1183                                            )
1184                                            .unwrap(),
1185                                        ),
1186                                    )
1187                                    .context("failed to respond to login http request")?;
1188                                    return Ok((
1189                                        user_id
1190                                            .ok_or_else(|| anyhow!("missing user_id parameter"))?,
1191                                        access_token.ok_or_else(|| {
1192                                            anyhow!("missing access_token parameter")
1193                                        })?,
1194                                    ));
1195                                }
1196                            }
1197
1198                            Err(anyhow!("didn't receive login redirect"))
1199                        })
1200                        .await?;
1201
1202                    let access_token = private_key
1203                        .decrypt_string(&access_token)
1204                        .context("failed to decrypt access token")?;
1205
1206                    Ok(Credentials::User {
1207                        user_id: user_id.parse()?,
1208                        access_token,
1209                    })
1210                })
1211                .await?;
1212
1213            cx.update(|cx| cx.activate(true))?;
1214            Ok(credentials)
1215        })
1216    }
1217
1218    async fn authenticate_as_admin(
1219        http: Arc<HttpClientWithUrl>,
1220        login: String,
1221        mut api_token: String,
1222    ) -> Result<Credentials> {
1223        #[derive(Deserialize)]
1224        struct AuthenticatedUserResponse {
1225            user: User,
1226        }
1227
1228        #[derive(Deserialize)]
1229        struct User {
1230            id: u64,
1231        }
1232
1233        // Use the collab server's admin API to retrieve the id
1234        // of the impersonated user.
1235        let mut url = Self::get_rpc_url(http.clone(), None).await?;
1236        url.set_path("/user");
1237        url.set_query(Some(&format!("github_login={login}")));
1238        let request = Request::get(url.as_str())
1239            .header("Authorization", format!("token {api_token}"))
1240            .body("".into())?;
1241
1242        let mut response = http.send(request).await?;
1243        let mut body = String::new();
1244        response.body_mut().read_to_string(&mut body).await?;
1245        if !response.status().is_success() {
1246            Err(anyhow!(
1247                "admin user request failed {} - {}",
1248                response.status().as_u16(),
1249                body,
1250            ))?;
1251        }
1252        let response: AuthenticatedUserResponse = serde_json::from_str(&body)?;
1253
1254        // Use the admin API token to authenticate as the impersonated user.
1255        api_token.insert_str(0, "ADMIN_TOKEN:");
1256        Ok(Credentials::User {
1257            user_id: response.user.id,
1258            access_token: api_token,
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}