client.rs

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