client.rs

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