chitralverma commented on code in PR #7977:
URL: https://github.com/apache/opendal/pull/7977#discussion_r4756962584
##########
core/services/sftp/src/writer.rs:
##########
@@ -15,45 +15,93 @@
// specific language governing permissions and limitations
// under the License.
-use std::pin::Pin;
-
use bytes::Buf;
-use openssh_sftp_client::file::File;
-use openssh_sftp_client::file::TokioCompatFile;
-use tokio::io::AsyncWriteExt;
+use super::core::PIPELINE_DEPTH;
+use super::core::SftpSessionRef;
+use super::core::close_handle_detached;
+use super::core::parse_sftp_error;
use opendal_core::raw::*;
use opendal_core::*;
+/// Writes a remote file by streaming `Buffer`s into an open SFTP handle.
+///
+/// Writes are split into packets no larger than the size the server advertises
+/// and several packets are kept in flight, so throughput does not collapse to
+/// one round trip per packet.
pub struct SftpWriter {
- /// TODO: maybe we can use `File` directly?
- file: Pin<Box<TokioCompatFile>>,
+ /// Keeps the session alive while the remote handle is open.
+ conn: SftpSessionRef,
+ handle: String,
+ offset: u64,
+ closed: bool,
+}
+
+impl Drop for SftpWriter {
+ fn drop(&mut self) {
+ if self.closed {
+ return;
+ }
+
+ // An aborted write never calls `close`, so release the handle here.
+ close_handle_detached(self.conn.session.clone(), std::mem::take(&mut
self.handle));
+ }
}
impl SftpWriter {
- pub fn new(file: File) -> Self {
+ pub fn new(conn: SftpSessionRef, handle: String, offset: u64) -> Self {
SftpWriter {
- file: Box::pin(TokioCompatFile::new(file)),
+ conn,
+ handle,
+ offset,
+ closed: false,
}
}
}
impl oio::Write for SftpWriter {
async fn write(&mut self, mut bs: Buffer) -> Result<()> {
+ let chunk = self.conn.write_len as usize;
+ let mut inflight = Vec::with_capacity(PIPELINE_DEPTH);
+
while bs.has_remaining() {
- let n = self
- .file
- .write(bs.chunk())
+ let piece = bs.chunk();
+ let take = piece.len().min(chunk);
+ let data = piece[..take].to_vec();
+ bs.advance(take);
+
+ let offset = self.offset;
+ self.offset += take as u64;
Review Comment:
04c34d691: `write_at` returns the new offset only after every
acknowledgement, and the writer assigns it after `?`.
`retried_write_after_partial_acknowledgement_writes_each_byte_once` runs an
in-memory russh-sftp server that fails the second packet once. It checks that
the error is temporary and the final bytes are right after the retry.
*This comment is AI assisted.*
##########
core/services/sftp/src/backend.rs:
##########
@@ -329,15 +434,66 @@ impl Service for SftpBackend {
to: &str,
_: OpRename,
) -> Result<RpRename> {
- let client = self.core.connect().await?;
-
- let mut fs = client.fs();
- fs.set_cwd(&self.core.root);
-
if let Some((dir, _)) = to.rsplit_once('/') {
self.create_dir(ctx, dir, OpCreateDir::default()).await?;
}
- fs.rename(from, to).await.map_err(parse_sftp_error)?;
+
+ let conn = self.core.connect().await?;
+ let from = self.core.abs_path(from);
+ let to = self.core.abs_path(to);
+
+ if conn.posix_rename {
+ // `[email protected]` replaces an existing destination
+ // atomically, which plain SFTP v3 `rename` refuses to do.
+ let payload: Vec<u8> = HardlinkExtension {
+ oldpath: from,
+ newpath: to,
+ }
+ .try_into()
+ .map_err(|err| {
+ Error::new(
+ ErrorKind::Unexpected,
+ "sftp failed to encode rename request",
+ )
+ .set_source(err)
+ })?;
+
+ match conn
+ .session
+ .extended(POSIX_RENAME, payload)
+ .await
+ .map_err(parse_sftp_error)?
+ {
+ Packet::Status(status) if status.status_code == StatusCode::Ok
=> {}
+ Packet::Status(status) => {
+ return
Err(parse_sftp_error(SftpClientError::Status(status)));
+ }
+ _ => {
+ return Err(Error::new(
+ ErrorKind::Unexpected,
+ "sftp rename returned an unexpected packet",
+ ));
+ }
+ }
+ } else {
+ // Plain SFTP v3 `rename` refuses an existing destination. Try it
+ // first and only clear the destination once it is the thing in the
+ // way, so a missing or unreadable source cannot destroy the
target.
+ match conn.session.rename(from.clone(), to.clone()).await {
+ Ok(_) => {}
+ Err(e) if is_sftp_failure(&e) => {
Review Comment:
04c34d691: without `[email protected]` the service sends a plain
`rename` and returns its error. It never removes the destination, as on `main`.
*This comment is AI assisted.*
##########
core/services/sftp/src/lister.rs:
##########
@@ -15,75 +15,143 @@
// specific language governing permissions and limitations
// under the License.
-use std::pin::Pin;
+use std::collections::VecDeque;
-use futures::StreamExt;
-use openssh_sftp_client::fs::DirEntry;
-use openssh_sftp_client::fs::ReadDir;
+use russh_sftp::protocol::{FileAttributes, FileMode};
+use super::core::SftpSessionRef;
+use super::core::close_handle_detached;
+use super::core::is_eof;
use super::core::parse_sftp_error;
use super::core::to_metadata;
use opendal_core::Result;
use opendal_core::raw::oio;
use opendal_core::raw::oio::Entry;
+/// Lists a remote directory one `SSH_FXP_READDIR` batch at a time.
+///
+/// Entries are yielded as they arrive rather than buffering the whole
+/// directory, which keeps memory flat for large directories.
pub struct SftpLister {
- dir: Pin<Box<ReadDir>>,
+ /// Keeps the session alive while the directory handle is open.
+ conn: SftpSessionRef,
+ handle: String,
prefix: String,
+ buffer: VecDeque<(String, FileAttributes)>,
+ /// Whether the directory's own entry still has to be emitted.
+ emit_self: bool,
+ finished: bool,
+}
+
+impl Drop for SftpLister {
+ fn drop(&mut self) {
+ if self.finished {
+ return;
+ }
+
+ // `list_with_limit` callers routinely stop before the directory ends,
+ // so the handle has to be released here too.
+ close_handle_detached(self.conn.session.clone(), std::mem::take(&mut
self.handle));
+ }
}
impl SftpLister {
- pub fn new(dir: ReadDir, path: String) -> Self {
+ pub fn new(conn: SftpSessionRef, handle: String, path: String) -> Self {
let prefix = if path == "/" { "".to_owned() } else { path };
SftpLister {
- dir: Box::pin(dir),
+ conn,
+ handle,
prefix,
+ buffer: VecDeque::new(),
+ emit_self: true,
+ finished: false,
+ }
+ }
+
+ /// Builds the entry for the directory being listed.
+ ///
+ /// The metadata comes from the open handle rather than a `.` entry:
+ /// OpenSSH on Windows omits `.` and `..` from `readdir` altogether, so a
+ /// listing that relied on them would silently drop the directory itself.
+ async fn self_entry(&self) -> Entry {
+ let attrs = match self.conn.session.fstat(self.handle.as_str()).await {
+ Ok(attrs) => attrs.attrs,
+ Err(_) => {
+ let mut attrs = FileAttributes::default();
+ attrs.set_type(FileMode::DIR);
+ attrs
+ }
+ };
+
+ let path = if self.prefix.is_empty() {
+ "/"
+ } else {
+ self.prefix.as_str()
+ };
+
+ Entry::new(path, to_metadata(&attrs))
+ }
+
+ /// Pulls the next batch of entries, returning `false` once the server
+ /// reports the end of the directory.
+ async fn fill(&mut self) -> Result<bool> {
+ if self.finished {
+ return Ok(false);
+ }
+
+ match self.conn.session.readdir(self.handle.as_str()).await {
+ Ok(name) => {
+ self.buffer
+ .extend(name.files.into_iter().map(|f| (f.filename,
f.attrs)));
+ Ok(true)
+ }
+ Err(e) if is_eof(&e) => {
+ self.finished = true;
+ // Release the directory handle as soon as the listing ends.
+ let _ = self
+ .conn
+ .session
+ .close(std::mem::take(&mut self.handle))
+ .await;
+ Ok(false)
+ }
+ Err(e) => {
+ self.finished = true;
Review Comment:
04c34d691: the lister owns an `OpenHandle`. Only EOF closes it explicitly;
an error, early drop, or cancellation closes it on drop. `readdir` also runs in
a task that the lister keeps, so a retried `next()` after a cancelled one waits
for the same reply and skips no entries.
*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]