client.rs

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