client.rs

   1#[cfg(any(test, feature = "test-support"))]
   2pub mod test;
   3
   4pub mod channel;
   5pub mod http;
   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, FutureExt, StreamExt};
  15use gpui::{
  16    action, AnyModelHandle, AnyViewHandle, AnyWeakModelHandle, AnyWeakViewHandle, AsyncAppContext,
  17    Entity, ModelContext, ModelHandle, MutableAppContext, Task, View, ViewContext, ViewHandle,
  18};
  19use http::HttpClient;
  20use lazy_static::lazy_static;
  21use parking_lot::RwLock;
  22use postage::watch;
  23use rand::prelude::*;
  24use rpc::proto::{AnyTypedEnvelope, EntityMessage, EnvelopedMessage, RequestMessage};
  25use std::{
  26    any::TypeId,
  27    collections::HashMap,
  28    convert::TryFrom,
  29    fmt::Write as _,
  30    future::Future,
  31    sync::{
  32        atomic::{AtomicUsize, Ordering},
  33        Arc, Weak,
  34    },
  35    time::{Duration, Instant},
  36};
  37use surf::{http::Method, Url};
  38use thiserror::Error;
  39use util::{ResultExt, TryFutureExt};
  40
  41pub use channel::*;
  42pub use rpc::*;
  43pub use user::*;
  44
  45lazy_static! {
  46    static ref ZED_SERVER_URL: String =
  47        std::env::var("ZED_SERVER_URL").unwrap_or("https://zed.dev".to_string());
  48    static ref IMPERSONATE_LOGIN: Option<String> = std::env::var("ZED_IMPERSONATE")
  49        .ok()
  50        .and_then(|s| if s.is_empty() { None } else { Some(s) });
  51}
  52
  53action!(Authenticate);
  54
  55pub fn init(rpc: Arc<Client>, cx: &mut MutableAppContext) {
  56    cx.add_global_action(move |_: &Authenticate, cx| {
  57        let rpc = rpc.clone();
  58        cx.spawn(|cx| async move { rpc.authenticate_and_connect(&cx).log_err().await })
  59            .detach();
  60    });
  61}
  62
  63pub struct Client {
  64    id: usize,
  65    peer: Arc<Peer>,
  66    http: Arc<dyn HttpClient>,
  67    state: RwLock<ClientState>,
  68    authenticate:
  69        Option<Box<dyn 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>>>,
  70    establish_connection: Option<
  71        Box<
  72            dyn 'static
  73                + Send
  74                + Sync
  75                + Fn(
  76                    &Credentials,
  77                    &AsyncAppContext,
  78                ) -> Task<Result<Connection, EstablishConnectionError>>,
  79        >,
  80    >,
  81}
  82
  83#[derive(Error, Debug)]
  84pub enum EstablishConnectionError {
  85    #[error("upgrade required")]
  86    UpgradeRequired,
  87    #[error("unauthorized")]
  88    Unauthorized,
  89    #[error("{0}")]
  90    Other(#[from] anyhow::Error),
  91    #[error("{0}")]
  92    Io(#[from] std::io::Error),
  93    #[error("{0}")]
  94    Http(#[from] async_tungstenite::tungstenite::http::Error),
  95}
  96
  97impl From<WebsocketError> for EstablishConnectionError {
  98    fn from(error: WebsocketError) -> Self {
  99        if let WebsocketError::Http(response) = &error {
 100            match response.status() {
 101                StatusCode::UNAUTHORIZED => return EstablishConnectionError::Unauthorized,
 102                StatusCode::UPGRADE_REQUIRED => return EstablishConnectionError::UpgradeRequired,
 103                _ => {}
 104            }
 105        }
 106        EstablishConnectionError::Other(error.into())
 107    }
 108}
 109
 110impl EstablishConnectionError {
 111    pub fn other(error: impl Into<anyhow::Error> + Send + Sync) -> Self {
 112        Self::Other(error.into())
 113    }
 114}
 115
 116#[derive(Copy, Clone, Debug)]
 117pub enum Status {
 118    SignedOut,
 119    UpgradeRequired,
 120    Authenticating,
 121    Connecting,
 122    ConnectionError,
 123    Connected { connection_id: ConnectionId },
 124    ConnectionLost,
 125    Reauthenticating,
 126    Reconnecting,
 127    ReconnectionError { next_reconnection: Instant },
 128}
 129
 130impl Status {
 131    pub fn is_connected(&self) -> bool {
 132        matches!(self, Self::Connected { .. })
 133    }
 134}
 135
 136struct ClientState {
 137    credentials: Option<Credentials>,
 138    status: (watch::Sender<Status>, watch::Receiver<Status>),
 139    entity_id_extractors: HashMap<TypeId, Box<dyn Send + Sync + Fn(&dyn AnyTypedEnvelope) -> u64>>,
 140    _reconnect_task: Option<Task<()>>,
 141    reconnect_interval: Duration,
 142    entities_by_type_and_remote_id: HashMap<(TypeId, u64), AnyWeakEntityHandle>,
 143    models_by_message_type: HashMap<TypeId, AnyWeakModelHandle>,
 144    entity_types_by_message_type: HashMap<TypeId, TypeId>,
 145    message_handlers: HashMap<
 146        TypeId,
 147        Arc<
 148            dyn Send
 149                + Sync
 150                + Fn(
 151                    AnyEntityHandle,
 152                    Box<dyn AnyTypedEnvelope>,
 153                    AsyncAppContext,
 154                ) -> LocalBoxFuture<'static, Result<()>>,
 155        >,
 156    >,
 157}
 158
 159enum AnyWeakEntityHandle {
 160    Model(AnyWeakModelHandle),
 161    View(AnyWeakViewHandle),
 162}
 163
 164enum AnyEntityHandle {
 165    Model(AnyModelHandle),
 166    View(AnyViewHandle),
 167}
 168
 169#[derive(Clone, Debug)]
 170pub struct Credentials {
 171    pub user_id: u64,
 172    pub access_token: String,
 173}
 174
 175impl Default for ClientState {
 176    fn default() -> Self {
 177        Self {
 178            credentials: None,
 179            status: watch::channel_with(Status::SignedOut),
 180            entity_id_extractors: Default::default(),
 181            _reconnect_task: None,
 182            reconnect_interval: Duration::from_secs(5),
 183            models_by_message_type: Default::default(),
 184            entities_by_type_and_remote_id: Default::default(),
 185            entity_types_by_message_type: Default::default(),
 186            message_handlers: Default::default(),
 187        }
 188    }
 189}
 190
 191pub enum Subscription {
 192    Entity {
 193        client: Weak<Client>,
 194        id: (TypeId, u64),
 195    },
 196    Message {
 197        client: Weak<Client>,
 198        id: TypeId,
 199    },
 200}
 201
 202impl Drop for Subscription {
 203    fn drop(&mut self) {
 204        match self {
 205            Subscription::Entity { client, id } => {
 206                if let Some(client) = client.upgrade() {
 207                    let mut state = client.state.write();
 208                    let _ = state.entities_by_type_and_remote_id.remove(id);
 209                }
 210            }
 211            Subscription::Message { client, id } => {
 212                if let Some(client) = client.upgrade() {
 213                    let mut state = client.state.write();
 214                    let _ = state.entity_types_by_message_type.remove(id);
 215                    let _ = state.message_handlers.remove(id);
 216                }
 217            }
 218        }
 219    }
 220}
 221
 222impl Client {
 223    pub fn new(http: Arc<dyn HttpClient>) -> Arc<Self> {
 224        lazy_static! {
 225            static ref NEXT_CLIENT_ID: AtomicUsize = AtomicUsize::default();
 226        }
 227
 228        Arc::new(Self {
 229            id: NEXT_CLIENT_ID.fetch_add(1, Ordering::SeqCst),
 230            peer: Peer::new(),
 231            http,
 232            state: Default::default(),
 233            authenticate: None,
 234            establish_connection: None,
 235        })
 236    }
 237
 238    pub fn id(&self) -> usize {
 239        self.id
 240    }
 241
 242    pub fn http_client(&self) -> Arc<dyn HttpClient> {
 243        self.http.clone()
 244    }
 245
 246    #[cfg(any(test, feature = "test-support"))]
 247    pub fn tear_down(&self) {
 248        let mut state = self.state.write();
 249        state._reconnect_task.take();
 250        state.message_handlers.clear();
 251        state.models_by_message_type.clear();
 252        state.entities_by_type_and_remote_id.clear();
 253        state.entity_id_extractors.clear();
 254        self.peer.reset();
 255    }
 256
 257    #[cfg(any(test, feature = "test-support"))]
 258    pub fn override_authenticate<F>(&mut self, authenticate: F) -> &mut Self
 259    where
 260        F: 'static + Send + Sync + Fn(&AsyncAppContext) -> Task<Result<Credentials>>,
 261    {
 262        self.authenticate = Some(Box::new(authenticate));
 263        self
 264    }
 265
 266    #[cfg(any(test, feature = "test-support"))]
 267    pub fn override_establish_connection<F>(&mut self, connect: F) -> &mut Self
 268    where
 269        F: 'static
 270            + Send
 271            + Sync
 272            + Fn(&Credentials, &AsyncAppContext) -> Task<Result<Connection, EstablishConnectionError>>,
 273    {
 274        self.establish_connection = Some(Box::new(connect));
 275        self
 276    }
 277
 278    pub fn user_id(&self) -> Option<u64> {
 279        self.state
 280            .read()
 281            .credentials
 282            .as_ref()
 283            .map(|credentials| credentials.user_id)
 284    }
 285
 286    pub fn status(&self) -> watch::Receiver<Status> {
 287        self.state.read().status.1.clone()
 288    }
 289
 290    fn set_status(self: &Arc<Self>, status: Status, cx: &AsyncAppContext) {
 291        let mut state = self.state.write();
 292        *state.status.0.borrow_mut() = status;
 293
 294        match status {
 295            Status::Connected { .. } => {
 296                state._reconnect_task = None;
 297            }
 298            Status::ConnectionLost => {
 299                let this = self.clone();
 300                let reconnect_interval = state.reconnect_interval;
 301                state._reconnect_task = Some(cx.spawn(|cx| async move {
 302                    let mut rng = StdRng::from_entropy();
 303                    let mut delay = Duration::from_millis(100);
 304                    while let Err(error) = this.authenticate_and_connect(&cx).await {
 305                        log::error!("failed to connect {}", error);
 306                        this.set_status(
 307                            Status::ReconnectionError {
 308                                next_reconnection: Instant::now() + delay,
 309                            },
 310                            &cx,
 311                        );
 312                        cx.background().timer(delay).await;
 313                        delay = delay
 314                            .mul_f32(rng.gen_range(1.0..=2.0))
 315                            .min(reconnect_interval);
 316                    }
 317                }));
 318            }
 319            Status::SignedOut | Status::UpgradeRequired => {
 320                state._reconnect_task.take();
 321            }
 322            _ => {}
 323        }
 324    }
 325
 326    pub fn add_view_for_remote_entity<T: View>(
 327        self: &Arc<Self>,
 328        remote_id: u64,
 329        cx: &mut ViewContext<T>,
 330    ) -> Subscription {
 331        let handle = AnyViewHandle::from(cx.handle());
 332        let mut state = self.state.write();
 333        let id = (TypeId::of::<T>(), remote_id);
 334        state
 335            .entities_by_type_and_remote_id
 336            .insert(id, AnyWeakEntityHandle::View(handle.downgrade()));
 337        Subscription::Entity {
 338            client: Arc::downgrade(self),
 339            id,
 340        }
 341    }
 342
 343    pub fn add_model_for_remote_entity<T: Entity>(
 344        self: &Arc<Self>,
 345        remote_id: u64,
 346        cx: &mut ModelContext<T>,
 347    ) -> Subscription {
 348        let handle = AnyModelHandle::from(cx.handle());
 349        let mut state = self.state.write();
 350        let id = (TypeId::of::<T>(), remote_id);
 351        state
 352            .entities_by_type_and_remote_id
 353            .insert(id, AnyWeakEntityHandle::Model(handle.downgrade()));
 354        Subscription::Entity {
 355            client: Arc::downgrade(self),
 356            id,
 357        }
 358    }
 359
 360    pub fn add_message_handler<M, E, H, F>(
 361        self: &Arc<Self>,
 362        model: ModelHandle<E>,
 363        handler: H,
 364    ) -> Subscription
 365    where
 366        M: EnvelopedMessage,
 367        E: Entity,
 368        H: 'static
 369            + Send
 370            + Sync
 371            + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 372        F: 'static + Future<Output = Result<()>>,
 373    {
 374        let message_type_id = TypeId::of::<M>();
 375
 376        let client = Arc::downgrade(self);
 377        let mut state = self.state.write();
 378        state
 379            .models_by_message_type
 380            .insert(message_type_id, model.downgrade().into());
 381
 382        let prev_handler = state.message_handlers.insert(
 383            message_type_id,
 384            Arc::new(move |handle, envelope, cx| {
 385                let handle = if let AnyEntityHandle::Model(handle) = handle {
 386                    handle
 387                } else {
 388                    unreachable!();
 389                };
 390                let model = handle.downcast::<E>().unwrap();
 391                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 392                if let Some(client) = client.upgrade() {
 393                    handler(model, *envelope, client.clone(), cx).boxed_local()
 394                } else {
 395                    async move { Ok(()) }.boxed_local()
 396                }
 397            }),
 398        );
 399        if prev_handler.is_some() {
 400            panic!("registered handler for the same message twice");
 401        }
 402
 403        Subscription::Message {
 404            client: Arc::downgrade(self),
 405            id: message_type_id,
 406        }
 407    }
 408
 409    pub fn add_view_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
 410    where
 411        M: EntityMessage,
 412        E: View,
 413        H: 'static
 414            + Send
 415            + Sync
 416            + Fn(ViewHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 417        F: 'static + Future<Output = Result<()>>,
 418    {
 419        let entity_type_id = TypeId::of::<E>();
 420        let message_type_id = TypeId::of::<M>();
 421
 422        let client = Arc::downgrade(self);
 423        let mut state = self.state.write();
 424        state
 425            .entity_types_by_message_type
 426            .insert(message_type_id, entity_type_id);
 427        state
 428            .entity_id_extractors
 429            .entry(message_type_id)
 430            .or_insert_with(|| {
 431                Box::new(|envelope| {
 432                    let envelope = envelope
 433                        .as_any()
 434                        .downcast_ref::<TypedEnvelope<M>>()
 435                        .unwrap();
 436                    envelope.payload.remote_entity_id()
 437                })
 438            });
 439
 440        let prev_handler = state.message_handlers.insert(
 441            message_type_id,
 442            Arc::new(move |handle, envelope, cx| {
 443                let handle = if let AnyEntityHandle::View(handle) = handle {
 444                    handle
 445                } else {
 446                    unreachable!();
 447                };
 448                let model = handle.downcast::<E>().unwrap();
 449                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 450                if let Some(client) = client.upgrade() {
 451                    handler(model, *envelope, client.clone(), cx).boxed_local()
 452                } else {
 453                    async move { Ok(()) }.boxed_local()
 454                }
 455            }),
 456        );
 457        if prev_handler.is_some() {
 458            panic!("registered handler for the same message twice");
 459        }
 460    }
 461
 462    pub fn add_model_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
 463    where
 464        M: EntityMessage,
 465        E: Entity,
 466        H: 'static
 467            + Send
 468            + Sync
 469            + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 470        F: 'static + Future<Output = Result<()>>,
 471    {
 472        let model_type_id = TypeId::of::<E>();
 473        let message_type_id = TypeId::of::<M>();
 474
 475        let client = Arc::downgrade(self);
 476        let mut state = self.state.write();
 477        state
 478            .entity_types_by_message_type
 479            .insert(message_type_id, model_type_id);
 480        state
 481            .entity_id_extractors
 482            .entry(message_type_id)
 483            .or_insert_with(|| {
 484                Box::new(|envelope| {
 485                    let envelope = envelope
 486                        .as_any()
 487                        .downcast_ref::<TypedEnvelope<M>>()
 488                        .unwrap();
 489                    envelope.payload.remote_entity_id()
 490                })
 491            });
 492
 493        let prev_handler = state.message_handlers.insert(
 494            message_type_id,
 495            Arc::new(move |handle, envelope, cx| {
 496                if let Some(client) = client.upgrade() {
 497                    let handle = if let AnyEntityHandle::Model(handle) = handle {
 498                        handle
 499                    } else {
 500                        unreachable!();
 501                    };
 502                    let model = handle.downcast::<E>().unwrap();
 503                    let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 504                    handler(model, *envelope, client.clone(), cx).boxed_local()
 505                } else {
 506                    async move { Ok(()) }.boxed_local()
 507                }
 508            }),
 509        );
 510        if prev_handler.is_some() {
 511            panic!("registered handler for the same message twice");
 512        }
 513    }
 514
 515    pub fn add_model_request_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
 516    where
 517        M: EntityMessage + RequestMessage,
 518        E: Entity,
 519        H: 'static
 520            + Send
 521            + Sync
 522            + Fn(ModelHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 523        F: 'static + Future<Output = Result<M::Response>>,
 524    {
 525        self.add_model_message_handler(move |model, envelope, client, cx| {
 526            let receipt = envelope.receipt();
 527            let response = handler(model, envelope, client.clone(), cx);
 528            async move {
 529                match response.await {
 530                    Ok(response) => {
 531                        client.respond(receipt, response)?;
 532                        Ok(())
 533                    }
 534                    Err(error) => {
 535                        client.respond_with_error(
 536                            receipt,
 537                            proto::Error {
 538                                message: error.to_string(),
 539                            },
 540                        )?;
 541                        Err(error)
 542                    }
 543                }
 544            }
 545        })
 546    }
 547
 548    pub fn add_view_request_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
 549    where
 550        M: EntityMessage + RequestMessage,
 551        E: View,
 552        H: 'static
 553            + Send
 554            + Sync
 555            + Fn(ViewHandle<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
 556        F: 'static + Future<Output = Result<M::Response>>,
 557    {
 558        self.add_view_message_handler(move |view, envelope, client, cx| {
 559            let receipt = envelope.receipt();
 560            let response = handler(view, envelope, client.clone(), cx);
 561            async move {
 562                match response.await {
 563                    Ok(response) => {
 564                        client.respond(receipt, response)?;
 565                        Ok(())
 566                    }
 567                    Err(error) => {
 568                        client.respond_with_error(
 569                            receipt,
 570                            proto::Error {
 571                                message: error.to_string(),
 572                            },
 573                        )?;
 574                        Err(error)
 575                    }
 576                }
 577            }
 578        })
 579    }
 580
 581    pub fn has_keychain_credentials(&self, cx: &AsyncAppContext) -> bool {
 582        read_credentials_from_keychain(cx).is_some()
 583    }
 584
 585    #[async_recursion(?Send)]
 586    pub async fn authenticate_and_connect(
 587        self: &Arc<Self>,
 588        cx: &AsyncAppContext,
 589    ) -> anyhow::Result<()> {
 590        let was_disconnected = match *self.status().borrow() {
 591            Status::SignedOut => true,
 592            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 593                false
 594            }
 595            Status::Connected { .. }
 596            | Status::Connecting { .. }
 597            | Status::Reconnecting { .. }
 598            | Status::Authenticating
 599            | Status::Reauthenticating => return Ok(()),
 600            Status::UpgradeRequired => return Err(EstablishConnectionError::UpgradeRequired)?,
 601        };
 602
 603        if was_disconnected {
 604            self.set_status(Status::Authenticating, cx);
 605        } else {
 606            self.set_status(Status::Reauthenticating, cx)
 607        }
 608
 609        let mut used_keychain = false;
 610        let credentials = self.state.read().credentials.clone();
 611        let credentials = if let Some(credentials) = credentials {
 612            credentials
 613        } else if let Some(credentials) = read_credentials_from_keychain(cx) {
 614            used_keychain = true;
 615            credentials
 616        } else {
 617            let credentials = match self.authenticate(&cx).await {
 618                Ok(credentials) => credentials,
 619                Err(err) => {
 620                    self.set_status(Status::ConnectionError, cx);
 621                    return Err(err);
 622                }
 623            };
 624            credentials
 625        };
 626
 627        if was_disconnected {
 628            self.set_status(Status::Connecting, cx);
 629        } else {
 630            self.set_status(Status::Reconnecting, cx);
 631        }
 632
 633        match self.establish_connection(&credentials, cx).await {
 634            Ok(conn) => {
 635                self.state.write().credentials = Some(credentials.clone());
 636                if !used_keychain && IMPERSONATE_LOGIN.is_none() {
 637                    write_credentials_to_keychain(&credentials, cx).log_err();
 638                }
 639                self.set_connection(conn, cx).await;
 640                Ok(())
 641            }
 642            Err(EstablishConnectionError::Unauthorized) => {
 643                self.state.write().credentials.take();
 644                if used_keychain {
 645                    cx.platform().delete_credentials(&ZED_SERVER_URL).log_err();
 646                    self.set_status(Status::SignedOut, cx);
 647                    self.authenticate_and_connect(cx).await
 648                } else {
 649                    self.set_status(Status::ConnectionError, cx);
 650                    Err(EstablishConnectionError::Unauthorized)?
 651                }
 652            }
 653            Err(EstablishConnectionError::UpgradeRequired) => {
 654                self.set_status(Status::UpgradeRequired, cx);
 655                Err(EstablishConnectionError::UpgradeRequired)?
 656            }
 657            Err(error) => {
 658                self.set_status(Status::ConnectionError, cx);
 659                Err(error)?
 660            }
 661        }
 662    }
 663
 664    async fn set_connection(self: &Arc<Self>, conn: Connection, cx: &AsyncAppContext) {
 665        let executor = cx.background();
 666        let (connection_id, handle_io, mut incoming) = self
 667            .peer
 668            .add_connection(conn, move |duration| executor.timer(duration))
 669            .await;
 670        cx.foreground()
 671            .spawn({
 672                let cx = cx.clone();
 673                let this = self.clone();
 674                async move {
 675                    let mut message_id = 0_usize;
 676                    while let Some(message) = incoming.next().await {
 677                        let mut state = this.state.write();
 678                        message_id += 1;
 679                        let type_name = message.payload_type_name();
 680                        let payload_type_id = message.payload_type_id();
 681                        let sender_id = message.original_sender_id().map(|id| id.0);
 682
 683                        let model = state
 684                            .models_by_message_type
 685                            .get(&payload_type_id)
 686                            .and_then(|model| model.upgrade(&cx))
 687                            .map(AnyEntityHandle::Model)
 688                            .or_else(|| {
 689                                let entity_type_id =
 690                                    *state.entity_types_by_message_type.get(&payload_type_id)?;
 691                                let entity_id = state
 692                                    .entity_id_extractors
 693                                    .get(&message.payload_type_id())
 694                                    .map(|extract_entity_id| {
 695                                        (extract_entity_id)(message.as_ref())
 696                                    })?;
 697
 698                                let entity = state
 699                                    .entities_by_type_and_remote_id
 700                                    .get(&(entity_type_id, entity_id))?;
 701                                if let Some(entity) = entity.upgrade(&cx) {
 702                                    Some(entity)
 703                                } else {
 704                                    state
 705                                        .entities_by_type_and_remote_id
 706                                        .remove(&(entity_type_id, entity_id));
 707                                    None
 708                                }
 709                            });
 710
 711                        let model = if let Some(model) = model {
 712                            model
 713                        } else {
 714                            log::info!("unhandled message {}", type_name);
 715                            continue;
 716                        };
 717
 718                        if let Some(handler) = state.message_handlers.get(&payload_type_id).cloned()
 719                        {
 720                            drop(state); // Avoid deadlocks if the handler interacts with rpc::Client
 721                            let future = handler(model, message, cx.clone());
 722
 723                            let client_id = this.id;
 724                            log::debug!(
 725                                "rpc message received. client_id:{}, message_id:{}, sender_id:{:?}, type:{}",
 726                                client_id,
 727                                message_id,
 728                                sender_id,
 729                                type_name
 730                            );
 731                            cx.foreground()
 732                                .spawn(async move {
 733                                    match future.await {
 734                                        Ok(()) => {
 735                                            log::debug!(
 736                                                "rpc message handled. client_id:{}, message_id:{}, sender_id:{:?}, type:{}",
 737                                                client_id,
 738                                                message_id,
 739                                                sender_id,
 740                                                type_name
 741                                            );
 742                                        }
 743                                        Err(error) => {
 744                                            log::error!(
 745                                                "error handling message. client_id:{}, message_id:{}, sender_id:{:?}, type:{}, error:{:?}",
 746                                                client_id,
 747                                                message_id,
 748                                                sender_id,
 749                                                type_name,
 750                                                error
 751                                            );
 752                                        }
 753                                    }
 754                                })
 755                                .detach();
 756                        } else {
 757                            log::info!("unhandled message {}", type_name);
 758                        }
 759
 760                        // Don't starve the main thread when receiving lots of messages at once.
 761                        smol::future::yield_now().await;
 762                    }
 763                }
 764            })
 765            .detach();
 766
 767        self.set_status(Status::Connected { connection_id }, cx);
 768
 769        let handle_io = cx.background().spawn(handle_io);
 770        let this = self.clone();
 771        let cx = cx.clone();
 772        cx.foreground()
 773            .spawn(async move {
 774                match handle_io.await {
 775                    Ok(()) => this.set_status(Status::SignedOut, &cx),
 776                    Err(err) => {
 777                        log::error!("connection error: {:?}", err);
 778                        this.set_status(Status::ConnectionLost, &cx);
 779                    }
 780                }
 781            })
 782            .detach();
 783    }
 784
 785    fn authenticate(self: &Arc<Self>, cx: &AsyncAppContext) -> Task<Result<Credentials>> {
 786        if let Some(callback) = self.authenticate.as_ref() {
 787            callback(cx)
 788        } else {
 789            self.authenticate_with_browser(cx)
 790        }
 791    }
 792
 793    fn establish_connection(
 794        self: &Arc<Self>,
 795        credentials: &Credentials,
 796        cx: &AsyncAppContext,
 797    ) -> Task<Result<Connection, EstablishConnectionError>> {
 798        if let Some(callback) = self.establish_connection.as_ref() {
 799            callback(credentials, cx)
 800        } else {
 801            self.establish_websocket_connection(credentials, cx)
 802        }
 803    }
 804
 805    fn establish_websocket_connection(
 806        self: &Arc<Self>,
 807        credentials: &Credentials,
 808        cx: &AsyncAppContext,
 809    ) -> Task<Result<Connection, EstablishConnectionError>> {
 810        let request = Request::builder()
 811            .header(
 812                "Authorization",
 813                format!("{} {}", credentials.user_id, credentials.access_token),
 814            )
 815            .header("X-Zed-Protocol-Version", rpc::PROTOCOL_VERSION);
 816
 817        let http = self.http.clone();
 818        cx.background().spawn(async move {
 819            let mut rpc_url = format!("{}/rpc", *ZED_SERVER_URL);
 820            let rpc_request = surf::Request::new(
 821                Method::Get,
 822                surf::Url::parse(&rpc_url).context("invalid ZED_SERVER_URL")?,
 823            );
 824            let rpc_response = http.send(rpc_request).await?;
 825
 826            if rpc_response.status().is_redirection() {
 827                rpc_url = rpc_response
 828                    .header("Location")
 829                    .ok_or_else(|| anyhow!("missing location header in /rpc response"))?
 830                    .as_str()
 831                    .to_string();
 832            }
 833            // Until we switch the zed.dev domain to point to the new Next.js app, there
 834            // will be no redirect required, and the app will connect directly to
 835            // wss://zed.dev/rpc.
 836            else if rpc_response.status() != surf::StatusCode::UpgradeRequired {
 837                Err(anyhow!(
 838                    "unexpected /rpc response status {}",
 839                    rpc_response.status()
 840                ))?
 841            }
 842
 843            let mut rpc_url = surf::Url::parse(&rpc_url).context("invalid rpc url")?;
 844            let rpc_host = rpc_url
 845                .host_str()
 846                .zip(rpc_url.port_or_known_default())
 847                .ok_or_else(|| anyhow!("missing host in rpc url"))?;
 848            let stream = smol::net::TcpStream::connect(rpc_host).await?;
 849
 850            log::info!("connected to rpc endpoint {}", rpc_url);
 851
 852            match rpc_url.scheme() {
 853                "https" => {
 854                    rpc_url.set_scheme("wss").unwrap();
 855                    let request = request.uri(rpc_url.as_str()).body(())?;
 856                    let (stream, _) =
 857                        async_tungstenite::async_tls::client_async_tls(request, stream).await?;
 858                    Ok(Connection::new(stream))
 859                }
 860                "http" => {
 861                    rpc_url.set_scheme("ws").unwrap();
 862                    let request = request.uri(rpc_url.as_str()).body(())?;
 863                    let (stream, _) = async_tungstenite::client_async(request, stream).await?;
 864                    Ok(Connection::new(stream))
 865                }
 866                _ => Err(anyhow!("invalid rpc url: {}", rpc_url))?,
 867            }
 868        })
 869    }
 870
 871    pub fn authenticate_with_browser(
 872        self: &Arc<Self>,
 873        cx: &AsyncAppContext,
 874    ) -> Task<Result<Credentials>> {
 875        let platform = cx.platform();
 876        let executor = cx.background();
 877        executor.clone().spawn(async move {
 878            // Generate a pair of asymmetric encryption keys. The public key will be used by the
 879            // zed server to encrypt the user's access token, so that it can'be intercepted by
 880            // any other app running on the user's device.
 881            let (public_key, private_key) =
 882                rpc::auth::keypair().expect("failed to generate keypair for auth");
 883            let public_key_string =
 884                String::try_from(public_key).expect("failed to serialize public key for auth");
 885
 886            // Start an HTTP server to receive the redirect from Zed's sign-in page.
 887            let server = tiny_http::Server::http("127.0.0.1:0").expect("failed to find open port");
 888            let port = server.server_addr().port();
 889
 890            // Open the Zed sign-in page in the user's browser, with query parameters that indicate
 891            // that the user is signing in from a Zed app running on the same device.
 892            let mut url = format!(
 893                "{}/native_app_signin?native_app_port={}&native_app_public_key={}",
 894                *ZED_SERVER_URL, port, public_key_string
 895            );
 896
 897            if let Some(impersonate_login) = IMPERSONATE_LOGIN.as_ref() {
 898                log::info!("impersonating user @{}", impersonate_login);
 899                write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
 900            }
 901
 902            platform.open_url(&url);
 903
 904            // Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
 905            // access token from the query params.
 906            //
 907            // TODO - Avoid ever starting more than one HTTP server. Maybe switch to using a
 908            // custom URL scheme instead of this local HTTP server.
 909            let (user_id, access_token) = executor
 910                .spawn(async move {
 911                    if let Some(req) = server.recv_timeout(Duration::from_secs(10 * 60))? {
 912                        let path = req.url();
 913                        let mut user_id = None;
 914                        let mut access_token = None;
 915                        let url = Url::parse(&format!("http://example.com{}", path))
 916                            .context("failed to parse login notification url")?;
 917                        for (key, value) in url.query_pairs() {
 918                            if key == "access_token" {
 919                                access_token = Some(value.to_string());
 920                            } else if key == "user_id" {
 921                                user_id = Some(value.to_string());
 922                            }
 923                        }
 924
 925                        let post_auth_url =
 926                            format!("{}/native_app_signin_succeeded", *ZED_SERVER_URL);
 927                        req.respond(
 928                            tiny_http::Response::empty(302).with_header(
 929                                tiny_http::Header::from_bytes(
 930                                    &b"Location"[..],
 931                                    post_auth_url.as_bytes(),
 932                                )
 933                                .unwrap(),
 934                            ),
 935                        )
 936                        .context("failed to respond to login http request")?;
 937                        Ok((
 938                            user_id.ok_or_else(|| anyhow!("missing user_id parameter"))?,
 939                            access_token
 940                                .ok_or_else(|| anyhow!("missing access_token parameter"))?,
 941                        ))
 942                    } else {
 943                        Err(anyhow!("didn't receive login redirect"))
 944                    }
 945                })
 946                .await?;
 947
 948            let access_token = private_key
 949                .decrypt_string(&access_token)
 950                .context("failed to decrypt access token")?;
 951            platform.activate(true);
 952
 953            Ok(Credentials {
 954                user_id: user_id.parse()?,
 955                access_token,
 956            })
 957        })
 958    }
 959
 960    pub fn disconnect(self: &Arc<Self>, cx: &AsyncAppContext) -> Result<()> {
 961        let conn_id = self.connection_id()?;
 962        self.peer.disconnect(conn_id);
 963        self.set_status(Status::SignedOut, cx);
 964        Ok(())
 965    }
 966
 967    fn connection_id(&self) -> Result<ConnectionId> {
 968        if let Status::Connected { connection_id, .. } = *self.status().borrow() {
 969            Ok(connection_id)
 970        } else {
 971            Err(anyhow!("not connected"))
 972        }
 973    }
 974
 975    pub fn send<T: EnvelopedMessage>(&self, message: T) -> Result<()> {
 976        log::debug!("rpc send. client_id:{}, name:{}", self.id, T::NAME);
 977        self.peer.send(self.connection_id()?, message)
 978    }
 979
 980    pub fn request<T: RequestMessage>(
 981        &self,
 982        request: T,
 983    ) -> impl Future<Output = Result<T::Response>> {
 984        let client_id = self.id;
 985        log::debug!(
 986            "rpc request start. client_id:{}. name:{}",
 987            client_id,
 988            T::NAME
 989        );
 990        let response = self
 991            .connection_id()
 992            .map(|conn_id| self.peer.request(conn_id, request));
 993        async move {
 994            let response = response?.await;
 995            log::debug!(
 996                "rpc request finish. client_id:{}. name:{}",
 997                client_id,
 998                T::NAME
 999            );
1000            response
1001        }
1002    }
1003
1004    fn respond<T: RequestMessage>(&self, receipt: Receipt<T>, response: T::Response) -> Result<()> {
1005        log::debug!("rpc respond. client_id:{}. name:{}", self.id, T::NAME);
1006        self.peer.respond(receipt, response)
1007    }
1008
1009    fn respond_with_error<T: RequestMessage>(
1010        &self,
1011        receipt: Receipt<T>,
1012        error: proto::Error,
1013    ) -> Result<()> {
1014        log::debug!("rpc respond. client_id:{}. name:{}", self.id, T::NAME);
1015        self.peer.respond_with_error(receipt, error)
1016    }
1017}
1018
1019impl AnyWeakEntityHandle {
1020    fn upgrade(&self, cx: &AsyncAppContext) -> Option<AnyEntityHandle> {
1021        match self {
1022            AnyWeakEntityHandle::Model(handle) => handle.upgrade(cx).map(AnyEntityHandle::Model),
1023            AnyWeakEntityHandle::View(handle) => handle.upgrade(cx).map(AnyEntityHandle::View),
1024        }
1025    }
1026}
1027
1028fn read_credentials_from_keychain(cx: &AsyncAppContext) -> Option<Credentials> {
1029    if IMPERSONATE_LOGIN.is_some() {
1030        return None;
1031    }
1032
1033    let (user_id, access_token) = cx
1034        .platform()
1035        .read_credentials(&ZED_SERVER_URL)
1036        .log_err()
1037        .flatten()?;
1038    Some(Credentials {
1039        user_id: user_id.parse().ok()?,
1040        access_token: String::from_utf8(access_token).ok()?,
1041    })
1042}
1043
1044fn write_credentials_to_keychain(credentials: &Credentials, cx: &AsyncAppContext) -> Result<()> {
1045    cx.platform().write_credentials(
1046        &ZED_SERVER_URL,
1047        &credentials.user_id.to_string(),
1048        credentials.access_token.as_bytes(),
1049    )
1050}
1051
1052const WORKTREE_URL_PREFIX: &'static str = "zed://worktrees/";
1053
1054pub fn encode_worktree_url(id: u64, access_token: &str) -> String {
1055    format!("{}{}/{}", WORKTREE_URL_PREFIX, id, access_token)
1056}
1057
1058pub fn decode_worktree_url(url: &str) -> Option<(u64, String)> {
1059    let path = url.trim().strip_prefix(WORKTREE_URL_PREFIX)?;
1060    let mut parts = path.split('/');
1061    let id = parts.next()?.parse::<u64>().ok()?;
1062    let access_token = parts.next()?;
1063    if access_token.is_empty() {
1064        return None;
1065    }
1066    Some((id, access_token.to_string()))
1067}
1068
1069#[cfg(test)]
1070mod tests {
1071    use super::*;
1072    use crate::test::{FakeHttpClient, FakeServer};
1073    use gpui::TestAppContext;
1074
1075    #[gpui::test(iterations = 10)]
1076    async fn test_reconnection(cx: &mut TestAppContext) {
1077        cx.foreground().forbid_parking();
1078
1079        let user_id = 5;
1080        let mut client = Client::new(FakeHttpClient::with_404_response());
1081        let server = FakeServer::for_client(user_id, &mut client, &cx).await;
1082        let mut status = client.status();
1083        assert!(matches!(
1084            status.next().await,
1085            Some(Status::Connected { .. })
1086        ));
1087        assert_eq!(server.auth_count(), 1);
1088
1089        server.forbid_connections();
1090        server.disconnect();
1091        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1092
1093        server.allow_connections();
1094        cx.foreground().advance_clock(Duration::from_secs(10));
1095        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1096        assert_eq!(server.auth_count(), 1); // Client reused the cached credentials when reconnecting
1097
1098        server.forbid_connections();
1099        server.disconnect();
1100        while !matches!(status.next().await, Some(Status::ReconnectionError { .. })) {}
1101
1102        // Clear cached credentials after authentication fails
1103        server.roll_access_token();
1104        server.allow_connections();
1105        cx.foreground().advance_clock(Duration::from_secs(10));
1106        while !matches!(status.next().await, Some(Status::Connected { .. })) {}
1107        assert_eq!(server.auth_count(), 2); // Client re-authenticated due to an invalid token
1108    }
1109
1110    #[test]
1111    fn test_encode_and_decode_worktree_url() {
1112        let url = encode_worktree_url(5, "deadbeef");
1113        assert_eq!(decode_worktree_url(&url), Some((5, "deadbeef".to_string())));
1114        assert_eq!(
1115            decode_worktree_url(&format!("\n {}\t", url)),
1116            Some((5, "deadbeef".to_string()))
1117        );
1118        assert_eq!(decode_worktree_url("not://the-right-format"), None);
1119    }
1120
1121    #[gpui::test]
1122    async fn test_subscribing_to_entity(cx: &mut TestAppContext) {
1123        cx.foreground().forbid_parking();
1124
1125        let user_id = 5;
1126        let mut client = Client::new(FakeHttpClient::with_404_response());
1127        let server = FakeServer::for_client(user_id, &mut client, &cx).await;
1128
1129        let (done_tx1, mut done_rx1) = smol::channel::unbounded();
1130        let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1131        client.add_model_message_handler(
1132            move |model: ModelHandle<Model>, _: TypedEnvelope<proto::UnshareProject>, _, cx| {
1133                match model.read_with(&cx, |model, _| model.id) {
1134                    1 => done_tx1.try_send(()).unwrap(),
1135                    2 => done_tx2.try_send(()).unwrap(),
1136                    _ => unreachable!(),
1137                }
1138                async { Ok(()) }
1139            },
1140        );
1141        let model1 = cx.add_model(|_| Model {
1142            id: 1,
1143            subscription: None,
1144        });
1145        let model2 = cx.add_model(|_| Model {
1146            id: 2,
1147            subscription: None,
1148        });
1149        let model3 = cx.add_model(|_| Model {
1150            id: 3,
1151            subscription: None,
1152        });
1153
1154        let _subscription1 = model1.update(cx, |_, cx| client.add_model_for_remote_entity(1, cx));
1155        let _subscription2 = model2.update(cx, |_, cx| client.add_model_for_remote_entity(2, cx));
1156        // Ensure dropping a subscription for the same entity type still allows receiving of
1157        // messages for other entity IDs of the same type.
1158        let subscription3 = model3.update(cx, |_, cx| client.add_model_for_remote_entity(3, cx));
1159        drop(subscription3);
1160
1161        server.send(proto::UnshareProject { project_id: 1 });
1162        server.send(proto::UnshareProject { project_id: 2 });
1163        done_rx1.next().await.unwrap();
1164        done_rx2.next().await.unwrap();
1165    }
1166
1167    #[gpui::test]
1168    async fn test_subscribing_after_dropping_subscription(cx: &mut TestAppContext) {
1169        cx.foreground().forbid_parking();
1170
1171        let user_id = 5;
1172        let mut client = Client::new(FakeHttpClient::with_404_response());
1173        let server = FakeServer::for_client(user_id, &mut client, &cx).await;
1174
1175        let model = cx.add_model(|_| Model::default());
1176        let (done_tx1, _done_rx1) = smol::channel::unbounded();
1177        let (done_tx2, mut done_rx2) = smol::channel::unbounded();
1178        let subscription1 = client.add_message_handler(
1179            model.clone(),
1180            move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1181                done_tx1.try_send(()).unwrap();
1182                async { Ok(()) }
1183            },
1184        );
1185        drop(subscription1);
1186        let _subscription2 =
1187            client.add_message_handler(model, move |_, _: TypedEnvelope<proto::Ping>, _, _| {
1188                done_tx2.try_send(()).unwrap();
1189                async { Ok(()) }
1190            });
1191        server.send(proto::Ping {});
1192        done_rx2.next().await.unwrap();
1193    }
1194
1195    #[gpui::test]
1196    async fn test_dropping_subscription_in_handler(cx: &mut TestAppContext) {
1197        cx.foreground().forbid_parking();
1198
1199        let user_id = 5;
1200        let mut client = Client::new(FakeHttpClient::with_404_response());
1201        let server = FakeServer::for_client(user_id, &mut client, &cx).await;
1202
1203        let model = cx.add_model(|_| Model::default());
1204        let (done_tx, mut done_rx) = smol::channel::unbounded();
1205        let subscription = client.add_message_handler(
1206            model.clone(),
1207            move |model, _: TypedEnvelope<proto::Ping>, _, mut cx| {
1208                model.update(&mut cx, |model, _| model.subscription.take());
1209                done_tx.try_send(()).unwrap();
1210                async { Ok(()) }
1211            },
1212        );
1213        model.update(cx, |model, _| {
1214            model.subscription = Some(subscription);
1215        });
1216        server.send(proto::Ping {});
1217        done_rx.next().await.unwrap();
1218    }
1219
1220    #[derive(Default)]
1221    struct Model {
1222        id: usize,
1223        subscription: Option<Subscription>,
1224    }
1225
1226    impl Entity for Model {
1227        type Event = ();
1228    }
1229}