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_rx.next().fuse() => {
 802                    return Err(anyhow!("authentication canceled"));
 803                }
 804            }
 805        }
 806        let credentials = credentials.unwrap();
 807        self.set_id(credentials.user_id);
 808
 809        if was_disconnected {
 810            self.set_status(Status::Connecting, cx);
 811        } else {
 812            self.set_status(Status::Reconnecting, cx);
 813        }
 814
 815        let mut timeout = cx.background().timer(CONNECTION_TIMEOUT).fuse();
 816        futures::select_biased! {
 817            connection = self.establish_connection(&credentials, cx).fuse() => {
 818                match connection {
 819                    Ok(conn) => {
 820                        self.state.write().credentials = Some(credentials.clone());
 821                        if !read_from_keychain && IMPERSONATE_LOGIN.is_none() {
 822                            write_credentials_to_keychain(&credentials, cx).log_err();
 823                        }
 824
 825                        futures::select_biased! {
 826                            result = self.set_connection(conn, cx).fuse() => result,
 827                            _ = timeout => {
 828                                self.set_status(Status::ConnectionError, cx);
 829                                Err(anyhow!("timed out waiting on hello message from server"))
 830                            }
 831                        }
 832                    }
 833                    Err(EstablishConnectionError::Unauthorized) => {
 834                        self.state.write().credentials.take();
 835                        if read_from_keychain {
 836                            cx.platform().delete_credentials(&ZED_SERVER_URL).log_err();
 837                            self.set_status(Status::SignedOut, cx);
 838                            self.authenticate_and_connect(false, cx).await
 839                        } else {
 840                            self.set_status(Status::ConnectionError, cx);
 841                            Err(EstablishConnectionError::Unauthorized)?
 842                        }
 843                    }
 844                    Err(EstablishConnectionError::UpgradeRequired) => {
 845                        self.set_status(Status::UpgradeRequired, cx);
 846                        Err(EstablishConnectionError::UpgradeRequired)?
 847                    }
 848                    Err(error) => {
 849                        self.set_status(Status::ConnectionError, cx);
 850                        Err(error)?
 851                    }
 852                }
 853            }
 854            _ = &mut timeout => {
 855                self.set_status(Status::ConnectionError, cx);
 856                Err(anyhow!("timed out trying to establish connection"))
 857            }
 858        }
 859    }
 860
 861    async fn set_connection(
 862        self: &Arc<Self>,
 863        conn: Connection,
 864        cx: &AsyncAppContext,
 865    ) -> Result<()> {
 866        let executor = cx.background();
 867        log::info!("add connection to peer");
 868        let (connection_id, handle_io, mut incoming) = self
 869            .peer
 870            .add_connection(conn, move |duration| executor.timer(duration));
 871        let handle_io = cx.background().spawn(handle_io);
 872
 873        let peer_id = async {
 874            log::info!("waiting for server hello");
 875            let message = incoming
 876                .next()
 877                .await
 878                .ok_or_else(|| anyhow!("no hello message received"))?;
 879            log::info!("got server hello");
 880            let hello_message_type_name = message.payload_type_name().to_string();
 881            let hello = message
 882                .into_any()
 883                .downcast::<TypedEnvelope<proto::Hello>>()
 884                .map_err(|_| {
 885                    anyhow!(
 886                        "invalid hello message received: {:?}",
 887                        hello_message_type_name
 888                    )
 889                })?;
 890            let peer_id = hello
 891                .payload
 892                .peer_id
 893                .ok_or_else(|| anyhow!("invalid peer id"))?;
 894            Ok(peer_id)
 895        };
 896
 897        let peer_id = match peer_id.await {
 898            Ok(peer_id) => peer_id,
 899            Err(error) => {
 900                self.peer.disconnect(connection_id);
 901                return Err(error);
 902            }
 903        };
 904
 905        log::info!(
 906            "set status to connected (connection id: {:?}, peer id: {:?})",
 907            connection_id,
 908            peer_id
 909        );
 910        self.set_status(
 911            Status::Connected {
 912                peer_id,
 913                connection_id,
 914            },
 915            cx,
 916        );
 917        cx.foreground()
 918            .spawn({
 919                let cx = cx.clone();
 920                let this = self.clone();
 921                async move {
 922                    while let Some(message) = incoming.next().await {
 923                        this.handle_message(message, &cx);
 924                        // Don't starve the main thread when receiving lots of messages at once.
 925                        smol::future::yield_now().await;
 926                    }
 927                }
 928            })
 929            .detach();
 930
 931        let this = self.clone();
 932        let cx = cx.clone();
 933        cx.foreground()
 934            .spawn(async move {
 935                match handle_io.await {
 936                    Ok(()) => {
 937                        if this.status().borrow().clone()
 938                            == (Status::Connected {
 939                                connection_id,
 940                                peer_id,
 941                            })
 942                        {
 943                            this.set_status(Status::SignedOut, &cx);
 944                        }
 945                    }
 946                    Err(err) => {
 947                        log::error!("connection error: {:?}", err);
 948                        this.set_status(Status::ConnectionLost, &cx);
 949                    }
 950                }
 951            })
 952            .detach();
 953
 954        Ok(())
 955    }
 956
 957    fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
 958        #[cfg(any(test, feature = "test-support"))]
 959        if let Some(callback) = self.authenticate.read().as_ref() {
 960            return callback(cx);
 961        }
 962
 963        self.authenticate_with_browser(cx)
 964    }
 965
 966    fn establish_connection(
 967        self: &Arc<Self>,
 968        credentials: &Credentials,
 969        cx: &AsyncAppContext,
 970    ) -> Task<Result<Connection, EstablishConnectionError>> {
 971        #[cfg(any(test, feature = "test-support"))]
 972        if let Some(callback) = self.establish_connection.read().as_ref() {
 973            return callback(credentials, cx);
 974        }
 975
 976        self.establish_websocket_connection(credentials, cx)
 977    }
 978
 979    async fn get_rpc_url(http: Arc<dyn HttpClient>, is_preview: bool) -> Result<Url> {
 980        let preview_param = if is_preview { "?preview=1" } else { "" };
 981        let url = format!("{}/rpc{preview_param}", *ZED_SERVER_URL);
 982        let response = http.get(&url, Default::default(), false).await?;
 983
 984        // Normally, ZED_SERVER_URL is set to the URL of zed.dev website.
 985        // The website's /rpc endpoint redirects to a collab server's /rpc endpoint,
 986        // which requires authorization via an HTTP header.
 987        //
 988        // For testing purposes, ZED_SERVER_URL can also set to the direct URL of
 989        // of a collab server. In that case, a request to the /rpc endpoint will
 990        // return an 'unauthorized' response.
 991        let collab_url = if response.status().is_redirection() {
 992            response
 993                .headers()
 994                .get("Location")
 995                .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
 996                .to_str()
 997                .map_err(EstablishConnectionError::other)?
 998                .to_string()
 999        } else if response.status() == StatusCode::UNAUTHORIZED {
1000            url
1001        } else {
1002            Err(anyhow!(
1003                "unexpected /rpc response status {}",
1004                response.status()
1005            ))?
1006        };
1007
1008        Url::parse(&collab_url).context("invalid rpc url")
1009    }
1010
1011    fn establish_websocket_connection(
1012        self: &Arc<Self>,
1013        credentials: &Credentials,
1014        cx: &AsyncAppContext,
1015    ) -> Task<Result<Connection, EstablishConnectionError>> {
1016        let use_preview_server = cx.read(|cx| {
1017            if cx.has_global::<ReleaseChannel>() {
1018                *cx.global::<ReleaseChannel>() != ReleaseChannel::Stable
1019            } else {
1020                false
1021            }
1022        });
1023
1024        let request = Request::builder()
1025            .header(
1026                "Authorization",
1027                format!("{} {}", credentials.user_id, credentials.access_token),
1028            )
1029            .header("x-zed-protocol-version", rpc::PROTOCOL_VERSION);
1030
1031        let http = self.http.clone();
1032        cx.background().spawn(async move {
1033            let mut rpc_url = Self::get_rpc_url(http, use_preview_server).await?;
1034            let rpc_host = rpc_url
1035                .host_str()
1036                .zip(rpc_url.port_or_known_default())
1037                .ok_or_else(|| anyhow!("missing host in rpc url"))?;
1038            let stream = smol::net::TcpStream::connect(rpc_host).await?;
1039
1040            log::info!("connected to rpc endpoint {}", rpc_url);
1041
1042            match rpc_url.scheme() {
1043                "https" => {
1044                    rpc_url.set_scheme("wss").unwrap();
1045                    let request = request.uri(rpc_url.as_str()).body(())?;
1046                    let (stream, _) =
1047                        async_tungstenite::async_tls::client_async_tls(request, stream).await?;
1048                    Ok(Connection::new(
1049                        stream
1050                            .map_err(|error| anyhow!(error))
1051                            .sink_map_err(|error| anyhow!(error)),
1052                    ))
1053                }
1054                "http" => {
1055                    rpc_url.set_scheme("ws").unwrap();
1056                    let request = request.uri(rpc_url.as_str()).body(())?;
1057                    let (stream, _) = async_tungstenite::client_async(request, stream).await?;
1058                    Ok(Connection::new(
1059                        stream
1060                            .map_err(|error| anyhow!(error))
1061                            .sink_map_err(|error| anyhow!(error)),
1062                    ))
1063                }
1064                _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
1065            }
1066        })
1067    }
1068
1069    pub fn authenticate_with_browser(
1070        self: &Arc<Self>,
1071        cx: &AsyncAppContext,
1072    ) -> Task<Result<Credentials>> {
1073        let platform = cx.platform();
1074        let executor = cx.background();
1075        let http = self.http.clone();
1076
1077        executor.clone().spawn(async move {
1078            // Generate a pair of asymmetric encryption keys. The public key will be used by the
1079            // zed server to encrypt the user's access token, so that it can'be intercepted by
1080            // any other app running on the user's device.
1081            let (public_key, private_key) =
1082                rpc::auth::keypair().expect("failed to generate keypair for auth");
1083            let public_key_string =
1084                String::try_from(public_key).expect("failed to serialize public key for auth");
1085
1086            if let Some((login, token)) = IMPERSONATE_LOGIN.as_ref().zip(ADMIN_API_TOKEN.as_ref()) {
1087                return Self::authenticate_as_admin(http, login.clone(), token.clone()).await;
1088            }
1089
1090            // Start an HTTP server to receive the redirect from Zed's sign-in page.
1091            let server = tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
1092            let port = server.server_addr().port();
1093
1094            // Open the Zed sign-in page in the user's browser, with query parameters that indicate
1095            // that the user is signing in from a Zed app running on the same device.
1096            let mut url = format!(
1097                "{}/native_app_signin?native_app_port={}&native_app_public_key={}",
1098                *ZED_SERVER_URL, port, public_key_string
1099            );
1100
1101            if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
1102                log::info!("impersonating user @{}", impersonate_login);
1103                write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
1104            }
1105
1106            platform.open_url(&url);
1107
1108            // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
1109            // access token from the query params.
1110            //
1111            // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
1112            // custom URL scheme instead of this local HTTP server.
1113            let (user_id, access_token) = executor
1114                .spawn(async move {
1115                    for _ in 0..100 {
1116                        if let Some(req) = server.recv_timeout(Duration::from_secs(1))? {
1117                            let path = req.url();
1118                            let mut user_id = None;
1119                            let mut access_token = None;
1120                            let url = Url::parse(&format!("http://example.com{}", path))
1121                                .context("failed to parse login notification url")?;
1122                            for (key, value) in url.query_pairs() {
1123                                if key == "access_token" {
1124                                    access_token = Some(value.to_string());
1125                                } else if key == "user_id" {
1126                                    user_id = Some(value.to_string());
1127                                }
1128                            }
1129
1130                            let post_auth_url =
1131                                format!("{}/native_app_signin_succeeded", *ZED_SERVER_URL);
1132                            req.respond(
1133                                tiny_http::Response::empty(302).with_header(
1134                                    tiny_http::Header::from_bytes(
1135                                        &b"Location"[..],
1136                                        post_auth_url.as_bytes(),
1137                                    )
1138                                    .unwrap(),
1139                                ),
1140                            )
1141                            .context("failed to respond to login http request")?;
1142                            return Ok((
1143                                user_id.ok_or_else(|| anyhow!("missing user_id parameter"))?,
1144                                access_token
1145                                    .ok_or_else(|| anyhow!("missing access_token parameter"))?,
1146                            ));
1147                        }
1148                    }
1149
1150                    Err(anyhow!("didn't receive login redirect"))
1151                })
1152                .await?;
1153
1154            let access_token = private_key
1155                .decrypt_string(&access_token)
1156                .context("failed to decrypt access token")?;
1157            platform.activate(true);
1158
1159            Ok(Credentials {
1160                user_id: user_id.parse()?,
1161                access_token,
1162            })
1163        })
1164    }
1165
1166    async fn authenticate_as_admin(
1167        http: Arc<dyn HttpClient>,
1168        login: String,
1169        mut api_token: String,
1170    ) -> Result<Credentials> {
1171        #[derive(Deserialize)]
1172        struct AuthenticatedUserResponse {
1173            user: User,
1174        }
1175
1176        #[derive(Deserialize)]
1177        struct User {
1178            id: u64,
1179        }
1180
1181        // Use the collab server's admin API to retrieve the id
1182        // of the impersonated user.
1183        let mut url = Self::get_rpc_url(http.clone(), false).await?;
1184        url.set_path("/user");
1185        url.set_query(Some(&format!("github_login={login}")));
1186        let request = Request::get(url.as_str())
1187            .header("Authorization", format!("token {api_token}"))
1188            .body("".into())?;
1189
1190        let mut response = http.send(request).await?;
1191        let mut body = String::new();
1192        response.body_mut().read_to_string(&mut body).await?;
1193        if !response.status().is_success() {
1194            Err(anyhow!(
1195                "admin user request failed {} - {}",
1196                response.status().as_u16(),
1197                body,
1198            ))?;
1199        }
1200        let response: AuthenticatedUserResponse = serde_json::from_str(&body)?;
1201
1202        // Use the admin API token to authenticate as the impersonated user.
1203        api_token.insert_str(0, "ADMIN_TOKEN:");
1204        Ok(Credentials {
1205            user_id: response.user.id,
1206            access_token: api_token,
1207        })
1208    }
1209
1210    pub fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) {
1211        self.peer.teardown();
1212        self.set_status(Status::SignedOut, cx);
1213    }
1214
1215    fn connection_id(&self) -> Result<ConnectionId> {
1216        if let Status::Connected { connection_id, .. } = *self.status().borrow() {
1217            Ok(connection_id)
1218        } else {
1219            Err(anyhow!("not connected"))
1220        }
1221    }
1222
1223    pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
1224        log::debug!("rpc send. client_id:{}, name:{}", self.id(), T::NAME);
1225        self.peer.send(self.connection_id()?, message)
1226    }
1227
1228    pub fn request<T: RequestMessage>(
1229        &self,
1230        request: T,
1231    ) -> impl Future<Output = Result<T::Response>> {
1232        self.request_envelope(request)
1233            .map_ok(|envelope| envelope.payload)
1234    }
1235
1236    pub fn request_envelope<T: RequestMessage>(
1237        &self,
1238        request: T,
1239    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> {
1240        let client_id = self.id();
1241        log::debug!(
1242            "rpc request start. client_id:{}. name:{}",
1243            client_id,
1244            T::NAME
1245        );
1246        let response = self
1247            .connection_id()
1248            .map(|conn_id| self.peer.request_envelope(conn_id, request));
1249        async move {
1250            let response = response?.await;
1251            log::debug!(
1252                "rpc request finish. client_id:{}. name:{}",
1253                client_id,
1254                T::NAME
1255            );
1256            response
1257        }
1258    }
1259
1260    fn respond<T: RequestMessage>(&self, receipt: Receipt<T>, response: T::Response) -> Result<()> {
1261        log::debug!("rpc respond. client_id:{}. name:{}", self.id(), T::NAME);
1262        self.peer.respond(receipt, response)
1263    }
1264
1265    fn respond_with_error<T: RequestMessage>(
1266        &self,
1267        receipt: Receipt<T>,
1268        error: proto::Error,
1269    ) -> Result<()> {
1270        log::debug!("rpc respond. client_id:{}. name:{}", self.id(), T::NAME);
1271        self.peer.respond_with_error(receipt, error)
1272    }
1273
1274    fn handle_message(
1275        self: &Arc<Client>,
1276        message: Box<dyn AnyTypedEnvelope>,
1277        cx: &AsyncAppContext,
1278    ) {
1279        let mut state = self.state.write();
1280        let type_name = message.payload_type_name();
1281        let payload_type_id = message.payload_type_id();
1282        let sender_id = message.original_sender_id();
1283
1284        let mut subscriber = None;
1285
1286        if let Some(message_model) = state
1287            .models_by_message_type
1288            .get(&payload_type_id)
1289            .and_then(|model| model.upgrade(cx))
1290        {
1291            subscriber = Some(Subscriber::Model(message_model));
1292        } else if let Some((extract_entity_id, entity_type_id)) =
1293            state.entity_id_extractors.get(&payload_type_id).zip(
1294                state
1295                    .entity_types_by_message_type
1296                    .get(&payload_type_id)
1297                    .copied(),
1298            )
1299        {
1300            let entity_id = (extract_entity_id)(message.as_ref());
1301
1302            match state
1303                .entities_by_type_and_remote_id
1304                .get_mut(&(entity_type_id, entity_id))
1305            {
1306                Some(WeakSubscriber::Pending(pending)) => {
1307                    pending.push(message);
1308                    return;
1309                }
1310                Some(weak_subscriber @ _) => match weak_subscriber {
1311                    WeakSubscriber::Model(handle) => {
1312                        subscriber = handle.upgrade(cx).map(Subscriber::Model);
1313                    }
1314                    WeakSubscriber::View(handle) => {
1315                        subscriber = Some(Subscriber::View(handle.clone()));
1316                    }
1317                    WeakSubscriber::Pending(_) => {}
1318                },
1319                _ => {}
1320            }
1321        }
1322
1323        let subscriber = if let Some(subscriber) = subscriber {
1324            subscriber
1325        } else {
1326            log::info!("unhandled message {}", type_name);
1327            self.peer.respond_with_unhandled_message(message).log_err();
1328            return;
1329        };
1330
1331        let handler = state.message_handlers.get(&payload_type_id).cloned();
1332        // Dropping the state prevents deadlocks if the handler interacts with rpc::Client.
1333        // It also ensures we don't hold the lock while yielding back to the executor, as
1334        // that might cause the executor thread driving this future to block indefinitely.
1335        drop(state);
1336
1337        if let Some(handler) = handler {
1338            let future = handler(subscriber, message, &self, cx.clone());
1339            let client_id = self.id();
1340            log::debug!(
1341                "rpc message received. client_id:{}, sender_id:{:?}, type:{}",
1342                client_id,
1343                sender_id,
1344                type_name
1345            );
1346            cx.foreground()
1347                .spawn(async move {
1348                    match future.await {
1349                        Ok(()) => {
1350                            log::debug!(
1351                                "rpc message handled. client_id:{}, sender_id:{:?}, type:{}",
1352                                client_id,
1353                                sender_id,
1354                                type_name
1355                            );
1356                        }
1357                        Err(error) => {
1358                            log::error!(
1359                                "error handling message. client_id:{}, sender_id:{:?}, type:{}, error:{:?}",
1360                                client_id,
1361                                sender_id,
1362                                type_name,
1363                                error
1364                            );
1365                        }
1366                    }
1367                })
1368                .detach();
1369        } else {
1370            log::info!("unhandled message {}", type_name);
1371            self.peer.respond_with_unhandled_message(message).log_err();
1372        }
1373    }
1374
1375    pub fn telemetry(&self) -> &Arc<Telemetry> {
1376        &self.telemetry
1377    }
1378}
1379
1380fn read_credentials_from_keychain(cx: &AsyncAppContext) -> Option<Credentials> {
1381    if IMPERSONATE_LOGIN.is_some() {
1382        return None;
1383    }
1384
1385    let (user_id, access_token) = cx
1386        .platform()
1387        .read_credentials(&ZED_SERVER_URL)
1388        .log_err()
1389        .flatten()?;
1390    Some(Credentials {
1391        user_id: user_id.parse().ok()?,
1392        access_token: String::from_utf8(access_token).ok()?,
1393    })
1394}
1395
1396fn write_credentials_to_keychain(credentials: &Credentials, cx: &AsyncAppContext) -> Result<()> {
1397    cx.platform().write_credentials(
1398        &ZED_SERVER_URL,
1399        &credentials.user_id.to_string(),
1400        credentials.access_token.as_bytes(),
1401    )
1402}
1403
1404const WORKTREE_URL_PREFIX: &str = "zed://worktrees/";
1405
1406pub fn encode_worktree_url(id: u64, access_token: &str) -> String {
1407    format!("{}{}/{}", WORKTREE_URL_PREFIX, id, access_token)
1408}
1409
1410pub fn decode_worktree_url(url: &str) -> Option<(u64, String)> {
1411    let path = url.trim().strip_prefix(WORKTREE_URL_PREFIX)?;
1412    let mut parts = path.split('/');
1413    let id = parts.next()?.parse::<u64>().ok()?;
1414    let access_token = parts.next()?;
1415    if access_token.is_empty() {
1416        return None;
1417    }
1418    Some((id, access_token.to_string()))
1419}
1420
1421#[cfg(test)]
1422mod tests {
1423    use super::*;
1424    use crate::test::FakeServer;
1425    use gpui::{executor::Deterministic, TestAppContext};
1426    use parking_lot::Mutex;
1427    use std::future;
1428    use util::http::FakeHttpClient;
1429
1430    #[gpui::test(iterations = 10)]
1431    async fn test_reconnection(cx: &mut TestAppContext) {
1432        cx.foreground().forbid_parking();
1433
1434        let user_id = 5;
1435        let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1436        let server = FakeServer::for_client(user_id, &client, cx).await;
1437        let mut status = client.status();
1438        assert!(matches!(
1439            status.next().await,
1440            Some(Status::Connected { .. })
1441        ));
1442        assert_eq!(server.auth_count(), 1);
1443
1444        server.forbid_connections();
1445        server.disconnect();
1446        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1447
1448        server.allow_connections();
1449        cx.foreground().advance_clock(Duration::from_secs(10));
1450        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1451        assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1452
1453        server.forbid_connections();
1454        server.disconnect();
1455        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1456
1457        // Clear cached credentials after authentication fails
1458        server.roll_access_token();
1459        server.allow_connections();
1460        cx.foreground().advance_clock(Duration::from_secs(10));
1461        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1462        assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1463    }
1464
1465    #[gpui::test(iterations = 10)]
1466    async fn test_connection_timeout(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
1467        deterministic.forbid_parking();
1468
1469        let user_id = 5;
1470        let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1471        let mut status = client.status();
1472
1473        // Time out when client tries to connect.
1474        client.override_authenticate(move |cx| {
1475            cx.foreground().spawn(async move {
1476                Ok(Credentials {
1477                    user_id,
1478                    access_token: "token".into(),
1479                })
1480            })
1481        });
1482        client.override_establish_connection(|_, cx| {
1483            cx.foreground().spawn(async move {
1484                future::pending::<()>().await;
1485                unreachable!()
1486            })
1487        });
1488        let auth_and_connect = cx.spawn({
1489            let client = client.clone();
1490            |cx| async move { client.authenticate_and_connect(false, &cx).await }
1491        });
1492        deterministic.run_until_parked();
1493        assert!(matches!(status.next().await, Some(Status::Connecting)));
1494
1495        deterministic.advance_clock(CONNECTION_TIMEOUT);
1496        assert!(matches!(
1497            status.next().await,
1498            Some(Status::ConnectionError { .. })
1499        ));
1500        auth_and_connect.await.unwrap_err();
1501
1502        // Allow the connection to be established.
1503        let server = FakeServer::for_client(user_id, &client, cx).await;
1504        assert!(matches!(
1505            status.next().await,
1506            Some(Status::Connected { .. })
1507        ));
1508
1509        // Disconnect client.
1510        server.forbid_connections();
1511        server.disconnect();
1512        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1513
1514        // Time out when re-establishing the connection.
1515        server.allow_connections();
1516        client.override_establish_connection(|_, cx| {
1517            cx.foreground().spawn(async move {
1518                future::pending::<()>().await;
1519                unreachable!()
1520            })
1521        });
1522        deterministic.advance_clock(2 * INITIAL_RECONNECTION_DELAY);
1523        assert!(matches!(
1524            status.next().await,
1525            Some(Status::Reconnecting { .. })
1526        ));
1527
1528        deterministic.advance_clock(CONNECTION_TIMEOUT);
1529        assert!(matches!(
1530            status.next().await,
1531            Some(Status::ReconnectionError { .. })
1532        ));
1533    }
1534
1535    #[gpui::test(iterations = 10)]
1536    async fn test_authenticating_more_than_once(
1537        cx: &mut TestAppContext,
1538        deterministic: Arc<Deterministic>,
1539    ) {
1540        cx.foreground().forbid_parking();
1541
1542        let auth_count = Arc::new(Mutex::new(0));
1543        let dropped_auth_count = Arc::new(Mutex::new(0));
1544        let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1545        client.override_authenticate({
1546            let auth_count = auth_count.clone();
1547            let dropped_auth_count = dropped_auth_count.clone();
1548            move |cx| {
1549                let auth_count = auth_count.clone();
1550                let dropped_auth_count = dropped_auth_count.clone();
1551                cx.foreground().spawn(async move {
1552                    *auth_count.lock() += 1;
1553                    let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
1554                    future::pending::<()>().await;
1555                    unreachable!()
1556                })
1557            }
1558        });
1559
1560        let _authenticate = cx.spawn(|cx| {
1561            let client = client.clone();
1562            async move { client.authenticate_and_connect(false, &cx).await }
1563        });
1564        deterministic.run_until_parked();
1565        assert_eq!(*auth_count.lock(), 1);
1566        assert_eq!(*dropped_auth_count.lock(), 0);
1567
1568        let _authenticate = cx.spawn(|cx| {
1569            let client = client.clone();
1570            async move { client.authenticate_and_connect(false, &cx).await }
1571        });
1572        deterministic.run_until_parked();
1573        assert_eq!(*auth_count.lock(), 2);
1574        assert_eq!(*dropped_auth_count.lock(), 1);
1575    }
1576
1577    #[test]
1578    fn test_encode_and_decode_worktree_url() {
1579        let url = encode_worktree_url(5, "deadbeef");
1580        assert_eq!(decode_worktree_url(&url), Some((5, "deadbeef".to_string())));
1581        assert_eq!(
1582            decode_worktree_url(&format!("\n {}\t", url)),
1583            Some((5, "deadbeef".to_string()))
1584        );
1585        assert_eq!(decode_worktree_url("not://the-right-format"), None);
1586    }
1587
1588    #[gpui::test]
1589    async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1590        cx.foreground().forbid_parking();
1591
1592        let user_id = 5;
1593        let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1594        let server = FakeServer::for_client(user_id, &client, cx).await;
1595
1596        let (done_tx1, mut done_rx1) = smol::channel::unbounded();
1597        let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1598        client.add_model_message_handler(
1599            move |model: ModelHandle<Model>, _: TypedEnvelope<proto::JoinProject>, _, cx| {
1600                match model.read_with(&cx, |model, _| model.id) {
1601                    1 => done_tx1.try_send(()).unwrap(),
1602                    2 => done_tx2.try_send(()).unwrap(),
1603                    _ => unreachable!(),
1604                }
1605                async { Ok(()) }
1606            },
1607        );
1608        let model1 = cx.add_model(|_| Model {
1609            id: 1,
1610            subscription: None,
1611        });
1612        let model2 = cx.add_model(|_| Model {
1613            id: 2,
1614            subscription: None,
1615        });
1616        let model3 = cx.add_model(|_| Model {
1617            id: 3,
1618            subscription: None,
1619        });
1620
1621        let _subscription1 = client
1622            .subscribe_to_entity(1)
1623            .unwrap()
1624            .set_model(&model1, &mut cx.to_async());
1625        let _subscription2 = client
1626            .subscribe_to_entity(2)
1627            .unwrap()
1628            .set_model(&model2, &mut cx.to_async());
1629        // Ensure dropping a subscription for the same entity type still allows receiving of
1630        // messages for other entity IDs of the same type.
1631        let subscription3 = client
1632            .subscribe_to_entity(3)
1633            .unwrap()
1634            .set_model(&model3, &mut cx.to_async());
1635        drop(subscription3);
1636
1637        server.send(proto::JoinProject { project_id: 1 });
1638        server.send(proto::JoinProject { project_id: 2 });
1639        done_rx1.next().await.unwrap();
1640        done_rx2.next().await.unwrap();
1641    }
1642
1643    #[gpui::test]
1644    async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
1645        cx.foreground().forbid_parking();
1646
1647        let user_id = 5;
1648        let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1649        let server = FakeServer::for_client(user_id, &client, cx).await;
1650
1651        let model = cx.add_model(|_| Model::default());
1652        let (done_tx1, _done_rx1) = smol::channel::unbounded();
1653        let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1654        let subscription1 = client.add_message_handler(
1655            model.clone(),
1656            move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1657                done_tx1.try_send(()).unwrap();
1658                async { Ok(()) }
1659            },
1660        );
1661        drop(subscription1);
1662        let _subscription2 = client.add_message_handler(
1663            model.clone(),
1664            move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1665                done_tx2.try_send(()).unwrap();
1666                async { Ok(()) }
1667            },
1668        );
1669        server.send(proto::Ping {});
1670        done_rx2.next().await.unwrap();
1671    }
1672
1673    #[gpui::test]
1674    async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
1675        cx.foreground().forbid_parking();
1676
1677        let user_id = 5;
1678        let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
1679        let server = FakeServer::for_client(user_id, &client, cx).await;
1680
1681        let model = cx.add_model(|_| Model::default());
1682        let (done_tx, mut done_rx) = smol::channel::unbounded();
1683        let subscription = client.add_message_handler(
1684            model.clone(),
1685            move |model, _: TypedEnvelope<proto::Ping>, _, mut cx| {
1686                model.update(&mut cx, |model, _| model.subscription.take());
1687                done_tx.try_send(()).unwrap();
1688                async { Ok(()) }
1689            },
1690        );
1691        model.update(cx, |model, _| {
1692            model.subscription = Some(subscription);
1693        });
1694        server.send(proto::Ping {});
1695        done_rx.next().await.unwrap();
1696    }
1697
1698    #[derive(Default)]
1699    struct Model {
1700        id: usize,
1701        subscription: Option<Subscription>,
1702    }
1703
1704    impl Entity for Model {
1705        type Event = ();
1706    }
1707}