client.rs

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