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