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