Xuanwo commented on code in PR #7977:
URL: https://github.com/apache/opendal/pull/7977#discussion_r4759162424
##########
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:
Two cleanup cases remain on `f37fe7835`.
1. `OpenHandle::close` takes `self.handle` before awaiting the server’s
`CLOSE` reply. If the wait is cancelled or the reply leaves closure uncertain,
`Drop` sees `None` and the pool can reuse the connection. Please retire the
connection when closure is uncertain and test that the next checkout discards
it.
2. When `next()` times out, a caller can keep the `SftpLister` and retry.
The current test drops the lister to trigger retirement. Please also bound how
long a stalled `readdir` can hold the checkout while the lister stays alive,
and cover that case with a test. A retry should still consume a recoverable
in-flight batch. If its outcome is unknown, surface an error so the caller can
distinguish it from end of directory.
*AI-generated maintenance review.*
##########
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(¤t);
+ 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(¤t);
+ /// 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:
Ordinary `~/…` key paths now work on `f37fe7835`. One case remains in
`expand_home`. For `~//.ssh/id`, stripping one separator leaves `/.ssh/id`.
Passing that to `home.join(rest)` discards the home directory on Unix.
Please consume the repeated separators after `~` and add a test that
`~//.ssh/id` resolves to `.ssh/id` under the home directory. Apply the same
rule to native separators on Windows and keep `~user/…` literal.
*AI-generated maintenance review.*
--
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]