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