client.rs

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