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


##########
core/services/sftp/src/core.rs:
##########
@@ -15,40 +15,135 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use std::borrow::Cow;
 use std::fmt::Debug;
 use std::future::Future;
 use std::io;
 use std::ops::Deref;
-use std::path::{Component, Path, PathBuf};
+use std::path::PathBuf;
 use std::sync::Arc;
 
 use asyncband::pool::{ManageObject, ObjectStatus, unbounded};
 use asyncband::semaphore::{OwnedSemaphorePermit, Semaphore};
 use log::debug;
 use opendal_core::raw::*;
 use opendal_core::*;
-use openssh::Error as SshError;
-use openssh::{KnownHosts, SessionBuilder};
-use openssh_sftp_client::Error as SftpClientError;
-use openssh_sftp_client::error::SftpErrorKind;
-use openssh_sftp_client::{Sftp, SftpOptions};
+use russh::client;
+use russh::keys::PrivateKeyWithHashAlg;
+use russh::keys::ssh_key::Algorithm;
+use russh::keys::ssh_key::HashAlg;
+use russh_sftp::client::RawSftpSession;
+use russh_sftp::client::error::Error as SftpClientError;
+use russh_sftp::client::rawsession::Limits;
+use russh_sftp::extensions;
+use russh_sftp::protocol::{FileAttributes, Handle, OpenFlags, SftpHandle, 
SftpString, StatusCode};
+use url::Url;
+
+use super::known_hosts::HostKeyVerifier;
 
 const POOL_CAPACITY: usize = 64;
 
+/// SSH handshakes that one pool runs at a time. OpenSSH starts to drop
+/// unauthenticated connections at 10 (`MaxStartups 10:30:100`).
+pub(crate) const MAX_CONCURRENT_HANDSHAKES: usize = 4;
+
+/// Payload limit of one read or write when the server does not send
+/// `[email protected]`. SFTP v3 servers must accept packets of 32 KiB.
+const DEFAULT_PAYLOAD_LEN: u64 = 32 * 1024;
+
+/// Bytes of a packet that a read or write request header can use. OpenSSH
+/// keeps the same distance between its packet and payload limits.
+const REQUEST_HEADER_LEN: u64 = 1024;
+
+const COPY_DATA: &str = "copy-data";
+
+/// SSH server address and login user parsed from the `endpoint` option.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SshEndpoint {
+    pub user: Option<String>,
+    pub host: String,
+    pub port: u16,
+}
+
+impl SshEndpoint {
+    /// Parses `[user@]host[:port]` or `ssh://[user@]host[:port]`.
+    ///
+    /// The port defaults to 22. An IPv6 address must be in brackets.
+    pub fn parse(endpoint: &str) -> Result<Self> {
+        let invalid = |reason: &str| {
+            Error::new(
+                ErrorKind::ConfigInvalid,
+                format!("sftp endpoint is invalid: {reason}"),
+            )
+            .with_context("endpoint", endpoint)

Review Comment:
   83a4121f2 removes the endpoint from parse errors. 
`endpoint_errors_omit_credentials` checks that `ssh://alice:secret-marker@host` 
leaves no marker in `Display` or `Debug`. I'll merge the builder diagnostics 
fix once it lands.
   
   *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 {

Review Comment:
   83a4121f2 bounds each case and retires the connection when its state is 
unknown. Retiring closes the SFTP session, which frees its handles on the 
server, and `is_recyclable` then discards the connection.
   
   - **Open:** no longer runs in a task. A cancelled `open` or `opendir` 
retires the connection at once.
   - **Dropped handle:** its close waits at most 10 s 
(`CLOSE_ON_DROP_TIMEOUT`). A failure or timeout retires the connection.
   - **Directory read:** a lister dropped while a `readdir` is pending aborts 
the task and retires the connection.
   
   Tests use an in-process russh server that stalls `open`, `readdir`, or 
`close`. Each test fails when its retirement is removed.
   
   *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