client.rs

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