Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 110 additions & 32 deletions src/crates/services/services-integrations/src/remote_ssh/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//! This module manages SSH connections using the pure-Russ SSH implementation

use super::proxy_command::{expand_tokens, ProxyCommandChild};
use super::sftp_file::ManagedSftpSession;
use super::sftp_file::{ManagedSftpFile, ManagedSftpSession};
#[cfg(feature = "ssh_config")]
use super::ssh_config_loader::{
is_host_pattern, load_merged_config_async, resolve_host_settings, split_directive,
Expand All @@ -26,6 +26,8 @@ use russh_sftp::client::error::Error as SftpError;
use russh_sftp::client::{RawSftpSession, SftpSession};
use russh_sftp::protocol::{File as SftpFile, StatusCode as SftpStatusCode};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
Expand Down Expand Up @@ -375,7 +377,7 @@ mtime=$(stat -c %Y \"$item\" 2>/dev/null || stat -f %m \"$item\" 2>/dev/null ||
mode=$(stat -c %a \"$item\" 2>/dev/null || stat -f %Lp \"$item\" 2>/dev/null || true); \
printf '%s\\0%s\\0%s\\0%s\\0%s\\0%s\\0' \"$name\" \"$item\" \"$kind\" \"$size\" \"$mtime\" \"$mode\";";

fn sftp_error_may_be_stale_transport(error: &SftpError) -> bool {
pub(super) fn sftp_error_may_be_stale_transport(error: &SftpError) -> bool {
match error {
SftpError::Status(status) => matches!(
status.status_code,
Expand Down Expand Up @@ -671,6 +673,9 @@ struct SftpCache {
init_lock: tokio::sync::Mutex<()>,
}

/// One replayable request issued against a cached SFTP subsystem.
type SftpRequest<T> = Pin<Box<dyn Future<Output = Result<T, SftpError>> + Send>>;

impl SftpCache {
fn new() -> Self {
Self {
Expand Down Expand Up @@ -5602,11 +5607,9 @@ impl SSHConnectionManager {
let transport = self.open_workspace_stdio(connection_id, &command).await?;
return Ok(Box::new(ContainerFileReader::from_transport(transport)));
}
let sftp = self.get_sftp(connection_id).await?;
let file = sftp
.open(&path)
let file = self
.sftp_open_with_recovery(connection_id, &path)
.await
.map_err(anyhow::Error::new)
.with_context(|| format!("Failed to open remote file '{path}'"))?;
if !file.metadata().await?.file_type().is_file() {
anyhow::bail!("Workspace path is not a regular file: {path}");
Expand Down Expand Up @@ -6393,6 +6396,58 @@ impl SSHConnectionManager {
Ok(sftp)
}

/// Replay one read-only request on a fresh subsystem channel.
///
/// russh-sftp rejects every request on a closed subsystem channel with
/// `UnexpectedBehavior("session closed")` and never reopens it, while
/// `get_sftp` keeps handing out that same cached session. Returning that
/// error left the file browser stuck on `Failed to stat` until the app was
/// restarted. [`ManagedSftpSession`] now retires a session whose channel is
/// gone, so replaying the request once opens a new channel instead of
/// failing forever. Only idempotent queries may use this helper.
async fn sftp_query_with_recovery<T, F>(
&self,
connection_id: &str,
path: &str,
query: F,
) -> anyhow::Result<T>
where
F: Fn(Arc<ManagedSftpSession>, String) -> SftpRequest<T>,
{
let mut replay = true;
loop {
let session = self.get_sftp(connection_id).await?;
match query(session, path.to_owned()).await {
Ok(value) => return Ok(value),
Err(error) if replay && sftp_error_may_be_stale_transport(&error) => {
replay = false;
log::warn!(
"Cached SFTP subsystem for {} failed on '{}' (will retry once on a new channel): {}",
connection_id,
path,
error
);
}
Err(error) => return Err(anyhow::Error::new(error)),
}
}
}

/// Open a file read-only, replaying the OPEN once on a fresh subsystem.
///
/// A read-only OPEN changes nothing on the server and no data has reached
/// the caller yet, so it is as safe to replay as a metadata query.
async fn sftp_open_with_recovery(
&self,
connection_id: &str,
path: &str,
) -> anyhow::Result<ManagedSftpFile> {
self.sftp_query_with_recovery(connection_id, path, |sftp, open_path| {
Box::pin(async move { sftp.open(&open_path).await })
})
.await
}

/// Reuse a dedicated SFTP channel for serialized directory enumeration.
/// The high-level API leaks directory handles on errors/cancellation. The
/// raw path closes on all exits and can also stop at an entry budget.
Expand Down Expand Up @@ -6476,9 +6531,8 @@ impl SSHConnectionManager {
/// Read a file via SFTP
pub async fn sftp_read(&self, connection_id: &str, path: &str) -> anyhow::Result<Vec<u8>> {
let path = self.resolve_sftp_path(connection_id, path).await?;
let sftp = self.get_sftp(connection_id).await?;
let mut file = sftp
.open(&path)
let mut file = self
.sftp_open_with_recovery(connection_id, &path)
.await
.map_err(|e| anyhow!("Failed to open remote file '{}': {}", path, e))?;

Expand Down Expand Up @@ -6507,18 +6561,18 @@ impl SSHConnectionManager {
on_progress: &mut impl FnMut(u64, u64) -> bool,
) -> anyhow::Result<Vec<u8>> {
let resolved = self.resolve_sftp_path(connection_id, path).await?;
let sftp = self.get_sftp(connection_id).await?;

// Determine file size from metadata for progress calculation.
let metadata = sftp
.as_ref()
.metadata(&resolved)
let metadata = self
.sftp_query_with_recovery(connection_id, &resolved, |sftp, query_path| {
Box::pin(async move { sftp.as_ref().metadata(&query_path).await })
})
.await
.map_err(|e| anyhow!("Failed to stat '{}': {}", resolved, e))?;
let total = metadata.size.unwrap_or(0);

let mut file = sftp
.open(&resolved)
let mut file = self
.sftp_open_with_recovery(connection_id, &resolved)
.await
.map_err(|e| anyhow!("Failed to open remote file '{}': {}", resolved, e))?;

Expand Down Expand Up @@ -6904,16 +6958,37 @@ impl SSHConnectionManager {
/// Create directory and all parents via SFTP
pub async fn sftp_mkdir_all(&self, connection_id: &str, path: &str) -> anyhow::Result<()> {
let path = self.resolve_sftp_path(connection_id, path).await?;
// Every step accepts directories that already exist, so a whole attempt
// can be replayed once after a dead cached subsystem was retired.
match self.sftp_mkdir_all_once(connection_id, &path).await {
Err(error)
if error
.downcast_ref::<SftpError>()
.is_some_and(sftp_error_may_be_stale_transport) =>
{
log::warn!(
"Cached SFTP subsystem for {} failed creating '{}' (will retry once on a new channel): {:#}",
connection_id,
path,
error
);
self.sftp_mkdir_all_once(connection_id, &path).await
}
result => result,
}
}

async fn sftp_mkdir_all_once(&self, connection_id: &str, path: &str) -> anyhow::Result<()> {
let sftp = self.get_sftp(connection_id).await?;

// Check if path exists
match sftp.as_ref().try_exists(&path).await {
match sftp.as_ref().try_exists(path).await {
Ok(true) => return Ok(()), // Already exists
Ok(false) => {}
Err(_) => {}
}

for dir in sftp_mkdir_all_prefixes(&path) {
for dir in sftp_mkdir_all_prefixes(path) {
if let Ok(true) = sftp.as_ref().try_exists(&dir).await {
continue;
}
Expand All @@ -6922,7 +6997,8 @@ impl SSHConnectionManager {
match sftp.as_ref().try_exists(&dir).await {
Ok(true) => continue,
Ok(false) | Err(_) => {
return Err(anyhow!("Failed to create directory '{}': {}", dir, error));
let message = format!("Failed to create directory '{}': {}", dir, error);
return Err(anyhow::Error::new(error).context(message));
}
}
}
Expand Down Expand Up @@ -6970,11 +7046,11 @@ impl SSHConnectionManager {
/// Check if path exists via SFTP
pub async fn sftp_exists(&self, connection_id: &str, path: &str) -> anyhow::Result<bool> {
let path = self.resolve_sftp_path(connection_id, path).await?;
let sftp = self.get_sftp(connection_id).await?;
sftp.as_ref()
.try_exists(&path)
.await
.map_err(|e| anyhow!("Failed to check if '{}' exists: {}", path, e))
self.sftp_query_with_recovery(connection_id, &path, |sftp, query_path| {
Box::pin(async move { sftp.as_ref().try_exists(&query_path).await })
})
.await
.map_err(|e| anyhow!("Failed to check if '{}' exists: {}", path, e))
}

/// Get file metadata via SFTP
Expand All @@ -6984,10 +7060,13 @@ impl SSHConnectionManager {
path: &str,
) -> anyhow::Result<russh_sftp::client::fs::Metadata> {
let path = self.resolve_sftp_path(connection_id, path).await?;
let sftp = self.get_sftp(connection_id).await?;
sftp.as_ref().metadata(&path).await.map_err(|error| {
self.sftp_query_with_recovery(connection_id, &path, |sftp, query_path| {
Box::pin(async move { sftp.as_ref().metadata(&query_path).await })
})
.await
.map_err(|error| {
let message = format!("Failed to stat '{}': {}", path, error);
anyhow::Error::new(error).context(message)
error.context(message)
})
}

Expand All @@ -6998,12 +7077,11 @@ impl SSHConnectionManager {
path: &str,
) -> anyhow::Result<russh_sftp::client::fs::Metadata> {
let path = self.resolve_sftp_path(connection_id, path).await?;
let sftp = self.get_sftp(connection_id).await?;
sftp.as_ref()
.symlink_metadata(&path)
.await
.map_err(anyhow::Error::new)
.with_context(|| format!("Failed to inspect '{}'", path))
self.sftp_query_with_recovery(connection_id, &path, |sftp, query_path| {
Box::pin(async move { sftp.as_ref().symlink_metadata(&query_path).await })
})
.await
.with_context(|| format!("Failed to inspect '{}'", path))
}

// ============================================================================
Expand Down
Loading
Loading