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 settings::ReleaseChannel;
  32use std::{
  33    any::TypeId,
  34    collections::HashMap,
  35    convert::TryFrom,
  36    fmt::Write as _,
  37    future::Future,
  38    path::PathBuf,
  39    sync::{Arc, Weak},
  40    time::{Duration, Instant},
  41};
  42use telemetry::Telemetry;
  43use thiserror::Error;
  44use url::Url;
  45use util::{ResultExt, TryFutureExt};
  46
  47pub use channel::*;
  48pub use rpc::*;
  49pub use user::*;
  50
  51lazy_static! {
  52    pub static ref ZED_SERVER_URL: String =
  53        std::env::var("ZED_SERVER_URL").unwrap_or_else(|_| "https://zed.dev".to_string());
  54    pub static ref IMPERSONATE_LOGIN: Option<String> = std::env::var("ZED_IMPERSONATE")
  55        .ok()
  56        .and_then(|s| if s.is_empty() { None } else { Some(s) });
  57    pub static ref ADMIN_API_TOKEN: Option<String> = std::env::var("ZED_ADMIN_API_TOKEN")
  58        .ok()
  59        .and_then(|s| if s.is_empty() { None } else { Some(s) });
  60}
  61
  62pub const ZED_SECRET_CLIENT_TOKEN: &str = "618033988749894";
  63pub const INITIAL_RECONNECTION_DELAY: Duration = Duration::from_millis(100);
  64pub const CONNECTION_TIMEOUT: Duration = Duration::from_secs(5);
  65
  66actions!(client, [Authenticate]);
  67
  68pub fn init(client: Arc<Client>, cx: &mut MutableAppContext) {
  69    cx.add_global_action({
  70        let client = client.clone();
  71        move |_: &Authenticate, cx| {
  72            let client = client.clone();
  73            cx.spawn(
  74                |cx| async move { client.authenticate_and_connect(true, &cx).log_err().await },
  75            )
  76            .detach();
  77        }
  78    });
  79}
  80
  81pub struct Client {
  82    id: usize,
  83    peer: Arc<Peer>,
  84    http: Arc<dyn HttpClient>,
  85    telemetry: Arc<Telemetry>,
  86    state: RwLock<ClientState>,
  87
  88    #[allow(clippy::type_complexity)]
  89    #[cfg(any(test, feature = "test-support"))]
  90    authenticate: RwLock<
  91        Option<Box<dyn 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>>>,
  92    >,
  93
  94    #[allow(clippy::type_complexity)]
  95    #[cfg(any(test, feature = "test-support"))]
  96    establish_connection: RwLock<
  97        Option<
  98            Box<
  99                dyn 'static
 100                    + Send
 101                    + Sync
 102                    + Fn(
 103                        &Credentials,
 104                        &AsyncAppContext,
 105                    ) -> Task<Result<Connection, EstablishConnectionError>>,
 106            >,
 107        >,
 108    >,
 109}
 110
 111#[derive(Error, Debug)]
 112pub enum EstablishConnectionError {
 113    #[error("upgrade required")]
 114    UpgradeRequired,
 115    #[error("unauthorized")]
 116    Unauthorized,
 117    #[error("{0}")]
 118    Other(#[from] anyhow::Error),
 119    #[error("{0}")]
 120    Http(#[from] http::Error),
 121    #[error("{0}")]
 122    Io(#[from] std::io::Error),
 123    #[error("{0}")]
 124    Websocket(#[from] async_tungstenite::tungstenite::http::Error),
 125}
 126
 127impl From<WebsocketError> for EstablishConnectionError {
 128    fn from(error: WebsocketError) -> Self {
 129        if let WebsocketError::Http(response) = &error {
 130            match response.status() {
 131                StatusCode::UNAUTHORIZED => return EstablishConnectionError::Unauthorized,
 132                StatusCode::UPGRADE_REQUIRED => return EstablishConnectionError::UpgradeRequired,
 133                _ => {}
 134            }
 135        }
 136        EstablishConnectionError::Other(error.into())
 137    }
 138}
 139
 140impl EstablishConnectionError {
 141    pub fn other(error: impl Into<anyhow::Error> + Send + Sync) -> Self {
 142        Self::Other(error.into())
 143    }
 144}
 145
 146#[derive(Copy, Clone, Debug, Eq, PartialEq)]
 147pub enum Status {
 148    SignedOut,
 149    UpgradeRequired,
 150    Authenticating,
 151    Connecting,
 152    ConnectionError,
 153    Connected {
 154        peer_id: PeerId,
 155        connection_id: ConnectionId,
 156    },
 157    ConnectionLost,
 158    Reauthenticating,
 159    Reconnecting,
 160    ReconnectionError {
 161        next_reconnection: Instant,
 162    },
 163}
 164
 165impl Status {
 166    pub fn is_connected(&self) -> bool {
 167        matches!(self, Self::Connected { .. })
 168    }
 169}
 170
 171struct ClientState {
 172    credentials: Option<Credentials>,
 173    status: (watch::Sender<Status>, watch::Receiver<Status>),
 174    entity_id_extractors: HashMap<TypeId, fn(&dyn AnyTypedEnvelope) -> u64>,
 175    _reconnect_task: Option<Task<()>>,
 176    reconnect_interval: Duration,
 177    entities_by_type_and_remote_id: HashMap<(TypeId, u64), AnyWeakEntityHandle>,
 178    models_by_message_type: HashMap<TypeId, AnyWeakModelHandle>,
 179    entity_types_by_message_type: HashMap<TypeId, TypeId>,
 180    #[allow(clippy::type_complexity)]
 181    message_handlers: HashMap<
 182        TypeId,
 183        Arc<
 184            dyn Send
 185                + Sync
 186                + Fn(
 187                    AnyEntityHandle,
 188                    Box<dyn AnyTypedEnvelope>,
 189                    &Arc<Client>,
 190                    AsyncAppContext,
 191                ) -> LocalBoxFuture<'static, Result<()>>,
 192        >,
 193    >,
 194}
 195
 196enum AnyWeakEntityHandle {
 197    Model(AnyWeakModelHandle),
 198    View(AnyWeakViewHandle),
 199}
 200
 201enum AnyEntityHandle {
 202    Model(AnyModelHandle),
 203    View(AnyViewHandle),
 204}
 205
 206#[derive(Clone, Debug)]
 207pub struct Credentials {
 208    pub user_id: u64,
 209    pub access_token: String,
 210}
 211
 212impl Default for ClientState {
 213    fn default() -> Self {
 214        Self {
 215            credentials: None,
 216            status: watch::channel_with(Status::SignedOut),
 217            entity_id_extractors: Default::default(),
 218            _reconnect_task: None,
 219            reconnect_interval: Duration::from_secs(5),
 220            models_by_message_type: Default::default(),
 221            entities_by_type_and_remote_id: Default::default(),
 222            entity_types_by_message_type: Default::default(),
 223            message_handlers: Default::default(),
 224        }
 225    }
 226}
 227
 228pub enum Subscription {
 229    Entity {
 230        client: Weak<Client>,
 231        id: (TypeId, u64),
 232    },
 233    Message {
 234        client: Weak<Client>,
 235        id: TypeId,
 236    },
 237}
 238
 239impl Drop for Subscription {
 240    fn drop(&mut self) {
 241        match self {
 242            Subscription::Entity { client, id } => {
 243                if let Some(client) = client.upgrade() {
 244                    let mut state = client.state.write();
 245                    let _ = state.entities_by_type_and_remote_id.remove(id);
 246                }
 247            }
 248            Subscription::Message { client, id } => {
 249                if let Some(client) = client.upgrade() {
 250                    let mut state = client.state.write();
 251                    let _ = state.entity_types_by_message_type.remove(id);
 252                    let _ = state.message_handlers.remove(id);
 253                }
 254            }
 255        }
 256    }
 257}
 258
 259impl Client {
 260    pub fn new(http: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
 261        Arc::new(Self {
 262            id: 0,
 263            peer: Peer::new(),
 264            telemetry: Telemetry::new(http.clone(), cx),
 265            http,
 266            state: Default::default(),
 267
 268            #[cfg(any(test, feature = "test-support"))]
 269            authenticate: Default::default(),
 270            #[cfg(any(test, feature = "test-support"))]
 271            establish_connection: Default::default(),
 272        })
 273    }
 274
 275    pub fn id(&self) -> usize {
 276        self.id
 277    }
 278
 279    pub fn http_client(&self) -> Arc<dyn HttpClient> {
 280        self.http.clone()
 281    }
 282
 283    #[cfg(any(test, feature = "test-support"))]
 284    pub fn set_id(&mut self, id: usize) -> &Self {
 285        self.id = id;
 286        self
 287    }
 288
 289    #[cfg(any(test, feature = "test-support"))]
 290    pub fn tear_down(&self) {
 291        let mut state = self.state.write();
 292        state._reconnect_task.take();
 293        state.message_handlers.clear();
 294        state.models_by_message_type.clear();
 295        state.entities_by_type_and_remote_id.clear();
 296        state.entity_id_extractors.clear();
 297        self.peer.reset();
 298    }
 299
 300    #[cfg(any(test, feature = "test-support"))]
 301    pub fn override_authenticate<F>(&self, authenticate: F) -> &Self
 302    where
 303        F: 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>,
 304    {
 305        *self.authenticate.write() = Some(Box::new(authenticate));
 306        self
 307    }
 308
 309    #[cfg(any(test, feature = "test-support"))]
 310    pub fn override_establish_connection<F>(&self, connect: F) -> &Self
 311    where
 312        F: 'static
 313            + Send
 314            + Sync
 315            + Fn(&Credentials, &AsyncAppContext) -> Task<Result<Connection, EstablishConnectionError>>,
 316    {
 317        *self.establish_connection.write() = Some(Box::new(connect));
 318        self
 319    }
 320
 321    pub fn user_id(&self) -> Option<u64> {
 322        self.state
 323            .read()
 324            .credentials
 325            .as_ref()
 326            .map(|credentials| credentials.user_id)
 327    }
 328
 329    pub fn peer_id(&self) -> Option<PeerId> {
 330        if let Status::Connected { peer_id, .. } = &*self.status().borrow() {
 331            Some(*peer_id)
 332        } else {
 333            None
 334        }
 335    }
 336
 337    pub fn status(&self) -> watch::Receiver<Status> {
 338        self.state.read().status.1.clone()
 339    }
 340
 341    fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncAppContext) {
 342        log::info!("set status on client {}: {:?}", self.id, status);
 343        let mut state = self.state.write();
 344        *state.status.0.borrow_mut() = status;
 345
 346        match status {
 347            Status::Connected { .. } => {
 348                state._reconnect_task = None;
 349            }
 350            Status::ConnectionLost => {
 351                let this = self.clone();
 352                let reconnect_interval = state.reconnect_interval;
 353                state._reconnect_task = Some(cx.spawn(|cx| async move {
 354                    let mut rng = StdRng::from_entropy();
 355                    let mut delay = INITIAL_RECONNECTION_DELAY;
 356                    while let Err(error) = this.authenticate_and_connect(true, &cx).await {
 357                        log::error!("failed to connect {}", error);
 358                        if matches!(*this.status().borrow(), Status::ConnectionError) {
 359                            this.set_status(
 360                                Status::ReconnectionError {
 361                                    next_reconnection: Instant::now() + delay,
 362                                },
 363                                &cx,
 364                            );
 365                            cx.background().timer(delay).await;
 366                            delay = delay
 367                                .mul_f32(rng.gen_range(1.0..=2.0))
 368                                .min(reconnect_interval);
 369                        } else {
 370                            break;
 371                        }
 372                    }
 373                }));
 374            }
 375            Status::SignedOut | Status::UpgradeRequired => {
 376                self.telemetry.set_authenticated_user_info(None, false);
 377                state._reconnect_task.take();
 378            }
 379            _ => {}
 380        }
 381    }
 382
 383    pub fn add_view_for_remote_entity<T: View>(
 384        self: &Arc<Self>,
 385        remote_id: u64,
 386        cx: &mut ViewContext<T>,
 387    ) -> Subscription {
 388        let id = (TypeId::of::<T>(), remote_id);
 389        self.state
 390            .write()
 391            .entities_by_type_and_remote_id
 392            .insert(id, AnyWeakEntityHandle::View(cx.weak_handle().into()));
 393        Subscription::Entity {
 394            client: Arc::downgrade(self),
 395            id,
 396        }
 397    }
 398
 399    pub fn add_model_for_remote_entity<T: Entity>(
 400        self: &Arc<Self>,
 401        remote_id: u64,
 402        cx: &mut ModelContext<T>,
 403    ) -> Subscription {
 404        let id = (TypeId::of::<T>(), remote_id);
 405        self.state
 406            .write()
 407            .entities_by_type_and_remote_id
 408            .insert(id, AnyWeakEntityHandle::Model(cx.weak_handle().into()));
 409        Subscription::Entity {
 410            client: Arc::downgrade(self),
 411            id,
 412        }
 413    }
 414
 415    pub fn add_message_handler<M, E, H, F>(
 416        self: &Arc<Self>,
 417        model: ModelHandle<E>,
 418        handler: H,
 419    ) -> Subscription
 420    where
 421        M: EnvelopedMessage,
 422        E: Entity,
 423        H: 'static
 424            + Send
 425            + Sync
 426            + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 427        F: 'static + Future<Output = Result<()>>,
 428    {
 429        let message_type_id = TypeId::of::<M>();
 430
 431        let mut state = self.state.write();
 432        state
 433            .models_by_message_type
 434            .insert(message_type_id, model.downgrade().into());
 435
 436        let prev_handler = state.message_handlers.insert(
 437            message_type_id,
 438            Arc::new(move |handle, envelope, client, cx| {
 439                let handle = if let AnyEntityHandle::Model(handle) = handle {
 440                    handle
 441                } else {
 442                    unreachable!();
 443                };
 444                let model = handle.downcast::<E>().unwrap();
 445                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 446                handler(model, *envelope, client.clone(), cx).boxed_local()
 447            }),
 448        );
 449        if prev_handler.is_some() {
 450            panic!("registered handler for the same message twice");
 451        }
 452
 453        Subscription::Message {
 454            client: Arc::downgrade(self),
 455            id: message_type_id,
 456        }
 457    }
 458
 459    pub fn add_request_handler<M, E, H, F>(
 460        self: &Arc<Self>,
 461        model: ModelHandle<E>,
 462        handler: H,
 463    ) -> Subscription
 464    where
 465        M: RequestMessage,
 466        E: Entity,
 467        H: 'static
 468            + Send
 469            + Sync
 470            + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 471        F: 'static + Future<Output = Result<M::Response>>,
 472    {
 473        self.add_message_handler(model, move |handle, envelope, this, cx| {
 474            Self::respond_to_request(
 475                envelope.receipt(),
 476                handler(handle, envelope, this.clone(), cx),
 477                this,
 478            )
 479        })
 480    }
 481
 482    pub fn add_view_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
 483    where
 484        M: EntityMessage,
 485        E: View,
 486        H: 'static
 487            + Send
 488            + Sync
 489            + Fn(ViewHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 490        F: 'static + Future<Output = Result<()>>,
 491    {
 492        self.add_entity_message_handler::<M, E, _, _>(move |handle, message, client, cx| {
 493            if let AnyEntityHandle::View(handle) = handle {
 494                handler(handle.downcast::<E>().unwrap(), message, client, cx)
 495            } else {
 496                unreachable!();
 497            }
 498        })
 499    }
 500
 501    pub fn add_model_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
 502    where
 503        M: EntityMessage,
 504        E: Entity,
 505        H: 'static
 506            + Send
 507            + Sync
 508            + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 509        F: 'static + Future<Output = Result<()>>,
 510    {
 511        self.add_entity_message_handler::<M, E, _, _>(move |handle, message, client, cx| {
 512            if let AnyEntityHandle::Model(handle) = handle {
 513                handler(handle.downcast::<E>().unwrap(), message, client, cx)
 514            } else {
 515                unreachable!();
 516            }
 517        })
 518    }
 519
 520    fn add_entity_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
 521    where
 522        M: EntityMessage,
 523        E: Entity,
 524        H: 'static
 525            + Send
 526            + Sync
 527            + Fn(AnyEntityHandle, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 528        F: 'static + Future<Output = Result<()>>,
 529    {
 530        let model_type_id = TypeId::of::<E>();
 531        let message_type_id = TypeId::of::<M>();
 532
 533        let mut state = self.state.write();
 534        state
 535            .entity_types_by_message_type
 536            .insert(message_type_id, model_type_id);
 537        state
 538            .entity_id_extractors
 539            .entry(message_type_id)
 540            .or_insert_with(|| {
 541                |envelope| {
 542                    envelope
 543                        .as_any()
 544                        .downcast_ref::<TypedEnvelope<M>>()
 545                        .unwrap()
 546                        .payload
 547                        .remote_entity_id()
 548                }
 549            });
 550        let prev_handler = state.message_handlers.insert(
 551            message_type_id,
 552            Arc::new(move |handle, envelope, client, cx| {
 553                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 554                handler(handle, *envelope, client.clone(), cx).boxed_local()
 555            }),
 556        );
 557        if prev_handler.is_some() {
 558            panic!("registered handler for the same message twice");
 559        }
 560    }
 561
 562    pub fn add_model_request_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
 563    where
 564        M: EntityMessage + RequestMessage,
 565        E: Entity,
 566        H: 'static
 567            + Send
 568            + Sync
 569            + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 570        F: 'static + Future<Output = Result<M::Response>>,
 571    {
 572        self.add_model_message_handler(move |entity, envelope, client, cx| {
 573            Self::respond_to_request::<M, _>(
 574                envelope.receipt(),
 575                handler(entity, envelope, client.clone(), cx),
 576                client,
 577            )
 578        })
 579    }
 580
 581    pub fn add_view_request_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
 582    where
 583        M: EntityMessage + RequestMessage,
 584        E: View,
 585        H: 'static
 586            + Send
 587            + Sync
 588            + Fn(ViewHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 589        F: 'static + Future<Output = Result<M::Response>>,
 590    {
 591        self.add_view_message_handler(move |entity, envelope, client, cx| {
 592            Self::respond_to_request::<M, _>(
 593                envelope.receipt(),
 594                handler(entity, envelope, client.clone(), cx),
 595                client,
 596            )
 597        })
 598    }
 599
 600    async fn respond_to_request<T: RequestMessage, F: Future<Output = Result<T::Response>>>(
 601        receipt: Receipt<T>,
 602        response: F,
 603        client: Arc<Self>,
 604    ) -> Result<()> {
 605        match response.await {
 606            Ok(response) => {
 607                client.respond(receipt, response)?;
 608                Ok(())
 609            }
 610            Err(error) => {
 611                client.respond_with_error(
 612                    receipt,
 613                    proto::Error {
 614                        message: format!("{:?}", error),
 615                    },
 616                )?;
 617                Err(error)
 618            }
 619        }
 620    }
 621
 622    pub fn has_keychain_credentials(&self, cx: &AsyncAppContext) -> bool {
 623        read_credentials_from_keychain(cx).is_some()
 624    }
 625
 626    #[async_recursion(?Send)]
 627    pub async fn authenticate_and_connect(
 628        self: &Arc<Self>,
 629        try_keychain: bool,
 630        cx: &AsyncAppContext,
 631    ) -> anyhow::Result<()> {
 632        let was_disconnected = match *self.status().borrow() {
 633            Status::SignedOut => true,
 634            Status::ConnectionError
 635            | Status::ConnectionLost
 636            | Status::Authenticating { .. }
 637            | Status::Reauthenticating { .. }
 638            | Status::ReconnectionError { .. } => false,
 639            Status::Connected { .. } | Status::Connecting { .. } | Status::Reconnecting { .. } => {
 640                return Ok(())
 641            }
 642            Status::UpgradeRequired => return Err(EstablishConnectionError::UpgradeRequired)?,
 643        };
 644
 645        if was_disconnected {
 646            self.set_status(Status::Authenticating, cx);
 647        } else {
 648            self.set_status(Status::Reauthenticating, cx)
 649        }
 650
 651        let mut read_from_keychain = false;
 652        let mut credentials = self.state.read().credentials.clone();
 653        if credentials.is_none() && try_keychain {
 654            credentials = read_credentials_from_keychain(cx);
 655            read_from_keychain = credentials.is_some();
 656            if read_from_keychain {
 657                self.report_event("read credentials from keychain", Default::default());
 658            }
 659        }
 660        if credentials.is_none() {
 661            let mut status_rx = self.status();
 662            let _ = status_rx.next().await;
 663            futures::select_biased! {
 664                authenticate = self.authenticate(cx).fuse() => {
 665                    match authenticate {
 666                        Ok(creds) => credentials = Some(creds),
 667                        Err(err) => {
 668                            self.set_status(Status::ConnectionError, cx);
 669                            return Err(err);
 670                        }
 671                    }
 672                }
 673                _ = status_rx.next().fuse() => {
 674                    return Err(anyhow!("authentication canceled"));
 675                }
 676            }
 677        }
 678        let credentials = credentials.unwrap();
 679
 680        if was_disconnected {
 681            self.set_status(Status::Connecting, cx);
 682        } else {
 683            self.set_status(Status::Reconnecting, cx);
 684        }
 685
 686        let mut timeout = cx.background().timer(CONNECTION_TIMEOUT).fuse();
 687        futures::select_biased! {
 688            connection = self.establish_connection(&credentials, cx).fuse() => {
 689                match connection {
 690                    Ok(conn) => {
 691                        self.state.write().credentials = Some(credentials.clone());
 692                        if !read_from_keychain && IMPERSONATE_LOGIN.is_none() {
 693                            write_credentials_to_keychain(&credentials, cx).log_err();
 694                        }
 695
 696                        futures::select_biased! {
 697                            result = self.set_connection(conn, cx).fuse() => result,
 698                            _ = timeout => {
 699                                self.set_status(Status::ConnectionError, cx);
 700                                Err(anyhow!("timed out waiting on hello message from server"))
 701                            }
 702                        }
 703                    }
 704                    Err(EstablishConnectionError::Unauthorized) => {
 705                        self.state.write().credentials.take();
 706                        if read_from_keychain {
 707                            cx.platform().delete_credentials(&ZED_SERVER_URL).log_err();
 708                            self.set_status(Status::SignedOut, cx);
 709                            self.authenticate_and_connect(false, cx).await
 710                        } else {
 711                            self.set_status(Status::ConnectionError, cx);
 712                            Err(EstablishConnectionError::Unauthorized)?
 713                        }
 714                    }
 715                    Err(EstablishConnectionError::UpgradeRequired) => {
 716                        self.set_status(Status::UpgradeRequired, cx);
 717                        Err(EstablishConnectionError::UpgradeRequired)?
 718                    }
 719                    Err(error) => {
 720                        self.set_status(Status::ConnectionError, cx);
 721                        Err(error)?
 722                    }
 723                }
 724            }
 725            _ = &mut timeout => {
 726                self.set_status(Status::ConnectionError, cx);
 727                Err(anyhow!("timed out trying to establish connection"))
 728            }
 729        }
 730    }
 731
 732    async fn set_connection(
 733        self: &Arc<Self>,
 734        conn: Connection,
 735        cx: &AsyncAppContext,
 736    ) -> Result<()> {
 737        let executor = cx.background();
 738        log::info!("add connection to peer");
 739        let (connection_id, handle_io, mut incoming) = self
 740            .peer
 741            .add_connection(conn, move |duration| executor.timer(duration));
 742        let handle_io = cx.background().spawn(handle_io);
 743
 744        let peer_id = async {
 745            log::info!("waiting for server hello");
 746            let message = incoming
 747                .next()
 748                .await
 749                .ok_or_else(|| anyhow!("no hello message received"))?;
 750            log::info!("got server hello");
 751            let hello_message_type_name = message.payload_type_name().to_string();
 752            let hello = message
 753                .into_any()
 754                .downcast::<TypedEnvelope<proto::Hello>>()
 755                .map_err(|_| {
 756                    anyhow!(
 757                        "invalid hello message received: {:?}",
 758                        hello_message_type_name
 759                    )
 760                })?;
 761            Ok(PeerId(hello.payload.peer_id))
 762        };
 763
 764        let peer_id = match peer_id.await {
 765            Ok(peer_id) => peer_id,
 766            Err(error) => {
 767                self.peer.disconnect(connection_id);
 768                return Err(error);
 769            }
 770        };
 771
 772        log::info!(
 773            "set status to connected (connection id: {}, peer id: {})",
 774            connection_id,
 775            peer_id
 776        );
 777        self.set_status(
 778            Status::Connected {
 779                peer_id,
 780                connection_id,
 781            },
 782            cx,
 783        );
 784        cx.foreground()
 785            .spawn({
 786                let cx = cx.clone();
 787                let this = self.clone();
 788                async move {
 789                    let mut message_id = 0_usize;
 790                    while let Some(message) = incoming.next().await {
 791                        let mut state = this.state.write();
 792                        message_id += 1;
 793                        let type_name = message.payload_type_name();
 794                        let payload_type_id = message.payload_type_id();
 795                        let sender_id = message.original_sender_id().map(|id| id.0);
 796
 797                        let model = state
 798                            .models_by_message_type
 799                            .get(&payload_type_id)
 800                            .and_then(|model| model.upgrade(&cx))
 801                            .map(AnyEntityHandle::Model)
 802                            .or_else(|| {
 803                                let entity_type_id =
 804                                    *state.entity_types_by_message_type.get(&payload_type_id)?;
 805                                let entity_id = state
 806                                    .entity_id_extractors
 807                                    .get(&message.payload_type_id())
 808                                    .map(|extract_entity_id| {
 809                                        (extract_entity_id)(message.as_ref())
 810                                    })?;
 811
 812                                let entity = state
 813                                    .entities_by_type_and_remote_id
 814                                    .get(&(entity_type_id, entity_id))?;
 815                                if let Some(entity) = entity.upgrade(&cx) {
 816                                    Some(entity)
 817                                } else {
 818                                    state
 819                                        .entities_by_type_and_remote_id
 820                                        .remove(&(entity_type_id, entity_id));
 821                                    None
 822                                }
 823                            });
 824
 825                        let model = if let Some(model) = model {
 826                            model
 827                        } else {
 828                            log::info!("unhandled message {}", type_name);
 829                            continue;
 830                        };
 831
 832                        if let Some(handler) = state.message_handlers.get(&payload_type_id).cloned()
 833                        {
 834                            drop(state); // Avoid deadlocks if the handler interacts with rpc::Client
 835                            let future = handler(model, message, &this, cx.clone());
 836
 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, db: Db) {
1221        self.telemetry.start(db.clone());
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}