client.rs

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