client.rs

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