chitralverma commented on code in PR #7977:
URL: https://github.com/apache/opendal/pull/7977#discussion_r4759260800


##########
core/services/sftp/src/core.rs:
##########
@@ -83,71 +177,417 @@ impl SftpCore {
             _permit: permit,
         })
     }
+
+    /// Returns the server path for an OpenDAL path.
+    pub fn remote_path(&self, path: &str) -> String {
+        remote_path(&self.root, path)
+    }
+}
+
+/// Returns the server path for `path` under `root`.
+///
+/// An empty root keeps the path relative to the login directory.
+fn remote_path(root: &str, path: &str) -> String {
+    let joined = if root.is_empty() {
+        build_absolute_path("/", path)
+    } else {
+        build_rooted_absolute_path(root, path)
+    };
+
+    // OpenSSH for Windows rejects a path with a trailing separator.
+    match joined.trim_end_matches('/') {
+        "" if root.is_empty() => ".".to_string(),
+        "" => "/".to_string(),
+        trimmed => trimmed.to_string(),
+    }
 }
 
 pub struct SftpConnection {
     // Return the connection to the pool before another checkout can take its 
slot.
-    object: unbounded::Object<Sftp, Manager>,
+    object: unbounded::Object<SftpClient, Manager>,
     _permit: OwnedSemaphorePermit,
 }
 
 impl Deref for SftpConnection {
-    type Target = Sftp;
+    type Target = SftpClient;
 
     fn deref(&self) -> &Self::Target {
         &self.object
     }
 }
 
