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