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