chitralverma commented on code in PR #7977:
URL: https://github.com/apache/opendal/pull/7977#discussion_r4757562326
##########
core/services/sftp/src/writer.rs:
##########
@@ -15,48 +15,60 @@
// specific language governing permissions and limitations
// under the License.
-use bytes::Bytes;
-use openssh_sftp_client::file::File;
+use std::collections::VecDeque;
-use super::core::SftpConnection;
+use russh_sftp::client::RawSftpSession;
+use russh_sftp::client::rawsession::PendingWrite;
+use russh_sftp::protocol::SftpHandle;
+
+use super::core::OpenHandle;
use super::core::parse_sftp_error;
use opendal_core::raw::*;
use opendal_core::*;
+/// Write requests sent before the writer waits for the oldest acknowledgement.
+/// Each request needs a round trip, so one request at a time is bound by
latency.
+const MAX_PENDING_WRITES: usize = 16;
+
pub struct SftpWriter {
- file: Option<File>,
- // Keep the connection checked out until after the file handle closes.
- _conn: Option<SftpConnection>,
+ file: Option<OpenHandle>,
+ /// End of the data that the server has acknowledged.
+ offset: u64,
}
impl SftpWriter {
- pub fn new(file: File, conn: SftpConnection) -> Self {
+ pub fn new(file: OpenHandle) -> Self {
SftpWriter {
file: Some(file),
- _conn: Some(conn),
+ offset: 0,
}
}
}
impl oio::Write for SftpWriter {
async fn write(&mut self, bs: Buffer) -> Result<()> {
- let file = self.file.as_mut().ok_or_else(|| {
+ let file = self.file.as_ref().ok_or_else(|| {
Error::new(ErrorKind::Unexpected, "sftp writer has already been
closed")
})?;
+ let client = file.client();
- let mut chunks: Vec<Bytes> = bs.into_iter().collect();
- file.write_all_zero_copy(&mut chunks)
- .await
- .map_err(parse_sftp_error)?;
-
+ // A failed write keeps the offset, so a retry sends the same bytes to
+ // the same offsets.
+ self.offset = write_at(
+ &client.sftp,
+ file.handle(),
+ client.write_len,
+ self.offset,
+ bs,
+ )
+ .await?;
Ok(())
}
async fn close(&mut self) -> Result<Metadata> {
if let Some(file) = self.file.take() {
- let res = file.close().await.map_err(parse_sftp_error);
- self._conn = None;
- res?;
+ // The server releases the handle even when close fails, so a
retry cannot help.
+ file.close().await.map_err(Error::set_permanent)?;
Review Comment:
83a4121f2: the writer now has `Open`, `Closing`, and `Closed` states. A
close enters `Closing` before it waits, and only a confirmed close moves to
`Closed`. After a failed or cancelled close, `close()` returns an error and
`write()` is rejected. `failed_close_is_reported_again` covers the error case.
*This comment is AI assisted.*
##########
core/services/sftp/src/writer.rs:
##########
@@ -69,3 +81,148 @@ impl oio::Write for SftpWriter {
))
}
}
+
+/// Writes `bs` to the file at `offset` and returns the offset after it once
+/// the server has acknowledged every request.
+async fn write_at(
+ sftp: &RawSftpSession,
+ handle: &SftpHandle,
+ write_len: u32,
+ mut offset: u64,
+ bs: Buffer,
+) -> Result<u64> {
+ let mut pending: VecDeque<PendingWrite> =
VecDeque::with_capacity(MAX_PENDING_WRITES);
+ for bytes in bs {
+ for data in bytes.chunks(write_len as usize) {
+ if pending.len() == MAX_PENDING_WRITES
+ && let Some(ack) = pending.pop_front()
+ {
+ ack.await.map_err(parse_sftp_error)?;
+ }
+ pending.push_back(
+ sftp.write_nowait(handle, offset, data)
+ .map_err(parse_sftp_error)?,
+ );
+ offset += data.len() as u64;
+ }
+ }
+ for ack in pending {
+ ack.await.map_err(parse_sftp_error)?;
+ }
+ Ok(offset)
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::Arc;
+ use std::sync::Mutex;
+
+ use russh_sftp::protocol::{
+ FileAttributes, Handle, OpenFlags, SftpString, Status, StatusCode,
Version,
+ };
+ use russh_sftp::server::StatusReply;
+
+ use super::*;
+
+ const WRITE_LEN: u32 = 4;
+
+ /// Stores one file in memory and fails the third write request once.
+ struct FlakyServer {
+ file: Arc<Mutex<Vec<u8>>>,
+ writes: usize,
+ }
+
+ impl russh_sftp::server::Handler for FlakyServer {
+ type Error = StatusReply;
+
+ fn unimplemented(&self) -> Self::Error {
+ StatusCode::OpUnsupported.into()
+ }
+
+ async fn init(
+ &mut self,
+ _: u32,
+ _: std::collections::HashMap<String, String>,
+ ) -> std::result::Result<Version, Self::Error> {
+ Ok(Version::new())
+ }
+
+ async fn open(
+ &mut self,
+ id: u32,
+ _: SftpString,
+ _: OpenFlags,
+ _: FileAttributes,
+ ) -> std::result::Result<Handle, Self::Error> {
+ Ok(Handle {
+ id,
+ handle: SftpHandle::from("file"),
+ })
+ }
+
+ async fn write(
+ &mut self,
+ id: u32,
+ _: SftpHandle,
+ offset: u64,
+ data: Vec<u8>,
+ ) -> std::result::Result<Status, Self::Error> {
+ self.writes += 1;
+ if self.writes == 3 {
+ return Err(StatusCode::Failure.into());
+ }
+ let mut file = self.file.lock().unwrap();
+ let end = offset as usize + data.len();
+ if file.len() < end {
+ file.resize(end, 0);
+ }
+ file[offset as usize..end].copy_from_slice(&data);
+ Ok(Status {
+ id,
+ status_code: StatusCode::Ok,
+ error_message: String::new(),
+ language_tag: String::new(),
+ })
+ }
+ }
+
+ #[tokio::test]
+ async fn
retried_write_after_partial_acknowledgement_writes_each_byte_once() {
+ let (client, server) = tokio::io::duplex(64 * 1024);
+ let file = Arc::new(Mutex::new(Vec::new()));
+ russh_sftp::server::run(
+ server,
+ FlakyServer {
+ file: file.clone(),
+ writes: 0,
+ },
+ )
+ .await;
+ let sftp = RawSftpSession::new(client);
+ sftp.init().await.unwrap();
+ let handle = sftp
+ .open("file", OpenFlags::WRITE, FileAttributes::empty())
+ .await
+ .unwrap()
+ .handle;
+
+ let head = b"0123".to_vec();
+ let end = write_at(&sftp, &handle, WRITE_LEN, 0,
Buffer::from(head.clone()))
+ .await
+ .unwrap();
+ assert_eq!(end, 4);
+
+ // The server acknowledges the first request of this buffer and fails
the second.
+ let tail = b"abcdefghij".to_vec();
+ let err = write_at(&sftp, &handle, WRITE_LEN, end,
Buffer::from(tail.clone()))
Review Comment:
83a4121f2: the test now retries through the same `SftpWriter` against an
in-process russh server that fails the second packet of a 100 KB write once. It
checks the final file bytes. Advancing the writer's offset before `write_at`
makes it fail.
*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]