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