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