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