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