+/// An authenticated SSH connection with an open SFTP session.
+pub struct SftpClient {
+    pub sftp: RawSftpSession,
+    /// Largest payload of one read request.
+    pub read_len: u32,
+    /// Largest payload of one write request.
+    pub write_len: u32,
+    pub posix_rename: bool,
+    pub copy_data: bool,
+    /// The runtime of the SSH connection tasks.
+    pub runtime: tokio::runtime::Handle,
+    _ssh: client::Handle<SshHandler>,
+}
+
+/// An open file or directory handle on a pooled connection.
+///
+/// The connection stays checked out while a handle is open. Dropping the
+/// handle without [`OpenHandle::close`] closes it in the background.
+pub struct OpenHandle {
+    conn: Arc<SftpConnection>,
+    handle: Option<SftpHandle>,
+}
+
+impl OpenHandle {
+    /// Opens a file with `flags`.
+    pub async fn open(
+        conn: Arc<SftpConnection>,
+        path: SftpString,
+        flags: OpenFlags,
+    ) -> Result<Self, SftpClientError> {
+        Self::spawn_open(conn, move |conn| async move {
+            conn.sftp.open(path, flags, FileAttributes::empty()).await
+        })
+        .await
+    }
+
+    /// Opens a directory to list.
+    pub async fn open_dir(
+        conn: Arc<SftpConnection>,
+        path: SftpString,
+    ) -> Result<Self, SftpClientError> {
+        Self::spawn_open(
+            conn,
+            move |conn| async move { conn.sftp.opendir(path).await },
+        )
+        .await
+    }
+
+    /// Sends the open request in a task that owns the result. If the caller
+    /// stops waiting, the task drops the new handle, which closes it.
+    async fn spawn_open<F, Fut>(conn: Arc<SftpConnection>, open: F) -> 
Result<Self, SftpClientError>
+    where
+        F: FnOnce(Arc<SftpConnection>) -> Fut,
+        Fut: Future<Output = Result<Handle, SftpClientError>> + Send + 'static,
+    {
+        let runtime = conn.runtime.clone();
+        let request = open(conn.clone());
+        runtime
+            .spawn(async move {
+                let handle = request.await?.handle;
+                Ok(Self {
+                    conn,
+                    handle: Some(handle),
+                })
+            })
+            .await
+            .unwrap_or_else(|err| {
+                Err(SftpClientError::UnexpectedBehavior(format!(
+                    "sftp open task failed: {err}"
+                )))
+            })
+    }
+
+    pub fn client(&self) -> &SftpClient {
+        &self.conn
+    }
+
+    pub fn connection(&self) -> &Arc<SftpConnection> {
+        &self.conn
+    }
+
+    pub fn handle(&self) -> &SftpHandle {
+        self.handle
+            .as_ref()
+            .expect("handle must stay open until close")
+    }
+
+    pub async fn close(mut self) -> Result<()> {
+        let handle = self.handle.take().expect("handle must not be closed 
twice");
+        self.conn
+            .sftp
+            .close(handle)
+            .await
+            .map(|_| ())
+            .map_err(parse_sftp_error)
+    }
+}
+
+impl Drop for OpenHandle {
+    fn drop(&mut self) {
+        let Some(handle) = self.handle.take() else {
+            return;
+        };
+        let conn = self.conn.clone();
+        self.conn.runtime.spawn(async move {

Review Comment:
   3ae6a0b7d fixes both cases.
   
   1. **Close:** `OpenHandle::close` now retires the connection when the close 
fails or nobody waits for its reply. 
`failed_close_retires_the_connection_for_the_next_checkout` checks that the 
next checkout opens a new SSH connection, and 
`cancelled_close_retires_the_connection` covers cancellation.
   2. **Directory read:** a pending `readdir` owns the directory handle, and 
the lister now has explicit states (`Idle`, `Reading`, `Done`, `Interrupted`).
      - A retried `next()` waits for the same reply, so it gets the in-flight 
batch: `retried_next_reads_the_batch_of_a_cancelled_readdir`.
      - When no caller waits, the request has 10 s. Then it retires the 
connection and drops the handle, which releases the checkout while the lister 
is still alive. Later `next()` calls return an error, not the end of the 
directory: `stalled_readdir_releases_the_connection_and_fails_the_listing`.
      - A caller that keeps waiting is not cut off: 
`waiting_next_outlasts_the_abandon_deadline`.
   
   Each test fails when its rule is removed, and the behavior suite still 
passes 130/130 on both fixture setups.
   
   *This comment is AI assisted.*



##########
core/services/sftp/src/core.rs:
##########
@@ -83,71 +177,417 @@ impl SftpCore {
             _permit: permit,
         })
     }
+
+    /// Returns the server path for an OpenDAL path.
+    pub fn remote_path(&self, path: &str) -> String {
+        remote_path(&self.root, path)
+    }
+}
+
+/// Returns the server path for `path` under `root`.
+///
+/// An empty root keeps the path relative to the login directory.
+fn remote_path(root: &str, path: &str) -> String {
+    let joined = if root.is_empty() {
+        build_absolute_path("/", path)
+    } else {
+        build_rooted_absolute_path(root, path)
+    };
+
+    // OpenSSH for Windows rejects a path with a trailing separator.
+    match joined.trim_end_matches('/') {
+        "" if root.is_empty() => ".".to_string(),
+        "" => "/".to_string(),
+        trimmed => trimmed.to_string(),
+    }
 }
 
 pub struct SftpConnection {
     // Return the connection to the pool before another checkout can take its 
slot.
-    object: unbounded::Object<Sftp, Manager>,
+    object: unbounded::Object<SftpClient, Manager>,
     _permit: OwnedSemaphorePermit,
 }
 
 impl Deref for SftpConnection {
-    type Target = Sftp;
+    type Target = SftpClient;
 
     fn deref(&self) -> &Self::Target {
         &self.object
     }
 }
 
+/// An authenticated SSH connection with an open SFTP session.
+pub struct SftpClient {
+    pub sftp: RawSftpSession,
+    /// Largest payload of one read request.
+    pub read_len: u32,
+    /// Largest payload of one write request.
+    pub write_len: u32,
+    pub posix_rename: bool,
+    pub copy_data: bool,
+    /// The runtime of the SSH connection tasks.
+    pub runtime: tokio::runtime::Handle,
+    _ssh: client::Handle<SshHandler>,
+}
+
+/// An open file or directory handle on a pooled connection.
+///
+/// The connection stays checked out while a handle is open. Dropping the
+/// handle without [`OpenHandle::close`] closes it in the background.
+pub struct OpenHandle {
+    conn: Arc<SftpConnection>,
+    handle: Option<SftpHandle>,
+}
+
+impl OpenHandle {
+    /// Opens a file with `flags`.
+    pub async fn open(
+        conn: Arc<SftpConnection>,
+        path: SftpString,
+        flags: OpenFlags,
+    ) -> Result<Self, SftpClientError> {
+        Self::spawn_open(conn, move |conn| async move {
+            conn.sftp.open(path, flags, FileAttributes::empty()).await
+        })
+        .await
+    }
+
+    /// Opens a directory to list.
+    pub async fn open_dir(
+        conn: Arc<SftpConnection>,
+        path: SftpString,
+    ) -> Result<Self, SftpClientError> {
+        Self::spawn_open(
+            conn,
+            move |conn| async move { conn.sftp.opendir(path).await },
+        )
+        .await
+    }
+
+    /// Sends the open request in a task that owns the result. If the caller
+    /// stops waiting, the task drops the new handle, which closes it.
+    async fn spawn_open<F, Fut>(conn: Arc<SftpConnection>, open: F) -> 
Result<Self, SftpClientError>
+    where
+        F: FnOnce(Arc<SftpConnection>) -> Fut,
+        Fut: Future<Output = Result<Handle, SftpClientError>> + Send + 'static,
+    {
+        let runtime = conn.runtime.clone();
+        let request = open(conn.clone());
+        runtime
+            .spawn(async move {
+                let handle = request.await?.handle;
+                Ok(Self {
+                    conn,
+                    handle: Some(handle),
+                })
+            })
+            .await
+            .unwrap_or_else(|err| {
+                Err(SftpClientError::UnexpectedBehavior(format!(
+                    "sftp open task failed: {err}"
+                )))
+            })
+    }
+
+    pub fn client(&self) -> &SftpClient {
+        &self.conn
+    }
+
+    pub fn connection(&self) -> &Arc<SftpConnection> {
+        &self.conn
+    }
+
+    pub fn handle(&self) -> &SftpHandle {
+        self.handle
+            .as_ref()
+            .expect("handle must stay open until close")
+    }
+
+    pub async fn close(mut self) -> Result<()> {
+        let handle = self.handle.take().expect("handle must not be closed 
twice");
+        self.conn
+            .sftp
+            .close(handle)
+            .await
+            .map(|_| ())
+            .map_err(parse_sftp_error)
+    }
+}
+
+impl Drop for OpenHandle {
+    fn drop(&mut self) {
+        let Some(handle) = self.handle.take() else {
+            return;
+        };
+        let conn = self.conn.clone();
+        self.conn.runtime.spawn(async move {
+            if let Err(err) = conn.sftp.close(handle).await {
+                debug!("failed to close SFTP handle: {err}");
+            }
+        });
+    }
+}
+
 pub struct Manager {
-    pub(super) endpoint: String,
+    pub(super) endpoint: SshEndpoint,
     pub(super) root: String,
-    pub(super) user: Option<String>,
+    pub(super) user: String,
     pub(super) key: Option<String>,
-    pub(super) known_hosts_strategy: KnownHosts,
+    pub(super) host_keys: HostKeyVerifier,
     pub(super) connect_timeout: Option<Duration>,
-    #[cfg(not(windows))]
-    pub(super) control_directory: Option<String>,
+    pub(super) handshakes: Semaphore,
 }
 
 impl Manager {
-    async fn initialize_root(&self, sftp: &Sftp) -> Result<()> {
-        create_dir_all(sftp, "", &self.root).await
-    }
-}
+    async fn connect_ssh(&self) -> Result<client::Handle<SshHandler>> {
+        let host = self.endpoint.known_hosts_name();
+        let mut config = client::Config::default();
+        config.preferred.key = Cow::Owned(prefer_recorded_algorithms(
+            &config.preferred.key,
+            &self.host_keys.recorded_algorithms(&host),
+        ));
 
-pub(crate) async fn create_dir_all(sftp: &Sftp, base: &str, path: &str) -> 
Result<()> {
-    let mut fs = sftp.fs();
-    let mut current = PathBuf::from(base);
-    if !base.is_empty() {
-        fs.set_cwd(&current);
+        let handler = SshHandler {
+            host,
+            host_keys: self.host_keys.clone(),
+        };
+        let mut ssh = client::connect(
+            Arc::new(config),
+            (self.endpoint.host.as_str(), self.endpoint.port),
+            handler,
+        )
+        .await
+        .map_err(SshClientError::into_error)?;
+
+        self.authenticate(&mut ssh, &self.user).await?;
+        Ok(ssh)
     }
 
-    for component in Path::new(path).components() {
-        let segment = component.as_os_str();
-        match component {
-            Component::RootDir => {
-                if base.is_empty() {
-                    current.push(segment);
-                    fs.set_cwd(&current);
+    /// Authenticates with `key`, or with the SSH agent and the default
+    /// identity files when `key` is not set.
+    async fn authenticate(&self, ssh: &mut client::Handle<SshHandler>, user: 
&str) -> Result<()> {
+        let rsa_hash = ssh
+            .best_supported_rsa_hash()
+            .await
+            .map_err(parse_ssh_error)?
+            .flatten();
+
+        if let Some(path) = &self.key {
+            let key = russh::keys::load_secret_key(path, None).map_err(|err| {

Review Comment:
   3ae6a0b7d strips every `/` after `~`, and every native separator on Windows, 
so `~//.ssh/id` resolves to `.ssh/id` under the home directory. `~user/…` stays 
literal. `home_relative_key_paths_are_expanded` covers `~//.ssh/id`, and on 
Windows `~\\.ssh\id`.
   
   *This comment is AI assisted.*



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to