client.rs

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