This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new d22359946f fix(integrations/unftp-sbe): scope rmd deletion and abort
failed puts (#8763)
d22359946f is described below
commit d22359946f8894492b36178b9e9ee3522c80cec3
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 08:44:19 2026 +0800
fix(integrations/unftp-sbe): scope rmd deletion and abort failed puts
(#8763)
`rmd` passed the directory path to recursive deletion without a trailing
slash. Prefix-based services such as memory then also removed siblings
sharing the prefix, for example deleting `d` removed `dd/b`. Reject the
FTP root, validate that the target is a directory, and delete `d/` so
only that directory is removed.
`put` unconditionally shut down the writer after copying, so a read or
write failure still committed the bytes copied so far over an existing
object. Abort the writer on copy failure instead, and report an abort
failure without hiding the original error.
Add regression tests for sibling preservation, root and non-directory
paths, and aborted puts on memory and staged filesystem writes.
---
integrations/unftp-sbe/src/lib.rs | 102 +++++++++-----
integrations/unftp-sbe/tests/storage_backend.rs | 171 ++++++++++++++++++++++++
2 files changed, 242 insertions(+), 31 deletions(-)
diff --git a/integrations/unftp-sbe/src/lib.rs
b/integrations/unftp-sbe/src/lib.rs
index af9cacc15e..389ddc267a 100644
--- a/integrations/unftp-sbe/src/lib.rs
+++ b/integrations/unftp-sbe/src/lib.rs
@@ -64,8 +64,7 @@ use unftp_core::storage::{self, Error, StorageBackend};
use futures::StreamExt;
use tokio::io::AsyncReadExt;
-use tokio::io::AsyncWriteExt;
-use tokio_util::compat::{FuturesAsyncReadCompatExt,
FuturesAsyncWriteCompatExt};
+use tokio_util::compat::FuturesAsyncReadCompatExt;
#[derive(Debug, Clone)]
pub struct OpendalStorage {
@@ -137,22 +136,50 @@ fn convert_path(path: &Path) -> storage::Result<&str> {
})
}
-async fn copy_read_write_loop<R, W>(input: &mut R, output: &mut W) ->
std::io::Result<u64>
+async fn copy_read_write_loop<R>(
+ input: &mut R,
+ output: &mut opendal::Writer,
+) -> storage::Result<u64>
where
R: tokio::io::AsyncRead + Unpin + ?Sized,
- W: tokio::io::AsyncWrite + Unpin + ?Sized,
{
+ const COPY_BUFFER_SIZE: usize = 256 * 1024;
+
let mut copied = 0u64;
- let mut buf = [0u8; 8 * 1024];
+ let mut buf = vec![0u8; COPY_BUFFER_SIZE];
+ let mut filled = 0;
loop {
- let n = input.read(&mut buf).await?;
+ let n = input.read(&mut buf[filled..]).await.map_err(|err| {
+ Error::new(
+ storage::ErrorKind::LocalError,
+ format!("Failed to read data: {err}"),
+ )
+ })?;
if n == 0 {
+ if filled > 0 {
+ output.write(buf[..filled].to_vec()).await.map_err(|err| {
+ Error::new(
+ storage::ErrorKind::LocalError,
+ format!("Failed to write data: {err}"),
+ )
+ })?;
+ copied += filled as u64;
+ }
return Ok(copied);
}
- output.write_all(&buf[..n]).await?;
- copied += n as u64;
+ filled += n;
+ if filled == buf.len() {
+ output.write(buf[..filled].to_vec()).await.map_err(|err| {
+ Error::new(
+ storage::ErrorKind::LocalError,
+ format!("Failed to write data: {err}"),
+ )
+ })?;
+ copied += filled as u64;
+ filled = 0;
+ }
}
}
@@ -266,27 +293,24 @@ impl<User: UserDetail> StorageBackend<User> for
OpendalStorage {
}
.map_err(convert_err)?;
- let mut w = writer.into_futures_async_write().compat_write();
- // Avoid `tokio::io::copy`'s pending-read flush path and keep
buffering policy explicit.
- let copy_result = copy_read_write_loop(&mut input, &mut w).await;
- let shutdown_result = w.shutdown().await;
- match (copy_result, shutdown_result) {
- (Ok(len), Ok(())) => Ok(len),
- (Err(copy_err), Ok(())) => Err(Error::new(
- storage::ErrorKind::LocalError,
- format!("Failed to copy data: {}", copy_err),
- )),
- (Ok(_), Err(shutdown_err)) => Err(Error::new(
- storage::ErrorKind::LocalError,
- format!("Failed to shutdown writer: {}", shutdown_err),
- )),
- (Err(copy_err), Err(shutdown_err)) => Err(Error::new(
- storage::ErrorKind::LocalError,
- format!(
- "Failed to copy data: {} AND failed to shutdown writer:
{}",
- copy_err, shutdown_err
- ),
- )),
+ let mut writer = writer;
+ match copy_read_write_loop(&mut input, &mut writer).await {
+ Ok(len) => {
+ writer.close().await.map_err(convert_err)?;
+ Ok(len)
+ }
+ Err(copy_err) => {
+ // The writer is still open, so abort it to discard buffered
+ // and uploaded data. Some services do not support abort;
+ // report that failure without hiding the original error.
+ match writer.abort().await {
+ Ok(()) => Err(copy_err),
+ Err(abort_err) => Err(Error::new(
+ copy_err.kind(),
+ format!("{copy_err} AND failed to abort writer:
{abort_err}"),
+ )),
+ }
+ }
}
}
@@ -315,9 +339,25 @@ impl<User: UserDetail> StorageBackend<User> for
OpendalStorage {
self.op.rename(from, to).await.map_err(convert_err)
}
- async fn rmd<P: AsRef<Path> + Send + Debug>(&self, _: &User, path: P) ->
storage::Result<()> {
+ async fn rmd<P: AsRef<Path> + Send + Debug>(
+ &self,
+ user: &User,
+ path: P,
+ ) -> storage::Result<()> {
+ let path = opendal::raw::normalize_path(convert_path(path.as_ref())?);
+ if path == "/" {
+ return Err(Error::new(
+ storage::ErrorKind::PermissionDenied,
+ "cannot remove the FTP root directory",
+ ));
+ }
+
+ // Recursive deletion without a trailing slash is a prefix match on
+ // services such as memory and can remove siblings like `dd/`.
+ let directory = format!("{}/", path.trim_end_matches('/'));
+ self.cwd(user, directory.as_str()).await?;
self.op
- .delete_with(convert_path(path.as_ref())?)
+ .delete_with(&directory)
.recursive(true)
.await
.map_err(convert_err)
diff --git a/integrations/unftp-sbe/tests/storage_backend.rs
b/integrations/unftp-sbe/tests/storage_backend.rs
index 5b4a324b04..6a5341c66e 100644
--- a/integrations/unftp-sbe/tests/storage_backend.rs
+++ b/integrations/unftp-sbe/tests/storage_backend.rs
@@ -15,12 +15,16 @@
// specific language governing permissions and limitations
// under the License.
+use std::io;
+use std::pin::Pin;
use std::sync::Arc;
+use std::task::{Context as TaskContext, Poll};
use anyhow::{Context, Result};
use opendal::raw::{self, oio};
use opendal::{OperationContext, Operator, services};
use tempfile::TempDir;
+use tokio::io::{AsyncRead, ReadBuf};
use unftp_core::auth::DefaultUser;
use unftp_core::storage::{ErrorKind, StorageBackend};
use unftp_sbe_opendal::OpendalStorage;
@@ -188,6 +192,27 @@ async fn read_file(storage: &OpendalStorage, path: &str)
-> Result<String> {
Ok(content)
}
+/// An input that yields `remaining` bytes and then fails, to exercise aborted
puts.
+struct FailingReader {
+ remaining: usize,
+}
+
+impl AsyncRead for FailingReader {
+ fn poll_read(
+ mut self: Pin<&mut Self>,
+ _cx: &mut TaskContext<'_>,
+ buf: &mut ReadBuf<'_>,
+ ) -> Poll<io::Result<()>> {
+ if self.remaining == 0 {
+ return Poll::Ready(Err(io::Error::other("injected read failure")));
+ }
+ let n = self.remaining.min(buf.remaining());
+ buf.put_slice(&vec![b'x'; n]);
+ self.remaining -= n;
+ Poll::Ready(Ok(()))
+ }
+}
+
/// `start_pos == 0` stores the input verbatim, whether the file exists or not.
#[tokio::test]
async fn put_overwrites_at_start_position_zero() -> Result<()> {
@@ -281,6 +306,152 @@ async fn put_rejects_offset_on_non_append_backend() ->
Result<()> {
Ok(())
}
+/// A read failure after data was written must abort the writer instead of
+/// committing a truncated object.
+#[tokio::test]
+async fn put_read_error_preserves_existing_content() -> Result<()> {
+ let storage =
OpendalStorage::new(Operator::new(services::Memory::default())?);
+ let user = DefaultUser;
+
+ storage
+ .put(&user, "old".as_bytes(), "file", 0)
+ .await
+ .context("put old")?;
+
+ let err = storage
+ .put(
+ &user,
+ FailingReader {
+ remaining: 300 * 1024,
+ },
+ "file",
+ 0,
+ )
+ .await
+ .expect_err("put must fail when the input read fails");
+ assert_eq!(err.kind(), ErrorKind::LocalError);
+ assert_eq!(read_file(&storage, "file").await?, "old");
+ Ok(())
+}
+
+/// A failed put must not leave a partial object behind when none existed.
+#[tokio::test]
+async fn put_read_error_does_not_create_file() -> Result<()> {
+ let storage =
OpendalStorage::new(Operator::new(services::Memory::default())?);
+ let user = DefaultUser;
+
+ let err = storage
+ .put(
+ &user,
+ FailingReader {
+ remaining: 300 * 1024,
+ },
+ "file",
+ 0,
+ )
+ .await
+ .expect_err("put must fail when the input read fails");
+ assert_eq!(err.kind(), ErrorKind::LocalError);
+ assert!(storage.metadata(&user, "file").await.is_err());
+ Ok(())
+}
+
+/// Filesystem writes can abort cleanly when they are staged for atomic commit.
+#[tokio::test]
+async fn put_read_error_preserves_existing_content_on_fs() -> Result<()> {
+ let temp = tempfile::tempdir()?;
+ let root = temp.path().join("root");
+ let staging = temp.path().join("staging");
+ std::fs::create_dir(&root)?;
+ std::fs::create_dir(&staging)?;
+ let fs = services::Fs::default()
+ .root(root.to_str().context("non-UTF-8 test root")?)
+ .atomic_write_dir(staging.to_str().context("non-UTF-8 staging dir")?);
+ let storage = OpendalStorage::new(Operator::new(fs)?);
+ let user = DefaultUser;
+
+ storage
+ .put(&user, "old".as_bytes(), "file", 0)
+ .await
+ .context("put old")?;
+
+ let err = storage
+ .put(
+ &user,
+ FailingReader {
+ remaining: 300 * 1024,
+ },
+ "file",
+ 0,
+ )
+ .await
+ .expect_err("put must fail when the input read fails");
+ assert_eq!(err.kind(), ErrorKind::LocalError);
+ assert_eq!(read_file(&storage, "file").await?, "old");
+ Ok(())
+}
+
+/// `rmd` must delete only the named directory. A prefix-based service would
+/// otherwise also remove siblings such as `dd/`.
+#[tokio::test]
+async fn rmd_deletes_only_the_named_directory() -> Result<()> {
+ let storage =
OpendalStorage::new(Operator::new(services::Memory::default())?);
+ let user = DefaultUser;
+
+ for (path, content) in [("d/a", "a"), ("d/sub/x", "x"), ("dd/b", "b")] {
+ storage
+ .put(&user, content.as_bytes(), path, 0)
+ .await
+ .with_context(|| format!("put {path}"))?;
+ }
+
+ storage.rmd(&user, "d").await.context("rmd d")?;
+
+ assert!(storage.metadata(&user, "d/a").await.is_err());
+ assert!(storage.metadata(&user, "d/sub/x").await.is_err());
+ assert_eq!(read_file(&storage, "dd/b").await?, "b");
+
+ // A trailing slash identifies the same directory and remains scoped.
+ storage
+ .put(&user, "a".as_bytes(), "d/a", 0)
+ .await
+ .context("restore d/a")?;
+ storage.rmd(&user, "d/").await.context("rmd d/")?;
+ assert!(storage.metadata(&user, "d/a").await.is_err());
+ assert_eq!(read_file(&storage, "dd/b").await?, "b");
+ Ok(())
+}
+
+#[tokio::test]
+async fn rmd_rejects_root_missing_and_file_paths() -> Result<()> {
+ let storage =
OpendalStorage::new(Operator::new(services::Memory::default())?);
+ let user = DefaultUser;
+
+ storage
+ .put(&user, "keep".as_bytes(), "file", 0)
+ .await
+ .context("put file")?;
+
+ for path in ["/", ""] {
+ let err = storage
+ .rmd(&user, path)
+ .await
+ .expect_err("rmd of the root must fail");
+ assert_eq!(err.kind(), ErrorKind::PermissionDenied);
+ }
+
+ for path in ["missing", "file"] {
+ let err = storage
+ .rmd(&user, path)
+ .await
+ .expect_err("rmd of a non-directory must fail");
+ assert_eq!(err.kind(), ErrorKind::PermanentDirectoryNotAvailable);
+ }
+
+ assert_eq!(read_file(&storage, "file").await?, "keep");
+ Ok(())
+}
+
#[tokio::test]
async fn cwd_on_filesystem_backend() -> Result<()> {
let (_root, storage) = fs_storage()?;