client.rs

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