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, 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, 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 upload_directory(
 840        &self,
 841        src_path: PathBuf,
 842        dest_path: RemotePathBuf,
 843        cx: &App,
 844    ) -> Task<Result<()>> {
 845        let Some(connection) = self.remote_connection() else {
 846            return Task::ready(Err(anyhow!("no ssh connection")));
 847        };
 848        connection.upload_directory(src_path, dest_path, cx)
 849    }
 850
 851    pub fn proto_client(&self) -> AnyProtoClient {
 852        self.client.clone().into()
 853    }
 854
 855    pub fn connection_options(&self) -> RemoteConnectionOptions {
 856        self.connection_options.clone()
 857    }
 858
 859    pub fn connection_state(&self) -> ConnectionState {
 860        self.state
 861            .as_ref()
 862            .map(ConnectionState::from)
 863            .unwrap_or(ConnectionState::Disconnected)
 864    }
 865
 866    pub fn is_disconnected(&self) -> bool {
 867        self.connection_state() == ConnectionState::Disconnected
 868    }
 869
 870    pub fn path_style(&self) -> PathStyle {
 871        self.path_style
 872    }
 873
 874    #[cfg(any(test, feature = "test-support"))]
 875    pub fn simulate_disconnect(&self, client_cx: &mut App) -> Task<()> {
 876        let opts = self.connection_options();
 877        client_cx.spawn(async move |cx| {
 878            let connection = cx
 879                .update_global(|c: &mut ConnectionPool, _| {
 880                    if let Some(ConnectionPoolEntry::Connecting(c)) = c.connections.get(&opts) {
 881                        c.clone()
 882                    } else {
 883                        panic!("missing test connection")
 884                    }
 885                })
 886                .unwrap()
 887                .await
 888                .unwrap();
 889
 890            connection.simulate_disconnect(cx);
 891        })
 892    }
 893
 894    #[cfg(any(test, feature = "test-support"))]
 895    pub fn fake_server(
 896        client_cx: &mut gpui::TestAppContext,
 897        server_cx: &mut gpui::TestAppContext,
 898    ) -> (RemoteConnectionOptions, AnyProtoClient) {
 899        let port = client_cx
 900            .update(|cx| cx.default_global::<ConnectionPool>().connections.len() as u16 + 1);
 901        let opts = RemoteConnectionOptions::Ssh(SshConnectionOptions {
 902            host: "<fake>".to_string(),
 903            port: Some(port),
 904            ..Default::default()
 905        });
 906        let (outgoing_tx, _) = mpsc::unbounded::<Envelope>();
 907        let (_, incoming_rx) = mpsc::unbounded::<Envelope>();
 908        let server_client =
 909            server_cx.update(|cx| ChannelClient::new(incoming_rx, outgoing_tx, cx, "fake-server"));
 910        let connection: Arc<dyn RemoteConnection> = Arc::new(fake::FakeRemoteConnection {
 911            connection_options: opts.clone(),
 912            server_cx: fake::SendableCx::new(server_cx),
 913            server_channel: server_client.clone(),
 914        });
 915
 916        client_cx.update(|cx| {
 917            cx.update_default_global(|c: &mut ConnectionPool, cx| {
 918                c.connections.insert(
 919                    opts.clone(),
 920                    ConnectionPoolEntry::Connecting(
 921                        cx.background_spawn({
 922                            let connection = connection.clone();
 923                            async move { Ok(connection.clone()) }
 924                        })
 925                        .shared(),
 926                    ),
 927                );
 928            })
 929        });
 930
 931        (opts, server_client.into())
 932    }
 933
 934    #[cfg(any(test, feature = "test-support"))]
 935    pub async fn fake_client(
 936        opts: RemoteConnectionOptions,
 937        client_cx: &mut gpui::TestAppContext,
 938    ) -> Entity<Self> {
 939        let (_tx, rx) = oneshot::channel();
 940        client_cx
 941            .update(|cx| {
 942                Self::new(
 943                    ConnectionIdentifier::setup(),
 944                    opts,
 945                    rx,
 946                    Arc::new(fake::Delegate),
 947                    cx,
 948                )
 949            })
 950            .await
 951            .unwrap()
 952            .unwrap()
 953    }
 954
 955    fn remote_connection(&self) -> Option<Arc<dyn RemoteConnection>> {
 956        self.state
 957            .as_ref()
 958            .and_then(|state| state.remote_connection())
 959    }
 960}
 961
 962enum ConnectionPoolEntry {
 963    Connecting(Shared<Task<Result<Arc<dyn RemoteConnection>, Arc<anyhow::Error>>>>),
 964    Connected(Weak<dyn RemoteConnection>),
 965}
 966
 967#[derive(Default)]
 968struct ConnectionPool {
 969    connections: HashMap<RemoteConnectionOptions, ConnectionPoolEntry>,
 970}
 971
 972impl Global for ConnectionPool {}
 973
 974impl ConnectionPool {
 975    pub fn connect(
 976        &mut self,
 977        opts: RemoteConnectionOptions,
 978        delegate: &Arc<dyn RemoteClientDelegate>,
 979        cx: &mut App,
 980    ) -> Shared<Task<Result<Arc<dyn RemoteConnection>, Arc<anyhow::Error>>>> {
 981        let connection = self.connections.get(&opts);
 982        match connection {
 983            Some(ConnectionPoolEntry::Connecting(task)) => {
 984                let delegate = delegate.clone();
 985                cx.spawn(async move |cx| {
 986                    delegate.set_status(Some("Waiting for existing connection attempt"), cx);
 987                })
 988                .detach();
 989                return task.clone();
 990            }
 991            Some(ConnectionPoolEntry::Connected(ssh)) => {
 992                if let Some(ssh) = ssh.upgrade()
 993                    && !ssh.has_been_killed()
 994                {
 995                    return Task::ready(Ok(ssh)).shared();
 996                }
 997                self.connections.remove(&opts);
 998            }
 999            None => {}
1000        }
1001
1002        let task = cx
1003            .spawn({
1004                let opts = opts.clone();
1005                let delegate = delegate.clone();
1006                async move |cx| {
1007                    let connection = match opts.clone() {
1008                        RemoteConnectionOptions::Ssh(opts) => {
1009                            SshRemoteConnection::new(opts, delegate, cx)
1010                                .await
1011                                .map(|connection| Arc::new(connection) as Arc<dyn RemoteConnection>)
1012                        }
1013                        RemoteConnectionOptions::Wsl(opts) => {
1014                            WslRemoteConnection::new(opts, delegate, cx)
1015                                .await
1016                                .map(|connection| Arc::new(connection) as Arc<dyn RemoteConnection>)
1017                        }
1018                    };
1019
1020                    cx.update_global(|pool: &mut Self, _| {
1021                        debug_assert!(matches!(
1022                            pool.connections.get(&opts),
1023                            Some(ConnectionPoolEntry::Connecting(_))
1024                        ));
1025                        match connection {
1026                            Ok(connection) => {
1027                                pool.connections.insert(
1028                                    opts.clone(),
1029                                    ConnectionPoolEntry::Connected(Arc::downgrade(&connection)),
1030                                );
1031                                Ok(connection)
1032                            }
1033                            Err(error) => {
1034                                pool.connections.remove(&opts);
1035                                Err(Arc::new(error))
1036                            }
1037                        }
1038                    })?
1039                }
1040            })
1041            .shared();
1042
1043        self.connections
1044            .insert(opts.clone(), ConnectionPoolEntry::Connecting(task.clone()));
1045        task
1046    }
1047}
1048
1049#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1050pub enum RemoteConnectionOptions {
1051    Ssh(SshConnectionOptions),
1052    Wsl(WslConnectionOptions),
1053}
1054
1055impl RemoteConnectionOptions {
1056    pub fn display_name(&self) -> String {
1057        match self {
1058            RemoteConnectionOptions::Ssh(opts) => opts.host.clone(),
1059            RemoteConnectionOptions::Wsl(opts) => opts.distro_name.clone(),
1060        }
1061    }
1062}
1063
1064impl From<SshConnectionOptions> for RemoteConnectionOptions {
1065    fn from(opts: SshConnectionOptions) -> Self {
1066        RemoteConnectionOptions::Ssh(opts)
1067    }
1068}
1069
1070impl From<WslConnectionOptions> for RemoteConnectionOptions {
1071    fn from(opts: WslConnectionOptions) -> Self {
1072        RemoteConnectionOptions::Wsl(opts)
1073    }
1074}
1075
1076#[async_trait(?Send)]
1077pub(crate) trait RemoteConnection: Send + Sync {
1078    fn start_proxy(
1079        &self,
1080        unique_identifier: String,
1081        reconnect: bool,
1082        incoming_tx: UnboundedSender<Envelope>,
1083        outgoing_rx: UnboundedReceiver<Envelope>,
1084        connection_activity_tx: Sender<()>,
1085        delegate: Arc<dyn RemoteClientDelegate>,
1086        cx: &mut AsyncApp,
1087    ) -> Task<Result<i32>>;
1088    fn upload_directory(
1089        &self,
1090        src_path: PathBuf,
1091        dest_path: RemotePathBuf,
1092        cx: &App,
1093    ) -> Task<Result<()>>;
1094    async fn kill(&self) -> Result<()>;
1095    fn has_been_killed(&self) -> bool;
1096    fn shares_network_interface(&self) -> bool {
1097        false
1098    }
1099    fn build_command(
1100        &self,
1101        program: Option<String>,
1102        args: &[String],
1103        env: &HashMap<String, String>,
1104        working_dir: Option<String>,
1105        port_forward: Option<(u16, String, u16)>,
1106    ) -> Result<CommandTemplate>;
1107    fn connection_options(&self) -> RemoteConnectionOptions;
1108    fn path_style(&self) -> PathStyle;
1109    fn shell(&self) -> String;
1110    fn default_system_shell(&self) -> String;
1111
1112    #[cfg(any(test, feature = "test-support"))]
1113    fn simulate_disconnect(&self, _: &AsyncApp) {}
1114}
1115
1116type ResponseChannels = Mutex<HashMap<MessageId, oneshot::Sender<(Envelope, oneshot::Sender<()>)>>>;
1117
1118struct Signal<T> {
1119    tx: Mutex<Option<oneshot::Sender<T>>>,
1120    rx: Shared<Task<Option<T>>>,
1121}
1122
1123impl<T: Send + Clone + 'static> Signal<T> {
1124    pub fn new(cx: &App) -> Self {
1125        let (tx, rx) = oneshot::channel();
1126
1127        let task = cx
1128            .background_executor()
1129            .spawn(async move { rx.await.ok() })
1130            .shared();
1131
1132        Self {
1133            tx: Mutex::new(Some(tx)),
1134            rx: task,
1135        }
1136    }
1137
1138    fn set(&self, value: T) {
1139        if let Some(tx) = self.tx.lock().take() {
1140            let _ = tx.send(value);
1141        }
1142    }
1143
1144    fn wait(&self) -> Shared<Task<Option<T>>> {
1145        self.rx.clone()
1146    }
1147}
1148
1149struct ChannelClient {
1150    next_message_id: AtomicU32,
1151    outgoing_tx: Mutex<mpsc::UnboundedSender<Envelope>>,
1152    buffer: Mutex<VecDeque<Envelope>>,
1153    response_channels: ResponseChannels,
1154    message_handlers: Mutex<ProtoMessageHandlerSet>,
1155    max_received: AtomicU32,
1156    name: &'static str,
1157    task: Mutex<Task<Result<()>>>,
1158    remote_started: Signal<()>,
1159}
1160
1161impl ChannelClient {
1162    fn new(
1163        incoming_rx: mpsc::UnboundedReceiver<Envelope>,
1164        outgoing_tx: mpsc::UnboundedSender<Envelope>,
1165        cx: &App,
1166        name: &'static str,
1167    ) -> Arc<Self> {
1168        Arc::new_cyclic(|this| Self {
1169            outgoing_tx: Mutex::new(outgoing_tx),
1170            next_message_id: AtomicU32::new(0),
1171            max_received: AtomicU32::new(0),
1172            response_channels: ResponseChannels::default(),
1173            message_handlers: Default::default(),
1174            buffer: Mutex::new(VecDeque::new()),
1175            name,
1176            task: Mutex::new(Self::start_handling_messages(
1177                this.clone(),
1178                incoming_rx,
1179                &cx.to_async(),
1180            )),
1181            remote_started: Signal::new(cx),
1182        })
1183    }
1184
1185    fn wait_for_remote_started(&self) -> Shared<Task<Option<()>>> {
1186        self.remote_started.wait()
1187    }
1188
1189    fn start_handling_messages(
1190        this: Weak<Self>,
1191        mut incoming_rx: mpsc::UnboundedReceiver<Envelope>,
1192        cx: &AsyncApp,
1193    ) -> Task<Result<()>> {
1194        cx.spawn(async move |cx| {
1195            if let Some(this) = this.upgrade() {
1196                let envelope = proto::RemoteStarted {}.into_envelope(0, None, None);
1197                this.outgoing_tx.lock().unbounded_send(envelope).ok();
1198            };
1199
1200            let peer_id = PeerId { owner_id: 0, id: 0 };
1201            while let Some(incoming) = incoming_rx.next().await {
1202                let Some(this) = this.upgrade() else {
1203                    return anyhow::Ok(());
1204                };
1205                if let Some(ack_id) = incoming.ack_id {
1206                    let mut buffer = this.buffer.lock();
1207                    while buffer.front().is_some_and(|msg| msg.id <= ack_id) {
1208                        buffer.pop_front();
1209                    }
1210                }
1211                if let Some(proto::envelope::Payload::FlushBufferedMessages(_)) = &incoming.payload
1212                {
1213                    log::debug!(
1214                        "{}:ssh message received. name:FlushBufferedMessages",
1215                        this.name
1216                    );
1217                    {
1218                        let buffer = this.buffer.lock();
1219                        for envelope in buffer.iter() {
1220                            this.outgoing_tx
1221                                .lock()
1222                                .unbounded_send(envelope.clone())
1223                                .ok();
1224                        }
1225                    }
1226                    let mut envelope = proto::Ack {}.into_envelope(0, Some(incoming.id), None);
1227                    envelope.id = this.next_message_id.fetch_add(1, SeqCst);
1228                    this.outgoing_tx.lock().unbounded_send(envelope).ok();
1229                    continue;
1230                }
1231
1232                if let Some(proto::envelope::Payload::RemoteStarted(_)) = &incoming.payload {
1233                    this.remote_started.set(());
1234                    let mut envelope = proto::Ack {}.into_envelope(0, Some(incoming.id), None);
1235                    envelope.id = this.next_message_id.fetch_add(1, SeqCst);
1236                    this.outgoing_tx.lock().unbounded_send(envelope).ok();
1237                    continue;
1238                }
1239
1240                this.max_received.store(incoming.id, SeqCst);
1241
1242                if let Some(request_id) = incoming.responding_to {
1243                    let request_id = MessageId(request_id);
1244                    let sender = this.response_channels.lock().remove(&request_id);
1245                    if let Some(sender) = sender {
1246                        let (tx, rx) = oneshot::channel();
1247                        if incoming.payload.is_some() {
1248                            sender.send((incoming, tx)).ok();
1249                        }
1250                        rx.await.ok();
1251                    }
1252                } else if let Some(envelope) =
1253                    build_typed_envelope(peer_id, Instant::now(), incoming)
1254                {
1255                    let type_name = envelope.payload_type_name();
1256                    let message_id = envelope.message_id();
1257                    if let Some(future) = ProtoMessageHandlerSet::handle_message(
1258                        &this.message_handlers,
1259                        envelope,
1260                        this.clone().into(),
1261                        cx.clone(),
1262                    ) {
1263                        log::debug!("{}:ssh message received. name:{type_name}", this.name);
1264                        cx.foreground_executor()
1265                            .spawn(async move {
1266                                match future.await {
1267                                    Ok(_) => {
1268                                        log::debug!(
1269                                            "{}:ssh message handled. name:{type_name}",
1270                                            this.name
1271                                        );
1272                                    }
1273                                    Err(error) => {
1274                                        log::error!(
1275                                            "{}:error handling message. type:{}, error:{:#}",
1276                                            this.name,
1277                                            type_name,
1278                                            format!("{error:#}").lines().fold(
1279                                                String::new(),
1280                                                |mut message, line| {
1281                                                    if !message.is_empty() {
1282                                                        message.push(' ');
1283                                                    }
1284                                                    message.push_str(line);
1285                                                    message
1286                                                }
1287                                            )
1288                                        );
1289                                    }
1290                                }
1291                            })
1292                            .detach()
1293                    } else {
1294                        log::error!("{}:unhandled ssh message name:{type_name}", this.name);
1295                        if let Err(e) = AnyProtoClient::from(this.clone()).send_response(
1296                            message_id,
1297                            anyhow::anyhow!("no handler registered for {type_name}").to_proto(),
1298                        ) {
1299                            log::error!(
1300                                "{}:error sending error response for {type_name}:{e:#}",
1301                                this.name
1302                            );
1303                        }
1304                    }
1305                }
1306            }
1307            anyhow::Ok(())
1308        })
1309    }
1310
1311    fn reconnect(
1312        self: &Arc<Self>,
1313        incoming_rx: UnboundedReceiver<Envelope>,
1314        outgoing_tx: UnboundedSender<Envelope>,
1315        cx: &AsyncApp,
1316    ) {
1317        *self.outgoing_tx.lock() = outgoing_tx;
1318        *self.task.lock() = Self::start_handling_messages(Arc::downgrade(self), incoming_rx, cx);
1319    }
1320
1321    fn request<T: RequestMessage>(
1322        &self,
1323        payload: T,
1324    ) -> impl 'static + Future<Output = Result<T::Response>> {
1325        self.request_internal(payload, true)
1326    }
1327
1328    fn request_internal<T: RequestMessage>(
1329        &self,
1330        payload: T,
1331        use_buffer: bool,
1332    ) -> impl 'static + Future<Output = Result<T::Response>> {
1333        log::debug!("ssh request start. name:{}", T::NAME);
1334        let response =
1335            self.request_dynamic(payload.into_envelope(0, None, None), T::NAME, use_buffer);
1336        async move {
1337            let response = response.await?;
1338            log::debug!("ssh request finish. name:{}", T::NAME);
1339            T::Response::from_envelope(response).context("received a response of the wrong type")
1340        }
1341    }
1342
1343    async fn resync(&self, timeout: Duration) -> Result<()> {
1344        smol::future::or(
1345            async {
1346                self.request_internal(proto::FlushBufferedMessages {}, false)
1347                    .await?;
1348
1349                for envelope in self.buffer.lock().iter() {
1350                    self.outgoing_tx
1351                        .lock()
1352                        .unbounded_send(envelope.clone())
1353                        .ok();
1354                }
1355                Ok(())
1356            },
1357            async {
1358                smol::Timer::after(timeout).await;
1359                anyhow::bail!("Timed out resyncing remote client")
1360            },
1361        )
1362        .await
1363    }
1364
1365    async fn ping(&self, timeout: Duration) -> Result<()> {
1366        smol::future::or(
1367            async {
1368                self.request(proto::Ping {}).await?;
1369                Ok(())
1370            },
1371            async {
1372                smol::Timer::after(timeout).await;
1373                anyhow::bail!("Timed out pinging remote client")
1374            },
1375        )
1376        .await
1377    }
1378
1379    fn send<T: EnvelopedMessage>(&self, payload: T) -> Result<()> {
1380        log::debug!("ssh send name:{}", T::NAME);
1381        self.send_dynamic(payload.into_envelope(0, None, None))
1382    }
1383
1384    fn request_dynamic(
1385        &self,
1386        mut envelope: proto::Envelope,
1387        type_name: &'static str,
1388        use_buffer: bool,
1389    ) -> impl 'static + Future<Output = Result<proto::Envelope>> {
1390        envelope.id = self.next_message_id.fetch_add(1, SeqCst);
1391        let (tx, rx) = oneshot::channel();
1392        let mut response_channels_lock = self.response_channels.lock();
1393        response_channels_lock.insert(MessageId(envelope.id), tx);
1394        drop(response_channels_lock);
1395
1396        let result = if use_buffer {
1397            self.send_buffered(envelope)
1398        } else {
1399            self.send_unbuffered(envelope)
1400        };
1401        async move {
1402            if let Err(error) = &result {
1403                log::error!("failed to send message: {error}");
1404                anyhow::bail!("failed to send message: {error}");
1405            }
1406
1407            let response = rx.await.context("connection lost")?.0;
1408            if let Some(proto::envelope::Payload::Error(error)) = &response.payload {
1409                return Err(RpcError::from_proto(error, type_name));
1410            }
1411            Ok(response)
1412        }
1413    }
1414
1415    pub fn send_dynamic(&self, mut envelope: proto::Envelope) -> Result<()> {
1416        envelope.id = self.next_message_id.fetch_add(1, SeqCst);
1417        self.send_buffered(envelope)
1418    }
1419
1420    fn send_buffered(&self, mut envelope: proto::Envelope) -> Result<()> {
1421        envelope.ack_id = Some(self.max_received.load(SeqCst));
1422        self.buffer.lock().push_back(envelope.clone());
1423        // ignore errors on send (happen while we're reconnecting)
1424        // assume that the global "disconnected" overlay is sufficient.
1425        self.outgoing_tx.lock().unbounded_send(envelope).ok();
1426        Ok(())
1427    }
1428
1429    fn send_unbuffered(&self, mut envelope: proto::Envelope) -> Result<()> {
1430        envelope.ack_id = Some(self.max_received.load(SeqCst));
1431        self.outgoing_tx.lock().unbounded_send(envelope).ok();
1432        Ok(())
1433    }
1434}
1435
1436impl ProtoClient for ChannelClient {
1437    fn request(
1438        &self,
1439        envelope: proto::Envelope,
1440        request_type: &'static str,
1441    ) -> BoxFuture<'static, Result<proto::Envelope>> {
1442        self.request_dynamic(envelope, request_type, true).boxed()
1443    }
1444
1445    fn send(&self, envelope: proto::Envelope, _message_type: &'static str) -> Result<()> {
1446        self.send_dynamic(envelope)
1447    }
1448
1449    fn send_response(&self, envelope: Envelope, _message_type: &'static str) -> anyhow::Result<()> {
1450        self.send_dynamic(envelope)
1451    }
1452
1453    fn message_handler_set(&self) -> &Mutex<ProtoMessageHandlerSet> {
1454        &self.message_handlers
1455    }
1456
1457    fn is_via_collab(&self) -> bool {
1458        false
1459    }
1460}
1461
1462#[cfg(any(test, feature = "test-support"))]
1463mod fake {
1464    use super::{ChannelClient, RemoteClientDelegate, RemoteConnection, RemotePlatform};
1465    use crate::remote_client::{CommandTemplate, RemoteConnectionOptions};
1466    use anyhow::Result;
1467    use askpass::EncryptedPassword;
1468    use async_trait::async_trait;
1469    use collections::HashMap;
1470    use futures::{
1471        FutureExt, SinkExt, StreamExt,
1472        channel::{
1473            mpsc::{self, Sender},
1474            oneshot,
1475        },
1476        select_biased,
1477    };
1478    use gpui::{App, AppContext as _, AsyncApp, SemanticVersion, Task, TestAppContext};
1479    use release_channel::ReleaseChannel;
1480    use rpc::proto::Envelope;
1481    use std::{path::PathBuf, sync::Arc};
1482    use util::paths::{PathStyle, RemotePathBuf};
1483
1484    pub(super) struct FakeRemoteConnection {
1485        pub(super) connection_options: RemoteConnectionOptions,
1486        pub(super) server_channel: Arc<ChannelClient>,
1487        pub(super) server_cx: SendableCx,
1488    }
1489
1490    pub(super) struct SendableCx(AsyncApp);
1491    impl SendableCx {
1492        // SAFETY: When run in test mode, GPUI is always single threaded.
1493        pub(super) fn new(cx: &TestAppContext) -> Self {
1494            Self(cx.to_async())
1495        }
1496
1497        // SAFETY: Enforce that we're on the main thread by requiring a valid AsyncApp
1498        fn get(&self, _: &AsyncApp) -> AsyncApp {
1499            self.0.clone()
1500        }
1501    }
1502
1503    // SAFETY: There is no way to access a SendableCx from a different thread, see [`SendableCx::new`] and [`SendableCx::get`]
1504    unsafe impl Send for SendableCx {}
1505    unsafe impl Sync for SendableCx {}
1506
1507    #[async_trait(?Send)]
1508    impl RemoteConnection for FakeRemoteConnection {
1509        async fn kill(&self) -> Result<()> {
1510            Ok(())
1511        }
1512
1513        fn has_been_killed(&self) -> bool {
1514            false
1515        }
1516
1517        fn build_command(
1518            &self,
1519            program: Option<String>,
1520            args: &[String],
1521            env: &HashMap<String, String>,
1522            _: Option<String>,
1523            _: Option<(u16, String, u16)>,
1524        ) -> Result<CommandTemplate> {
1525            let ssh_program = program.unwrap_or_else(|| "sh".to_string());
1526            let mut ssh_args = Vec::new();
1527            ssh_args.push(ssh_program);
1528            ssh_args.extend(args.iter().cloned());
1529            Ok(CommandTemplate {
1530                program: "ssh".into(),
1531                args: ssh_args,
1532                env: env.clone(),
1533            })
1534        }
1535
1536        fn upload_directory(
1537            &self,
1538            _src_path: PathBuf,
1539            _dest_path: RemotePathBuf,
1540            _cx: &App,
1541        ) -> Task<Result<()>> {
1542            unreachable!()
1543        }
1544
1545        fn connection_options(&self) -> RemoteConnectionOptions {
1546            self.connection_options.clone()
1547        }
1548
1549        fn simulate_disconnect(&self, cx: &AsyncApp) {
1550            let (outgoing_tx, _) = mpsc::unbounded::<Envelope>();
1551            let (_, incoming_rx) = mpsc::unbounded::<Envelope>();
1552            self.server_channel
1553                .reconnect(incoming_rx, outgoing_tx, &self.server_cx.get(cx));
1554        }
1555
1556        fn start_proxy(
1557            &self,
1558            _unique_identifier: String,
1559            _reconnect: bool,
1560            mut client_incoming_tx: mpsc::UnboundedSender<Envelope>,
1561            mut client_outgoing_rx: mpsc::UnboundedReceiver<Envelope>,
1562            mut connection_activity_tx: Sender<()>,
1563            _delegate: Arc<dyn RemoteClientDelegate>,
1564            cx: &mut AsyncApp,
1565        ) -> Task<Result<i32>> {
1566            let (mut server_incoming_tx, server_incoming_rx) = mpsc::unbounded::<Envelope>();
1567            let (server_outgoing_tx, mut server_outgoing_rx) = mpsc::unbounded::<Envelope>();
1568
1569            self.server_channel.reconnect(
1570                server_incoming_rx,
1571                server_outgoing_tx,
1572                &self.server_cx.get(cx),
1573            );
1574
1575            cx.background_spawn(async move {
1576                loop {
1577                    select_biased! {
1578                        server_to_client = server_outgoing_rx.next().fuse() => {
1579                            let Some(server_to_client) = server_to_client else {
1580                                return Ok(1)
1581                            };
1582                            connection_activity_tx.try_send(()).ok();
1583                            client_incoming_tx.send(server_to_client).await.ok();
1584                        }
1585                        client_to_server = client_outgoing_rx.next().fuse() => {
1586                            let Some(client_to_server) = client_to_server else {
1587                                return Ok(1)
1588                            };
1589                            server_incoming_tx.send(client_to_server).await.ok();
1590                        }
1591                    }
1592                }
1593            })
1594        }
1595
1596        fn path_style(&self) -> PathStyle {
1597            PathStyle::local()
1598        }
1599
1600        fn shell(&self) -> String {
1601            "sh".to_owned()
1602        }
1603
1604        fn default_system_shell(&self) -> String {
1605            "sh".to_owned()
1606        }
1607    }
1608
1609    pub(super) struct Delegate;
1610
1611    impl RemoteClientDelegate for Delegate {
1612        fn ask_password(&self, _: String, _: oneshot::Sender<EncryptedPassword>, _: &mut AsyncApp) {
1613            unreachable!()
1614        }
1615
1616        fn download_server_binary_locally(
1617            &self,
1618            _: RemotePlatform,
1619            _: ReleaseChannel,
1620            _: Option<SemanticVersion>,
1621            _: &mut AsyncApp,
1622        ) -> Task<Result<PathBuf>> {
1623            unreachable!()
1624        }
1625
1626        fn get_download_params(
1627            &self,
1628            _platform: RemotePlatform,
1629            _release_channel: ReleaseChannel,
1630            _version: Option<SemanticVersion>,
1631            _cx: &mut AsyncApp,
1632        ) -> Task<Result<Option<(String, String)>>> {
1633            unreachable!()
1634        }
1635
1636        fn set_status(&self, _: Option<&str>, _: &mut AsyncApp) {}
1637    }
1638}