remote_client.rs

   1use crate::{
   2    SshConnectionOptions,
   3    protocol::MessageId,
   4    proxy::ProxyLaunchError,
   5    transport::{
   6        ssh::SshRemoteConnection,
   7        wsl::{WslConnectionOptions, WslRemoteConnection},
   8    },
   9};
  10use anyhow::{Context as _, Result, anyhow};
  11use askpass::EncryptedPassword;
  12use async_trait::async_trait;
  13use collections::HashMap;
  14use futures::{
  15    Future, FutureExt as _, StreamExt as _,
  16    channel::{
  17        mpsc::{self, Sender, UnboundedReceiver, UnboundedSender},
  18        oneshot,
  19    },
  20    future::{BoxFuture, Shared},
  21    select, select_biased,
  22};
  23use gpui::{
  24    App, AppContext as _, AsyncApp, BackgroundExecutor, BorrowAppContext, Context, Entity,
  25    EventEmitter, FutureExt, Global, SemanticVersion, Task, WeakEntity,
  26};
  27use parking_lot::Mutex;
  28
  29use release_channel::ReleaseChannel;
  30use rpc::{
  31    AnyProtoClient, ErrorExt, ProtoClient, ProtoMessageHandlerSet, RpcError,
  32    proto::{self, Envelope, EnvelopedMessage, PeerId, RequestMessage, build_typed_envelope},
  33};
  34use std::{
  35    collections::VecDeque,
  36    fmt,
  37    ops::ControlFlow,
  38    path::PathBuf,
  39    sync::{
  40        Arc, Weak,
  41        atomic::{AtomicU32, AtomicU64, Ordering::SeqCst},
  42    },
  43    time::{Duration, Instant},
  44};
  45use util::{
  46    ResultExt,
  47    paths::{PathStyle, RemotePathBuf},
  48};
  49
  50#[derive(Copy, Clone, Debug)]
  51pub struct RemotePlatform {
  52    pub os: &'static str,
  53    pub arch: &'static str,
  54}
  55
  56#[derive(Clone, Debug)]
  57pub struct CommandTemplate {
  58    pub program: String,
  59    pub args: Vec<String>,
  60    pub env: HashMap<String, String>,
  61}
  62
  63pub trait RemoteClientDelegate: Send + Sync {
  64    fn ask_password(
  65        &self,
  66        prompt: String,
  67        tx: oneshot::Sender<EncryptedPassword>,
  68        cx: &mut AsyncApp,
  69    );
  70    fn get_download_params(
  71        &self,
  72        platform: RemotePlatform,
  73        release_channel: ReleaseChannel,
  74        version: Option<SemanticVersion>,
  75        cx: &mut AsyncApp,
  76    ) -> Task<Result<Option<(String, String)>>>;
  77    fn download_server_binary_locally(
  78        &self,
  79        platform: RemotePlatform,
  80        release_channel: ReleaseChannel,
  81        version: Option<SemanticVersion>,
  82        cx: &mut AsyncApp,
  83    ) -> Task<Result<PathBuf>>;
  84    fn set_status(&self, status: Option<&str>, cx: &mut AsyncApp);
  85}
  86
  87const MAX_MISSED_HEARTBEATS: usize = 5;
  88const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
  89const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(5);
  90
  91const MAX_RECONNECT_ATTEMPTS: usize = 3;
  92
  93enum State {
  94    Connecting,
  95    Connected {
  96        ssh_connection: Arc<dyn RemoteConnection>,
  97        delegate: Arc<dyn RemoteClientDelegate>,
  98
  99        multiplex_task: Task<Result<()>>,
 100        heartbeat_task: Task<Result<()>>,
 101    },
 102    HeartbeatMissed {
 103        missed_heartbeats: usize,
 104
 105        ssh_connection: Arc<dyn RemoteConnection>,
 106        delegate: Arc<dyn RemoteClientDelegate>,
 107
 108        multiplex_task: Task<Result<()>>,
 109        heartbeat_task: Task<Result<()>>,
 110    },
 111    Reconnecting,
 112    ReconnectFailed {
 113        ssh_connection: Arc<dyn RemoteConnection>,
 114        delegate: Arc<dyn RemoteClientDelegate>,
 115
 116        error: anyhow::Error,
 117        attempts: usize,
 118    },
 119    ReconnectExhausted,
 120    ServerNotRunning,
 121}
 122
 123impl fmt::Display for State {
 124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 125        match self {
 126            Self::Connecting => write!(f, "connecting"),
 127            Self::Connected { .. } => write!(f, "connected"),
 128            Self::Reconnecting => write!(f, "reconnecting"),
 129            Self::ReconnectFailed { .. } => write!(f, "reconnect failed"),
 130            Self::ReconnectExhausted => write!(f, "reconnect exhausted"),
 131            Self::HeartbeatMissed { .. } => write!(f, "heartbeat missed"),
 132            Self::ServerNotRunning { .. } => write!(f, "server not running"),
 133        }
 134    }
 135}
 136
 137impl State {
 138    fn remote_connection(&self) -> Option<Arc<dyn RemoteConnection>> {
 139        match self {
 140            Self::Connected { ssh_connection, .. } => Some(ssh_connection.clone()),
 141            Self::HeartbeatMissed { ssh_connection, .. } => Some(ssh_connection.clone()),
 142            Self::ReconnectFailed { ssh_connection, .. } => Some(ssh_connection.clone()),
 143            _ => None,
 144        }
 145    }
 146
 147    fn can_reconnect(&self) -> bool {
 148        match self {
 149            Self::Connected { .. }
 150            | Self::HeartbeatMissed { .. }
 151            | Self::ReconnectFailed { .. } => true,
 152            State::Connecting
 153            | State::Reconnecting
 154            | State::ReconnectExhausted
 155            | State::ServerNotRunning => false,
 156        }
 157    }
 158
 159    fn is_reconnect_failed(&self) -> bool {
 160        matches!(self, Self::ReconnectFailed { .. })
 161    }
 162
 163    fn is_reconnect_exhausted(&self) -> bool {
 164        matches!(self, Self::ReconnectExhausted { .. })
 165    }
 166
 167    fn is_server_not_running(&self) -> bool {
 168        matches!(self, Self::ServerNotRunning)
 169    }
 170
 171    fn is_reconnecting(&self) -> bool {
 172        matches!(self, Self::Reconnecting { .. })
 173    }
 174
 175    fn heartbeat_recovered(self) -> Self {
 176        match self {
 177            Self::HeartbeatMissed {
 178                ssh_connection,
 179                delegate,
 180                multiplex_task,
 181                heartbeat_task,
 182                ..
 183            } => Self::Connected {
 184                ssh_connection,
 185                delegate,
 186                multiplex_task,
 187                heartbeat_task,
 188            },
 189            _ => self,
 190        }
 191    }
 192
 193    fn heartbeat_missed(self) -> Self {
 194        match self {
 195            Self::Connected {
 196                ssh_connection,
 197                delegate,
 198                multiplex_task,
 199                heartbeat_task,
 200            } => Self::HeartbeatMissed {
 201                missed_heartbeats: 1,
 202                ssh_connection,
 203                delegate,
 204                multiplex_task,
 205                heartbeat_task,
 206            },
 207            Self::HeartbeatMissed {
 208                missed_heartbeats,
 209                ssh_connection,
 210                delegate,
 211                multiplex_task,
 212                heartbeat_task,
 213            } => Self::HeartbeatMissed {
 214                missed_heartbeats: missed_heartbeats + 1,
 215                ssh_connection,
 216                delegate,
 217                multiplex_task,
 218                heartbeat_task,
 219            },
 220            _ => self,
 221        }
 222    }
 223}
 224
 225/// The state of the ssh connection.
 226#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 227pub enum ConnectionState {
 228    Connecting,
 229    Connected,
 230    HeartbeatMissed,
 231    Reconnecting,
 232    Disconnected,
 233}
 234
 235impl From<&State> for ConnectionState {
 236    fn from(value: &State) -> Self {
 237        match value {
 238            State::Connecting => Self::Connecting,
 239            State::Connected { .. } => Self::Connected,
 240            State::Reconnecting | State::ReconnectFailed { .. } => Self::Reconnecting,
 241            State::HeartbeatMissed { .. } => Self::HeartbeatMissed,
 242            State::ReconnectExhausted => Self::Disconnected,
 243            State::ServerNotRunning => Self::Disconnected,
 244        }
 245    }
 246}
 247
 248pub struct RemoteClient {
 249    client: Arc<ChannelClient>,
 250    unique_identifier: String,
 251    connection_options: RemoteConnectionOptions,
 252    path_style: PathStyle,
 253    state: Option<State>,
 254}
 255
 256#[derive(Debug)]
 257pub enum RemoteClientEvent {
 258    Disconnected,
 259}
 260
 261impl EventEmitter<RemoteClientEvent> for RemoteClient {}
 262
 263// Identifies the socket on the remote server so that reconnects
 264// can re-join the same project.
 265pub enum ConnectionIdentifier {
 266    Setup(u64),
 267    Workspace(i64),
 268}
 269
 270static NEXT_ID: AtomicU64 = AtomicU64::new(1);
 271
 272impl ConnectionIdentifier {
 273    pub fn setup() -> Self {
 274        Self::Setup(NEXT_ID.fetch_add(1, SeqCst))
 275    }
 276
 277    // This string gets used in a socket name, and so must be relatively short.
 278    // The total length of:
 279    //   /home/{username}/.local/share/zed/server_state/{name}/stdout.sock
 280    // Must be less than about 100 characters
 281    //   https://unix.stackexchange.com/questions/367008/why-is-socket-path-length-limited-to-a-hundred-chars
 282    // So our strings should be at most 20 characters or so.
 283    fn to_string(&self, cx: &App) -> String {
 284        let identifier_prefix = match ReleaseChannel::global(cx) {
 285            ReleaseChannel::Stable => "".to_string(),
 286            release_channel => format!("{}-", release_channel.dev_name()),
 287        };
 288        match self {
 289            Self::Setup(setup_id) => format!("{identifier_prefix}setup-{setup_id}"),
 290            Self::Workspace(workspace_id) => {
 291                format!("{identifier_prefix}workspace-{workspace_id}",)
 292            }
 293        }
 294    }
 295}
 296
 297impl RemoteClient {
 298    pub fn ssh(
 299        unique_identifier: ConnectionIdentifier,
 300        connection_options: SshConnectionOptions,
 301        cancellation: oneshot::Receiver<()>,
 302        delegate: Arc<dyn RemoteClientDelegate>,
 303        cx: &mut App,
 304    ) -> Task<Result<Option<Entity<Self>>>> {
 305        Self::new(
 306            unique_identifier,
 307            RemoteConnectionOptions::Ssh(connection_options),
 308            cancellation,
 309            delegate,
 310            cx,
 311        )
 312    }
 313
 314    pub fn new(
 315        unique_identifier: ConnectionIdentifier,
 316        connection_options: RemoteConnectionOptions,
 317        cancellation: oneshot::Receiver<()>,
 318        delegate: Arc<dyn RemoteClientDelegate>,
 319        cx: &mut App,
 320    ) -> Task<Result<Option<Entity<Self>>>> {
 321        let unique_identifier = unique_identifier.to_string(cx);
 322        cx.spawn(async move |cx| {
 323            let success = Box::pin(async move {
 324                let (outgoing_tx, outgoing_rx) = mpsc::unbounded::<Envelope>();
 325                let (incoming_tx, incoming_rx) = mpsc::unbounded::<Envelope>();
 326                let (connection_activity_tx, connection_activity_rx) = mpsc::channel::<()>(1);
 327
 328                let client =
 329                    cx.update(|cx| ChannelClient::new(incoming_rx, outgoing_tx, cx, "client"))?;
 330
 331                let ssh_connection = cx
 332                    .update(|cx| {
 333                        cx.update_default_global(|pool: &mut ConnectionPool, cx| {
 334                            pool.connect(connection_options.clone(), delegate.clone(), cx)
 335                        })
 336                    })?
 337                    .await
 338                    .map_err(|e| e.cloned())?;
 339
 340                let path_style = ssh_connection.path_style();
 341                let this = cx.new(|_| Self {
 342                    client: client.clone(),
 343                    unique_identifier: unique_identifier.clone(),
 344                    connection_options,
 345                    path_style,
 346                    state: Some(State::Connecting),
 347                })?;
 348
 349                let io_task = ssh_connection.start_proxy(
 350                    unique_identifier,
 351                    false,
 352                    incoming_tx,
 353                    outgoing_rx,
 354                    connection_activity_tx,
 355                    delegate.clone(),
 356                    cx,
 357                );
 358
 359                let ready = client
 360                    .wait_for_remote_started()
 361                    .with_timeout(HEARTBEAT_TIMEOUT, cx.background_executor())
 362                    .await;
 363                match ready {
 364                    Ok(Some(_)) => {}
 365                    Ok(None) => {
 366                        let mut error = "remote client exited before becoming ready".to_owned();
 367                        if let Some(status) = io_task.now_or_never() {
 368                            match status {
 369                                Ok(exit_code) => {
 370                                    error.push_str(&format!(", exit_code={exit_code:?}"))
 371                                }
 372                                Err(e) => error.push_str(&format!(", error={e:?}")),
 373                            }
 374                        }
 375                        let error = anyhow::anyhow!("{error}");
 376                        log::error!("failed to establish connection: {}", error);
 377                        return Err(error);
 378                    }
 379                    Err(_) => {
 380                        let mut error =
 381                            "remote client did not become ready within the timeout".to_owned();
 382                        if let Some(status) = io_task.now_or_never() {
 383                            match status {
 384                                Ok(exit_code) => {
 385                                    error.push_str(&format!(", exit_code={exit_code:?}"))
 386                                }
 387                                Err(e) => error.push_str(&format!(", error={e:?}")),
 388                            }
 389                        }
 390                        let error = anyhow::anyhow!("{error}");
 391                        log::error!("failed to establish connection: {}", error);
 392                        return Err(error);
 393                    }
 394                }
 395                let multiplex_task = Self::monitor(this.downgrade(), io_task, cx);
 396                if let Err(error) = client.ping(HEARTBEAT_TIMEOUT).await {
 397                    log::error!("failed to establish connection: {}", error);
 398                    return Err(error);
 399                }
 400
 401                let heartbeat_task = Self::heartbeat(this.downgrade(), connection_activity_rx, cx);
 402
 403                this.update(cx, |this, _| {
 404                    this.state = Some(State::Connected {
 405                        ssh_connection,
 406                        delegate,
 407                        multiplex_task,
 408                        heartbeat_task,
 409                    });
 410                })?;
 411
 412                Ok(Some(this))
 413            });
 414
 415            select! {
 416                _ = cancellation.fuse() => {
 417                    Ok(None)
 418                }
 419                result = success.fuse() =>  result
 420            }
 421        })
 422    }
 423
 424    pub fn proto_client_from_channels(
 425        incoming_rx: mpsc::UnboundedReceiver<Envelope>,
 426        outgoing_tx: mpsc::UnboundedSender<Envelope>,
 427        cx: &App,
 428        name: &'static str,
 429    ) -> AnyProtoClient {
 430        ChannelClient::new(incoming_rx, outgoing_tx, cx, name).into()
 431    }
 432
 433    pub fn shutdown_processes<T: RequestMessage>(
 434        &mut self,
 435        shutdown_request: Option<T>,
 436        executor: BackgroundExecutor,
 437    ) -> Option<impl Future<Output = ()> + use<T>> {
 438        let state = self.state.take()?;
 439        log::info!("shutting down ssh processes");
 440
 441        let State::Connected {
 442            multiplex_task,
 443            heartbeat_task,
 444            ssh_connection,
 445            delegate,
 446        } = state
 447        else {
 448            return None;
 449        };
 450
 451        let client = self.client.clone();
 452
 453        Some(async move {
 454            if let Some(shutdown_request) = shutdown_request {
 455                client.send(shutdown_request).log_err();
 456                // We wait 50ms instead of waiting for a response, because
 457                // waiting for a response would require us to wait on the main thread
 458                // which we want to avoid in an `on_app_quit` callback.
 459                executor.timer(Duration::from_millis(50)).await;
 460            }
 461
 462            // Drop `multiplex_task` because it owns our ssh_proxy_process, which is a
 463            // child of master_process.
 464            drop(multiplex_task);
 465            // Now drop the rest of state, which kills master process.
 466            drop(heartbeat_task);
 467            drop(ssh_connection);
 468            drop(delegate);
 469        })
 470    }
 471
 472    fn reconnect(&mut self, cx: &mut Context<Self>) -> Result<()> {
 473        let can_reconnect = self
 474            .state
 475            .as_ref()
 476            .map(|state| state.can_reconnect())
 477            .unwrap_or(false);
 478        if !can_reconnect {
 479            log::info!("aborting reconnect, because not in state that allows reconnecting");
 480            let error = if let Some(state) = self.state.as_ref() {
 481                format!("invalid state, cannot reconnect while in state {state}")
 482            } else {
 483                "no state set".to_string()
 484            };
 485            anyhow::bail!(error);
 486        }
 487
 488        let state = self.state.take().unwrap();
 489        let (attempts, remote_connection, delegate) = match state {
 490            State::Connected {
 491                ssh_connection,
 492                delegate,
 493                multiplex_task,
 494                heartbeat_task,
 495            }
 496            | State::HeartbeatMissed {
 497                ssh_connection,
 498                delegate,
 499                multiplex_task,
 500                heartbeat_task,
 501                ..
 502            } => {
 503                drop(multiplex_task);
 504                drop(heartbeat_task);
 505                (0, ssh_connection, delegate)
 506            }
 507            State::ReconnectFailed {
 508                attempts,
 509                ssh_connection,
 510                delegate,
 511                ..
 512            } => (attempts, ssh_connection, delegate),
 513            State::Connecting
 514            | State::Reconnecting
 515            | State::ReconnectExhausted
 516            | State::ServerNotRunning => unreachable!(),
 517        };
 518
 519        let attempts = attempts + 1;
 520        if attempts > MAX_RECONNECT_ATTEMPTS {
 521            log::error!(
 522                "Failed to reconnect to after {} attempts, giving up",
 523                MAX_RECONNECT_ATTEMPTS
 524            );
 525            self.set_state(State::ReconnectExhausted, cx);
 526            return Ok(());
 527        }
 528
 529        self.set_state(State::Reconnecting, cx);
 530
 531        log::info!("Trying to reconnect to ssh server... Attempt {}", attempts);
 532
 533        let unique_identifier = self.unique_identifier.clone();
 534        let client = self.client.clone();
 535        let reconnect_task = cx.spawn(async move |this, cx| {
 536            macro_rules! failed {
 537                ($error:expr, $attempts:expr, $ssh_connection:expr, $delegate:expr) => {
 538                    return State::ReconnectFailed {
 539                        error: anyhow!($error),
 540                        attempts: $attempts,
 541                        ssh_connection: $ssh_connection,
 542                        delegate: $delegate,
 543                    };
 544                };
 545            }
 546
 547            if let Err(error) = remote_connection
 548                .kill()
 549                .await
 550                .context("Failed to kill ssh process")
 551            {
 552                failed!(error, attempts, remote_connection, delegate);
 553            };
 554
 555            let connection_options = remote_connection.connection_options();
 556
 557            let (outgoing_tx, outgoing_rx) = mpsc::unbounded::<Envelope>();
 558            let (incoming_tx, incoming_rx) = mpsc::unbounded::<Envelope>();
 559            let (connection_activity_tx, connection_activity_rx) = mpsc::channel::<()>(1);
 560
 561            let (ssh_connection, io_task) = match async {
 562                let ssh_connection = cx
 563                    .update_global(|pool: &mut ConnectionPool, cx| {
 564                        pool.connect(connection_options, delegate.clone(), cx)
 565                    })?
 566                    .await
 567                    .map_err(|error| error.cloned())?;
 568
 569                let io_task = ssh_connection.start_proxy(
 570                    unique_identifier,
 571                    true,
 572                    incoming_tx,
 573                    outgoing_rx,
 574                    connection_activity_tx,
 575                    delegate.clone(),
 576                    cx,
 577                );
 578                anyhow::Ok((ssh_connection, io_task))
 579            }
 580            .await
 581            {
 582                Ok((ssh_connection, io_task)) => (ssh_connection, io_task),
 583                Err(error) => {
 584                    failed!(error, attempts, remote_connection, delegate);
 585                }
 586            };
 587
 588            let multiplex_task = Self::monitor(this.clone(), io_task, cx);
 589            client.reconnect(incoming_rx, outgoing_tx, cx);
 590
 591            if let Err(error) = client.resync(HEARTBEAT_TIMEOUT).await {
 592                failed!(error, attempts, ssh_connection, delegate);
 593            };
 594
 595            State::Connected {
 596                ssh_connection,
 597                delegate,
 598                multiplex_task,
 599                heartbeat_task: Self::heartbeat(this.clone(), connection_activity_rx, cx),
 600            }
 601        });
 602
 603        cx.spawn(async move |this, cx| {
 604            let new_state = reconnect_task.await;
 605            this.update(cx, |this, cx| {
 606                this.try_set_state(cx, |old_state| {
 607                    if old_state.is_reconnecting() {
 608                        match &new_state {
 609                            State::Connecting
 610                            | State::Reconnecting
 611                            | State::HeartbeatMissed { .. }
 612                            | State::ServerNotRunning => {}
 613                            State::Connected { .. } => {
 614                                log::info!("Successfully reconnected");
 615                            }
 616                            State::ReconnectFailed {
 617                                error, attempts, ..
 618                            } => {
 619                                log::error!(
 620                                    "Reconnect attempt {} failed: {:?}. Starting new attempt...",
 621                                    attempts,
 622                                    error
 623                                );
 624                            }
 625                            State::ReconnectExhausted => {
 626                                log::error!("Reconnect attempt failed and all attempts exhausted");
 627                            }
 628                        }
 629                        Some(new_state)
 630                    } else {
 631                        None
 632                    }
 633                });
 634
 635                if this.state_is(State::is_reconnect_failed) {
 636                    this.reconnect(cx)
 637                } else if this.state_is(State::is_reconnect_exhausted) {
 638                    Ok(())
 639                } else {
 640                    log::debug!("State has transition from Reconnecting into new state while attempting reconnect.");
 641                    Ok(())
 642                }
 643            })
 644        })
 645        .detach_and_log_err(cx);
 646
 647        Ok(())
 648    }
 649
 650    fn heartbeat(
 651        this: WeakEntity<Self>,
 652        mut connection_activity_rx: mpsc::Receiver<()>,
 653        cx: &mut AsyncApp,
 654    ) -> Task<Result<()>> {
 655        let Ok(client) = this.read_with(cx, |this, _| this.client.clone()) else {
 656            return Task::ready(Err(anyhow!("SshRemoteClient lost")));
 657        };
 658
 659        cx.spawn(async move |cx| {
 660            let mut missed_heartbeats = 0;
 661
 662            let keepalive_timer = cx.background_executor().timer(HEARTBEAT_INTERVAL).fuse();
 663            futures::pin_mut!(keepalive_timer);
 664
 665            loop {
 666                select_biased! {
 667                    result = connection_activity_rx.next().fuse() => {
 668                        if result.is_none() {
 669                            log::warn!("ssh heartbeat: connection activity channel has been dropped. stopping.");
 670                            return Ok(());
 671                        }
 672
 673                        if missed_heartbeats != 0 {
 674                            missed_heartbeats = 0;
 675                            let _ =this.update(cx, |this, cx| {
 676                                this.handle_heartbeat_result(missed_heartbeats, cx)
 677                            })?;
 678                        }
 679                    }
 680                    _ = keepalive_timer => {
 681                        log::debug!("Sending heartbeat to server...");
 682
 683                        let result = select_biased! {
 684                            _ = connection_activity_rx.next().fuse() => {
 685                                Ok(())
 686                            }
 687                            ping_result = client.ping(HEARTBEAT_TIMEOUT).fuse() => {
 688                                ping_result
 689                            }
 690                        };
 691
 692                        if result.is_err() {
 693                            missed_heartbeats += 1;
 694                            log::warn!(
 695                                "No heartbeat from server after {:?}. Missed heartbeat {} out of {}.",
 696                                HEARTBEAT_TIMEOUT,
 697                                missed_heartbeats,
 698                                MAX_MISSED_HEARTBEATS
 699                            );
 700                        } else if missed_heartbeats != 0 {
 701                            missed_heartbeats = 0;
 702                        } else {
 703                            continue;
 704                        }
 705
 706                        let result = this.update(cx, |this, cx| {
 707                            this.handle_heartbeat_result(missed_heartbeats, cx)
 708                        })?;
 709                        if result.is_break() {
 710                            return Ok(());
 711                        }
 712                    }
 713                }
 714
 715                keepalive_timer.set(cx.background_executor().timer(HEARTBEAT_INTERVAL).fuse());
 716            }
 717        })
 718    }
 719
 720    fn handle_heartbeat_result(
 721        &mut self,
 722        missed_heartbeats: usize,
 723        cx: &mut Context<Self>,
 724    ) -> ControlFlow<()> {
 725        let state = self.state.take().unwrap();
 726        let next_state = if missed_heartbeats > 0 {
 727            state.heartbeat_missed()
 728        } else {
 729            state.heartbeat_recovered()
 730        };
 731
 732        self.set_state(next_state, cx);
 733
 734        if missed_heartbeats >= MAX_MISSED_HEARTBEATS {
 735            log::error!(
 736                "Missed last {} heartbeats. Reconnecting...",
 737                missed_heartbeats
 738            );
 739
 740            self.reconnect(cx)
 741                .context("failed to start reconnect process after missing heartbeats")
 742                .log_err();
 743            ControlFlow::Break(())
 744        } else {
 745            ControlFlow::Continue(())
 746        }
 747    }
 748
 749    fn monitor(
 750        this: WeakEntity<Self>,
 751        io_task: Task<Result<i32>>,
 752        cx: &AsyncApp,
 753    ) -> Task<Result<()>> {
 754        cx.spawn(async move |cx| {
 755            let result = io_task.await;
 756
 757            match result {
 758                Ok(exit_code) => {
 759                    if let Some(error) = ProxyLaunchError::from_exit_code(exit_code) {
 760                        match error {
 761                            ProxyLaunchError::ServerNotRunning => {
 762                                log::error!("failed to reconnect because server is not running");
 763                                this.update(cx, |this, cx| {
 764                                    this.set_state(State::ServerNotRunning, cx);
 765                                })?;
 766                            }
 767                        }
 768                    } else if exit_code > 0 {
 769                        log::error!("proxy process terminated unexpectedly");
 770                        this.update(cx, |this, cx| {
 771                            this.reconnect(cx).ok();
 772                        })?;
 773                    }
 774                }
 775                Err(error) => {
 776                    log::warn!("ssh io task died with error: {:?}. reconnecting...", error);
 777                    this.update(cx, |this, cx| {
 778                        this.reconnect(cx).ok();
 779                    })?;
 780                }
 781            }
 782
 783            Ok(())
 784        })
 785    }
 786
 787    fn state_is(&self, check: impl FnOnce(&State) -> bool) -> bool {
 788        self.state.as_ref().is_some_and(check)
 789    }
 790
 791    fn try_set_state(&mut self, cx: &mut Context<Self>, map: impl FnOnce(&State) -> Option<State>) {
 792        let new_state = self.state.as_ref().and_then(map);
 793        if let Some(new_state) = new_state {
 794            self.state.replace(new_state);
 795            cx.notify();
 796        }
 797    }
 798
 799    fn set_state(&mut self, state: State, cx: &mut Context<Self>) {
 800        log::info!("setting state to '{}'", &state);
 801
 802        let is_reconnect_exhausted = state.is_reconnect_exhausted();
 803        let is_server_not_running = state.is_server_not_running();
 804        self.state.replace(state);
 805
 806        if is_reconnect_exhausted || is_server_not_running {
 807            cx.emit(RemoteClientEvent::Disconnected);
 808        }
 809        cx.notify();
 810    }
 811
 812    pub fn shell(&self) -> Option<String> {
 813        Some(self.remote_connection()?.shell())
 814    }
 815
 816    pub fn default_system_shell(&self) -> Option<String> {
 817        Some(self.remote_connection()?.default_system_shell())
 818    }
 819
 820    pub fn shares_network_interface(&self) -> bool {
 821        self.remote_connection()
 822            .map_or(false, |connection| connection.shares_network_interface())
 823    }
 824
 825    pub fn build_command(
 826        &self,
 827        program: Option<String>,
 828        args: &[String],
 829        env: &HashMap<String, String>,
 830        working_dir: Option<String>,
 831        port_forward: Option<(u16, String, u16)>,
 832    ) -> Result<CommandTemplate> {
 833        let Some(connection) = self.remote_connection() else {
 834            return Err(anyhow!("no ssh connection"));
 835        };
 836        connection.build_command(program, args, env, working_dir, port_forward)
 837    }
 838
 839    pub fn build_forward_ports_command(
 840        &self,
 841        forwards: Vec<(u16, String, u16)>,
 842    ) -> Result<CommandTemplate> {
 843        let Some(connection) = self.remote_connection() else {
 844            return Err(anyhow!("no ssh connection"));
 845        };
 846        connection.build_forward_ports_command(forwards)
 847    }
 848
 849    pub fn upload_directory(
 850        &self,
 851        src_path: PathBuf,
 852        dest_path: RemotePathBuf,
 853        cx: &App,
 854    ) -> Task<Result<()>> {
 855        let Some(connection) = self.remote_connection() else {
 856            return Task::ready(Err(anyhow!("no ssh connection")));
 857        };
 858        connection.upload_directory(src_path, dest_path, cx)
 859    }
 860
 861    pub fn proto_client(&self) -> AnyProtoClient {
 862        self.client.clone().into()
 863    }
 864
 865    pub fn connection_options(&self) -> RemoteConnectionOptions {
 866        self.connection_options.clone()
 867    }
 868
 869    pub fn connection_state(&self) -> ConnectionState {
 870        self.state
 871            .as_ref()
 872            .map(ConnectionState::from)
 873            .unwrap_or(ConnectionState::Disconnected)
 874    }
 875
 876    pub fn is_disconnected(&self) -> bool {
 877        self.connection_state() == ConnectionState::Disconnected
 878    }
 879
 880    pub fn path_style(&self) -> PathStyle {
 881        self.path_style
 882    }
 883
 884    #[cfg(any(test, feature = "test-support"))]
 885    pub fn simulate_disconnect(&self, client_cx: &mut App) -> Task<()> {
 886        let opts = self.connection_options();
 887        client_cx.spawn(async move |cx| {
 888            let connection = cx
 889                .update_global(|c: &mut ConnectionPool, _| {
 890                    if let Some(ConnectionPoolEntry::Connecting(c)) = c.connections.get(&opts) {
 891                        c.clone()
 892                    } else {
 893                        panic!("missing test connection")
 894                    }
 895                })
 896                .unwrap()
 897                .await
 898                .unwrap();
 899
 900            connection.simulate_disconnect(cx);
 901        })
 902    }
 903
 904    #[cfg(any(test, feature = "test-support"))]
 905    pub fn fake_server(
 906        client_cx: &mut gpui::TestAppContext,
 907        server_cx: &mut gpui::TestAppContext,
 908    ) -> (RemoteConnectionOptions, AnyProtoClient) {
 909        let port = client_cx
 910            .update(|cx| cx.default_global::<ConnectionPool>().connections.len() as u16 + 1);
 911        let opts = RemoteConnectionOptions::Ssh(SshConnectionOptions {
 912            host: "<fake>".to_string(),
 913            port: Some(port),
 914            ..Default::default()
 915        });
 916        let (outgoing_tx, _) = mpsc::unbounded::<Envelope>();
 917        let (_, incoming_rx) = mpsc::unbounded::<Envelope>();
 918        let server_client =
 919            server_cx.update(|cx| ChannelClient::new(incoming_rx, outgoing_tx, cx, "fake-server"));
 920        let connection: Arc<dyn RemoteConnection> = Arc::new(fake::FakeRemoteConnection {
 921            connection_options: opts.clone(),
 922            server_cx: fake::SendableCx::new(server_cx),
 923            server_channel: server_client.clone(),
 924        });
 925
 926        client_cx.update(|cx| {
 927            cx.update_default_global(|c: &mut ConnectionPool, cx| {
 928                c.connections.insert(
 929                    opts.clone(),
 930                    ConnectionPoolEntry::Connecting(
 931                        cx.background_spawn({
 932                            let connection = connection.clone();
 933                            async move { Ok(connection.clone()) }
 934                        })
 935                        .shared(),
 936                    ),
 937                );
 938            })
 939        });
 940
 941        (opts, server_client.into())
 942    }
 943
 944    #[cfg(any(test, feature = "test-support"))]
 945    pub async fn fake_client(
 946        opts: RemoteConnectionOptions,
 947        client_cx: &mut gpui::TestAppContext,
 948    ) -> Entity<Self> {
 949        let (_tx, rx) = oneshot::channel();
 950        client_cx
 951            .update(|cx| {
 952                Self::new(
 953                    ConnectionIdentifier::setup(),
 954                    opts,
 955                    rx,
 956                    Arc::new(fake::Delegate),
 957                    cx,
 958                )
 959            })
 960            .await
 961            .unwrap()
 962            .unwrap()
 963    }
 964
 965    fn remote_connection(&self) -> Option<Arc<dyn RemoteConnection>> {
 966        self.state
 967            .as_ref()
 968            .and_then(|state| state.remote_connection())
 969    }
 970}
 971
 972enum ConnectionPoolEntry {
 973    Connecting(Shared<Task<Result<Arc<dyn RemoteConnection>, Arc<anyhow::Error>>>>),
 974    Connected(Weak<dyn RemoteConnection>),
 975}
 976
 977#[derive(Default)]
 978struct ConnectionPool {
 979    connections: HashMap<RemoteConnectionOptions, ConnectionPoolEntry>,
 980}
 981
 982impl Global for ConnectionPool {}
 983
 984impl ConnectionPool {
 985    pub fn connect(
 986        &mut self,
 987        opts: RemoteConnectionOptions,
 988        delegate: Arc<dyn RemoteClientDelegate>,
 989        cx: &mut App,
 990    ) -> Shared<Task<Result<Arc<dyn RemoteConnection>, Arc<anyhow::Error>>>> {
 991        let connection = self.connections.get(&opts);
 992        match connection {
 993            Some(ConnectionPoolEntry::Connecting(task)) => {
 994                let delegate = delegate.clone();
 995                cx.spawn(async move |cx| {
 996                    delegate.set_status(Some("Waiting for existing connection attempt"), cx);
 997                })
 998                .detach();
 999                return task.clone();
1000            }
1001            Some(ConnectionPoolEntry::Connected(ssh)) => {
1002                if let Some(ssh) = ssh.upgrade()
1003                    && !ssh.has_been_killed()
1004                {
1005                    return Task::ready(Ok(ssh)).shared();
1006                }
1007                self.connections.remove(&opts);
1008            }
1009            None => {}
1010        }
1011
1012        let task = cx
1013            .spawn({
1014                let opts = opts.clone();
1015                let delegate = delegate.clone();
1016                async move |cx| {
1017                    let connection = match opts.clone() {
1018                        RemoteConnectionOptions::Ssh(opts) => {
1019                            SshRemoteConnection::new(opts, delegate, cx)
1020                                .await
1021                                .map(|connection| Arc::new(connection) as Arc<dyn RemoteConnection>)
1022                        }
1023                        RemoteConnectionOptions::Wsl(opts) => {
1024                            WslRemoteConnection::new(opts, delegate, cx)
1025                                .await
1026                                .map(|connection| Arc::new(connection) as Arc<dyn RemoteConnection>)
1027                        }
1028                    };
1029
1030                    cx.update_global(|pool: &mut Self, _| {
1031                        debug_assert!(matches!(
1032                            pool.connections.get(&opts),
1033                            Some(ConnectionPoolEntry::Connecting(_))
1034                        ));
1035                        match connection {
1036                            Ok(connection) => {
1037                                pool.connections.insert(
1038                                    opts.clone(),
1039                                    ConnectionPoolEntry::Connected(Arc::downgrade(&connection)),
1040                                );
1041                                Ok(connection)
1042                            }
1043                            Err(error) => {
1044                                pool.connections.remove(&opts);
1045                                Err(Arc::new(error))
1046                            }
1047                        }
1048                    })?
1049                }
1050            })
1051            .shared();
1052
1053        self.connections
1054            .insert(opts.clone(), ConnectionPoolEntry::Connecting(task.clone()));
1055        task
1056    }
1057}
1058
1059#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1060pub enum RemoteConnectionOptions {
1061    Ssh(SshConnectionOptions),
1062    Wsl(WslConnectionOptions),
1063}
1064
1065impl RemoteConnectionOptions {
1066    pub fn display_name(&self) -> String {
1067        match self {
1068            RemoteConnectionOptions::Ssh(opts) => opts.host.clone(),
1069            RemoteConnectionOptions::Wsl(opts) => opts.distro_name.clone(),
1070        }
1071    }
1072}
1073
1074impl From<SshConnectionOptions> for RemoteConnectionOptions {
1075    fn from(opts: SshConnectionOptions) -> Self {
1076        RemoteConnectionOptions::Ssh(opts)
1077    }
1078}
1079
1080impl From<WslConnectionOptions> for RemoteConnectionOptions {
1081    fn from(opts: WslConnectionOptions) -> Self {
1082        RemoteConnectionOptions::Wsl(opts)
1083    }
1084}
1085
1086#[async_trait(?Send)]
1087pub(crate) trait RemoteConnection: Send + Sync {
1088    fn start_proxy(
1089        &self,
1090        unique_identifier: String,
1091        reconnect: bool,
1092        incoming_tx: UnboundedSender<Envelope>,
1093        outgoing_rx: UnboundedReceiver<Envelope>,
1094        connection_activity_tx: Sender<()>,
1095        delegate: Arc<dyn RemoteClientDelegate>,
1096        cx: &mut AsyncApp,
1097    ) -> Task<Result<i32>>;
1098    fn upload_directory(
1099        &self,
1100        src_path: PathBuf,
1101        dest_path: RemotePathBuf,
1102        cx: &App,
1103    ) -> Task<Result<()>>;
1104    async fn kill(&self) -> Result<()>;
1105    fn has_been_killed(&self) -> bool;
1106    fn shares_network_interface(&self) -> bool {
1107        false
1108    }
1109    fn build_command(
1110        &self,
1111        program: Option<String>,
1112        args: &[String],
1113        env: &HashMap<String, String>,
1114        working_dir: Option<String>,
1115        port_forward: Option<(u16, String, u16)>,
1116    ) -> Result<CommandTemplate>;
1117    fn build_forward_ports_command(
1118        &self,
1119        forwards: Vec<(u16, String, u16)>,
1120    ) -> Result<CommandTemplate>;
1121    fn connection_options(&self) -> RemoteConnectionOptions;
1122    fn path_style(&self) -> PathStyle;
1123    fn shell(&self) -> String;
1124    fn default_system_shell(&self) -> String;
1125
1126    #[cfg(any(test, feature = "test-support"))]
1127    fn simulate_disconnect(&self, _: &AsyncApp) {}
1128}
1129
1130type ResponseChannels = Mutex<HashMap<MessageId, oneshot::Sender<(Envelope, oneshot::Sender<()>)>>>;
1131
1132struct Signal<T> {
1133    tx: Mutex<Option<oneshot::Sender<T>>>,
1134    rx: Shared<Task<Option<T>>>,
1135}
1136
1137impl<T: Send + Clone + 'static> Signal<T> {
1138    pub fn new(cx: &App) -> Self {
1139        let (tx, rx) = oneshot::channel();
1140
1141        let task = cx
1142            .background_executor()
1143            .spawn(async move { rx.await.ok() })
1144            .shared();
1145
1146        Self {
1147            tx: Mutex::new(Some(tx)),
1148            rx: task,
1149        }
1150    }
1151
1152    fn set(&self, value: T) {
1153        if let Some(tx) = self.tx.lock().take() {
1154            let _ = tx.send(value);
1155        }
1156    }
1157
1158    fn wait(&self) -> Shared<Task<Option<T>>> {
1159        self.rx.clone()
1160    }
1161}
1162
1163struct ChannelClient {
1164    next_message_id: AtomicU32,
1165    outgoing_tx: Mutex<mpsc::UnboundedSender<Envelope>>,
1166    buffer: Mutex<VecDeque<Envelope>>,
1167    response_channels: ResponseChannels,
1168    message_handlers: Mutex<ProtoMessageHandlerSet>,
1169    max_received: AtomicU32,
1170    name: &'static str,
1171    task: Mutex<Task<Result<()>>>,
1172    remote_started: Signal<()>,
1173}
1174
1175impl ChannelClient {
1176    fn new(
1177        incoming_rx: mpsc::UnboundedReceiver<Envelope>,
1178        outgoing_tx: mpsc::UnboundedSender<Envelope>,
1179        cx: &App,
1180        name: &'static str,
1181    ) -> Arc<Self> {
1182        Arc::new_cyclic(|this| Self {
1183            outgoing_tx: Mutex::new(outgoing_tx),
1184            next_message_id: AtomicU32::new(0),
1185            max_received: AtomicU32::new(0),
1186            response_channels: ResponseChannels::default(),
1187            message_handlers: Default::default(),
1188            buffer: Mutex::new(VecDeque::new()),
1189            name,
1190            task: Mutex::new(Self::start_handling_messages(
1191                this.clone(),
1192                incoming_rx,
1193                &cx.to_async(),
1194            )),
1195            remote_started: Signal::new(cx),
1196        })
1197    }
1198
1199    fn wait_for_remote_started(&self) -> Shared<Task<Option<()>>> {
1200        self.remote_started.wait()
1201    }
1202
1203    fn start_handling_messages(
1204        this: Weak<Self>,
1205        mut incoming_rx: mpsc::UnboundedReceiver<Envelope>,
1206        cx: &AsyncApp,
1207    ) -> Task<Result<()>> {
1208        cx.spawn(async move |cx| {
1209            if let Some(this) = this.upgrade() {
1210                let envelope = proto::RemoteStarted {}.into_envelope(0, None, None);
1211                this.outgoing_tx.lock().unbounded_send(envelope).ok();
1212            };
1213
1214            let peer_id = PeerId { owner_id: 0, id: 0 };
1215            while let Some(incoming) = incoming_rx.next().await {
1216                let Some(this) = this.upgrade() else {
1217                    return anyhow::Ok(());
1218                };
1219                if let Some(ack_id) = incoming.ack_id {
1220                    let mut buffer = this.buffer.lock();
1221                    while buffer.front().is_some_and(|msg| msg.id <= ack_id) {
1222                        buffer.pop_front();
1223                    }
1224                }
1225                if let Some(proto::envelope::Payload::FlushBufferedMessages(_)) = &incoming.payload
1226                {
1227                    log::debug!(
1228                        "{}:ssh message received. name:FlushBufferedMessages",
1229                        this.name
1230                    );
1231                    {
1232                        let buffer = this.buffer.lock();
1233                        for envelope in buffer.iter() {
1234                            this.outgoing_tx
1235                                .lock()
1236                                .unbounded_send(envelope.clone())
1237                                .ok();
1238                        }
1239                    }
1240                    let mut envelope = proto::Ack {}.into_envelope(0, Some(incoming.id), None);
1241                    envelope.id = this.next_message_id.fetch_add(1, SeqCst);
1242                    this.outgoing_tx.lock().unbounded_send(envelope).ok();
1243                    continue;
1244                }
1245
1246                if let Some(proto::envelope::Payload::RemoteStarted(_)) = &incoming.payload {
1247                    this.remote_started.set(());
1248                    let mut envelope = proto::Ack {}.into_envelope(0, Some(incoming.id), None);
1249                    envelope.id = this.next_message_id.fetch_add(1, SeqCst);
1250                    this.outgoing_tx.lock().unbounded_send(envelope).ok();
1251                    continue;
1252                }
1253
1254                this.max_received.store(incoming.id, SeqCst);
1255
1256                if let Some(request_id) = incoming.responding_to {
1257                    let request_id = MessageId(request_id);
1258                    let sender = this.response_channels.lock().remove(&request_id);
1259                    if let Some(sender) = sender {
1260                        let (tx, rx) = oneshot::channel();
1261                        if incoming.payload.is_some() {
1262                            sender.send((incoming, tx)).ok();
1263                        }
1264                        rx.await.ok();
1265                    }
1266                } else if let Some(envelope) =
1267                    build_typed_envelope(peer_id, Instant::now(), incoming)
1268                {
1269                    let type_name = envelope.payload_type_name();
1270                    let message_id = envelope.message_id();
1271                    if let Some(future) = ProtoMessageHandlerSet::handle_message(
1272                        &this.message_handlers,
1273                        envelope,
1274                        this.clone().into(),
1275                        cx.clone(),
1276                    ) {
1277                        log::debug!("{}:ssh message received. name:{type_name}", this.name);
1278                        cx.foreground_executor()
1279                            .spawn(async move {
1280                                match future.await {
1281                                    Ok(_) => {
1282                                        log::debug!(
1283                                            "{}:ssh message handled. name:{type_name}",
1284                                            this.name
1285                                        );
1286                                    }
1287                                    Err(error) => {
1288                                        log::error!(
1289                                            "{}:error handling message. type:{}, error:{:#}",
1290                                            this.name,
1291                                            type_name,
1292                                            format!("{error:#}").lines().fold(
1293                                                String::new(),
1294                                                |mut message, line| {
1295                                                    if !message.is_empty() {
1296                                                        message.push(' ');
1297                                                    }
1298                                                    message.push_str(line);
1299                                                    message
1300                                                }
1301                                            )
1302                                        );
1303                                    }
1304                                }
1305                            })
1306                            .detach()
1307                    } else {
1308                        log::error!("{}:unhandled ssh message name:{type_name}", this.name);
1309                        if let Err(e) = AnyProtoClient::from(this.clone()).send_response(
1310                            message_id,
1311                            anyhow::anyhow!("no handler registered for {type_name}").to_proto(),
1312                        ) {
1313                            log::error!(
1314                                "{}:error sending error response for {type_name}:{e:#}",
1315                                this.name
1316                            );
1317                        }
1318                    }
1319                }
1320            }
1321            anyhow::Ok(())
1322        })
1323    }
1324
1325    fn reconnect(
1326        self: &Arc<Self>,
1327        incoming_rx: UnboundedReceiver<Envelope>,
1328        outgoing_tx: UnboundedSender<Envelope>,
1329        cx: &AsyncApp,
1330    ) {
1331        *self.outgoing_tx.lock() = outgoing_tx;
1332        *self.task.lock() = Self::start_handling_messages(Arc::downgrade(self), incoming_rx, cx);
1333    }
1334
1335    fn request<T: RequestMessage>(
1336        &self,
1337        payload: T,
1338    ) -> impl 'static + Future<Output = Result<T::Response>> {
1339        self.request_internal(payload, true)
1340    }
1341
1342    fn request_internal<T: RequestMessage>(
1343        &self,
1344        payload: T,
1345        use_buffer: bool,
1346    ) -> impl 'static + Future<Output = Result<T::Response>> {
1347        log::debug!("ssh request start. name:{}", T::NAME);
1348        let response =
1349            self.request_dynamic(payload.into_envelope(0, None, None), T::NAME, use_buffer);
1350        async move {
1351            let response = response.await?;
1352            log::debug!("ssh request finish. name:{}", T::NAME);
1353            T::Response::from_envelope(response).context("received a response of the wrong type")
1354        }
1355    }
1356
1357    async fn resync(&self, timeout: Duration) -> Result<()> {
1358        smol::future::or(
1359            async {
1360                self.request_internal(proto::FlushBufferedMessages {}, false)
1361                    .await?;
1362
1363                for envelope in self.buffer.lock().iter() {
1364                    self.outgoing_tx
1365                        .lock()
1366                        .unbounded_send(envelope.clone())
1367                        .ok();
1368                }
1369                Ok(())
1370            },
1371            async {
1372                smol::Timer::after(timeout).await;
1373                anyhow::bail!("Timed out resyncing remote client")
1374            },
1375        )
1376        .await
1377    }
1378
1379    async fn ping(&self, timeout: Duration) -> Result<()> {
1380        smol::future::or(
1381            async {
1382                self.request(proto::Ping {}).await?;
1383                Ok(())
1384            },
1385            async {
1386                smol::Timer::after(timeout).await;
1387                anyhow::bail!("Timed out pinging remote client")
1388            },
1389        )
1390        .await
1391    }
1392
1393    fn send<T: EnvelopedMessage>(&self, payload: T) -> Result<()> {
1394        log::debug!("ssh send name:{}", T::NAME);
1395        self.send_dynamic(payload.into_envelope(0, None, None))
1396    }
1397
1398    fn request_dynamic(
1399        &self,
1400        mut envelope: proto::Envelope,
1401        type_name: &'static str,
1402        use_buffer: bool,
1403    ) -> impl 'static + Future<Output = Result<proto::Envelope>> {
1404        envelope.id = self.next_message_id.fetch_add(1, SeqCst);
1405        let (tx, rx) = oneshot::channel();
1406        let mut response_channels_lock = self.response_channels.lock();
1407        response_channels_lock.insert(MessageId(envelope.id), tx);
1408        drop(response_channels_lock);
1409
1410        let result = if use_buffer {
1411            self.send_buffered(envelope)
1412        } else {
1413            self.send_unbuffered(envelope)
1414        };
1415        async move {
1416            if let Err(error) = &result {
1417                log::error!("failed to send message: {error}");
1418                anyhow::bail!("failed to send message: {error}");
1419            }
1420
1421            let response = rx.await.context("connection lost")?.0;
1422            if let Some(proto::envelope::Payload::Error(error)) = &response.payload {
1423                return Err(RpcError::from_proto(error, type_name));
1424            }
1425            Ok(response)
1426        }
1427    }
1428
1429    pub fn send_dynamic(&self, mut envelope: proto::Envelope) -> Result<()> {
1430        envelope.id = self.next_message_id.fetch_add(1, SeqCst);
1431        self.send_buffered(envelope)
1432    }
1433
1434    fn send_buffered(&self, mut envelope: proto::Envelope) -> Result<()> {
1435        envelope.ack_id = Some(self.max_received.load(SeqCst));
1436        self.buffer.lock().push_back(envelope.clone());
1437        // ignore errors on send (happen while we're reconnecting)
1438        // assume that the global "disconnected" overlay is sufficient.
1439        self.outgoing_tx.lock().unbounded_send(envelope).ok();
1440        Ok(())
1441    }
1442
1443    fn send_unbuffered(&self, mut envelope: proto::Envelope) -> Result<()> {
1444        envelope.ack_id = Some(self.max_received.load(SeqCst));
1445        self.outgoing_tx.lock().unbounded_send(envelope).ok();
1446        Ok(())
1447    }
1448}
1449
1450impl ProtoClient for ChannelClient {
1451    fn request(
1452        &self,
1453        envelope: proto::Envelope,
1454        request_type: &'static str,
1455    ) -> BoxFuture<'static, Result<proto::Envelope>> {
1456        self.request_dynamic(envelope, request_type, true).boxed()
1457    }
1458
1459    fn send(&self, envelope: proto::Envelope, _message_type: &'static str) -> Result<()> {
1460        self.send_dynamic(envelope)
1461    }
1462
1463    fn send_response(&self, envelope: Envelope, _message_type: &'static str) -> anyhow::Result<()> {
1464        self.send_dynamic(envelope)
1465    }
1466
1467    fn message_handler_set(&self) -> &Mutex<ProtoMessageHandlerSet> {
1468        &self.message_handlers
1469    }
1470
1471    fn is_via_collab(&self) -> bool {
1472        false
1473    }
1474}
1475
1476#[cfg(any(test, feature = "test-support"))]
1477mod fake {
1478    use super::{ChannelClient, RemoteClientDelegate, RemoteConnection, RemotePlatform};
1479    use crate::remote_client::{CommandTemplate, RemoteConnectionOptions};
1480    use anyhow::Result;
1481    use askpass::EncryptedPassword;
1482    use async_trait::async_trait;
1483    use collections::HashMap;
1484    use futures::{
1485        FutureExt, SinkExt, StreamExt,
1486        channel::{
1487            mpsc::{self, Sender},
1488            oneshot,
1489        },
1490        select_biased,
1491    };
1492    use gpui::{App, AppContext as _, AsyncApp, SemanticVersion, Task, TestAppContext};
1493    use release_channel::ReleaseChannel;
1494    use rpc::proto::Envelope;
1495    use std::{path::PathBuf, sync::Arc};
1496    use util::paths::{PathStyle, RemotePathBuf};
1497
1498    pub(super) struct FakeRemoteConnection {
1499        pub(super) connection_options: RemoteConnectionOptions,
1500        pub(super) server_channel: Arc<ChannelClient>,
1501        pub(super) server_cx: SendableCx,
1502    }
1503
1504    pub(super) struct SendableCx(AsyncApp);
1505    impl SendableCx {
1506        // SAFETY: When run in test mode, GPUI is always single threaded.
1507        pub(super) fn new(cx: &TestAppContext) -> Self {
1508            Self(cx.to_async())
1509        }
1510
1511        // SAFETY: Enforce that we're on the main thread by requiring a valid AsyncApp
1512        fn get(&self, _: &AsyncApp) -> AsyncApp {
1513            self.0.clone()
1514        }
1515    }
1516
1517    // SAFETY: There is no way to access a SendableCx from a different thread, see [`SendableCx::new`] and [`SendableCx::get`]
1518    unsafe impl Send for SendableCx {}
1519    unsafe impl Sync for SendableCx {}
1520
1521    #[async_trait(?Send)]
1522    impl RemoteConnection for FakeRemoteConnection {
1523        async fn kill(&self) -> Result<()> {
1524            Ok(())
1525        }
1526
1527        fn has_been_killed(&self) -> bool {
1528            false
1529        }
1530
1531        fn build_command(
1532            &self,
1533            program: Option<String>,
1534            args: &[String],
1535            env: &HashMap<String, String>,
1536            _: Option<String>,
1537            _: Option<(u16, String, u16)>,
1538        ) -> Result<CommandTemplate> {
1539            let ssh_program = program.unwrap_or_else(|| "sh".to_string());
1540            let mut ssh_args = Vec::new();
1541            ssh_args.push(ssh_program);
1542            ssh_args.extend(args.iter().cloned());
1543            Ok(CommandTemplate {
1544                program: "ssh".into(),
1545                args: ssh_args,
1546                env: env.clone(),
1547            })
1548        }
1549
1550        fn build_forward_ports_command(
1551            &self,
1552            forwards: Vec<(u16, String, u16)>,
1553        ) -> anyhow::Result<CommandTemplate> {
1554            Ok(CommandTemplate {
1555                program: "ssh".into(),
1556                args: std::iter::once("-N".to_owned())
1557                    .chain(forwards.into_iter().map(|(local_port, host, remote_port)| {
1558                        format!("{local_port}:{host}:{remote_port}")
1559                    }))
1560                    .collect(),
1561                env: Default::default(),
1562            })
1563        }
1564
1565        fn upload_directory(
1566            &self,
1567            _src_path: PathBuf,
1568            _dest_path: RemotePathBuf,
1569            _cx: &App,
1570        ) -> Task<Result<()>> {
1571            unreachable!()
1572        }
1573
1574        fn connection_options(&self) -> RemoteConnectionOptions {
1575            self.connection_options.clone()
1576        }
1577
1578        fn simulate_disconnect(&self, cx: &AsyncApp) {
1579            let (outgoing_tx, _) = mpsc::unbounded::<Envelope>();
1580            let (_, incoming_rx) = mpsc::unbounded::<Envelope>();
1581            self.server_channel
1582                .reconnect(incoming_rx, outgoing_tx, &self.server_cx.get(cx));
1583        }
1584
1585        fn start_proxy(
1586            &self,
1587            _unique_identifier: String,
1588            _reconnect: bool,
1589            mut client_incoming_tx: mpsc::UnboundedSender<Envelope>,
1590            mut client_outgoing_rx: mpsc::UnboundedReceiver<Envelope>,
1591            mut connection_activity_tx: Sender<()>,
1592            _delegate: Arc<dyn RemoteClientDelegate>,
1593            cx: &mut AsyncApp,
1594        ) -> Task<Result<i32>> {
1595            let (mut server_incoming_tx, server_incoming_rx) = mpsc::unbounded::<Envelope>();
1596            let (server_outgoing_tx, mut server_outgoing_rx) = mpsc::unbounded::<Envelope>();
1597
1598            self.server_channel.reconnect(
1599                server_incoming_rx,
1600                server_outgoing_tx,
1601                &self.server_cx.get(cx),
1602            );
1603
1604            cx.background_spawn(async move {
1605                loop {
1606                    select_biased! {
1607                        server_to_client = server_outgoing_rx.next().fuse() => {
1608                            let Some(server_to_client) = server_to_client else {
1609                                return Ok(1)
1610                            };
1611                            connection_activity_tx.try_send(()).ok();
1612                            client_incoming_tx.send(server_to_client).await.ok();
1613                        }
1614                        client_to_server = client_outgoing_rx.next().fuse() => {
1615                            let Some(client_to_server) = client_to_server else {
1616                                return Ok(1)
1617                            };
1618                            server_incoming_tx.send(client_to_server).await.ok();
1619                        }
1620                    }
1621                }
1622            })
1623        }
1624
1625        fn path_style(&self) -> PathStyle {
1626            PathStyle::local()
1627        }
1628
1629        fn shell(&self) -> String {
1630            "sh".to_owned()
1631        }
1632
1633        fn default_system_shell(&self) -> String {
1634            "sh".to_owned()
1635        }
1636    }
1637
1638    pub(super) struct Delegate;
1639
1640    impl RemoteClientDelegate for Delegate {
1641        fn ask_password(&self, _: String, _: oneshot::Sender<EncryptedPassword>, _: &mut AsyncApp) {
1642            unreachable!()
1643        }
1644
1645        fn download_server_binary_locally(
1646            &self,
1647            _: RemotePlatform,
1648            _: ReleaseChannel,
1649            _: Option<SemanticVersion>,
1650            _: &mut AsyncApp,
1651        ) -> Task<Result<PathBuf>> {
1652            unreachable!()
1653        }
1654
1655        fn get_download_params(
1656            &self,
1657            _platform: RemotePlatform,
1658            _release_channel: ReleaseChannel,
1659            _version: Option<SemanticVersion>,
1660            _cx: &mut AsyncApp,
1661        ) -> Task<Result<Option<(String, String)>>> {
1662            unreachable!()
1663        }
1664
1665        fn set_status(&self, _: Option<&str>, _: &mut AsyncApp) {}
1666    }
1667}