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 c5f382dbfe fix(integrations/unftp-sbe): keep missing modification 
times unknown in listings (#9088)
c5f382dbfe is described below

commit c5f382dbfe40bbdc076f7d5be3b55b99d469dc4a
Author: mola <[email protected]>
AuthorDate: Thu Nov 26 02:14:33 2026 +0800

    fix(integrations/unftp-sbe): keep missing modification times unknown in 
listings (#9088)
    
    * fix(integrations/unftp-sbe): report the Unix epoch when a backend has no 
modification time
    
    OpendalMetadata::modified returned an error when the OpenDAL metadata
    had no last_modified, as for directories on services::Memory. libunftp
    then lists the entry with a `--- -- --:--` date placeholder that
    `ls`-style parsers cannot read. OpenDAL's own ftp service (suppaftp)
    took the whole LIST line as the entry name and could not stat the
    directory it had just created.
    
    Report the Unix epoch instead, as the object_store integration does
    for backends without last_modified.
    
    
    * fix(integrations/unftp-sbe): keep missing modification times unknown in 
listings
    
    modified() returns an error when the backend reports no last_modified
    instead of reporting the Unix epoch. LIST and STAT render such entries
    as MLST fact lines with modify omitted, so clients still parse them
    and can stat directories. MDTM and MLST keep the missing-time behavior:
    MDTM fails and MLST omits modify.
    
    STAT of an empty directory now returns the directory entry itself,
    since list drops the directory entry from its own listing.
    
    * test(integrations/unftp-sbe): fix listing assertion spelling
    
    ---------
    
    Co-authored-by: Mola-maker <[email protected]>
    Co-authored-by: Xuanwo <[email protected]>
---
 integrations/unftp-sbe/src/lib.rs            |  99 ++++++++++++--
 integrations/unftp-sbe/tests/ftp_loopback.rs | 189 ++++++++++++++++++++++++++-
 2 files changed, 275 insertions(+), 13 deletions(-)

diff --git a/integrations/unftp-sbe/src/lib.rs 
b/integrations/unftp-sbe/src/lib.rs
index 3a2c24471c..0c92c367ce 100644
--- a/integrations/unftp-sbe/src/lib.rs
+++ b/integrations/unftp-sbe/src/lib.rs
@@ -60,7 +60,7 @@ use std::path::{Path, PathBuf};
 
 use opendal::Operator;
 use unftp_core::auth::UserDetail;
-use unftp_core::storage::{self, Error, StorageBackend};
+use unftp_core::storage::{self, Error, Metadata, StorageBackend};
 
 use futures::StreamExt;
 use tokio::io::AsyncReadExt;
@@ -99,13 +99,12 @@ impl storage::Metadata for OpendalMetadata {
     }
 
     fn modified(&self) -> storage::Result<std::time::SystemTime> {
-        match self.0.last_modified() {
-            Some(ts) => Ok(ts.into()),
-            None => Err(Error::new(
-                storage::ErrorKind::LocalError,
-                "no last modified time",
-            )),
-        }
+        // A backend that reports no modification time stays unknown here.
+        // Listing output renders such entries without a timestamp instead.
+        self.0
+            .last_modified()
+            .map(Into::into)
+            .ok_or_else(|| storage::ErrorKind::LocalError.into())
     }
 
     fn gid(&self) -> u32 {
@@ -128,6 +127,30 @@ fn convert_err(err: opendal::Error) -> Error {
     Error::new(kind, err)
 }
 
+/// Format one listing entry for `LIST` and `STAT`.
+///
+/// Entries with a known modification time use the `ls`-style line from
+/// [`storage::Fileinfo`]. Entries without one use the MLST fact line instead
+/// (`type=file;size=5; f.txt`, with `modify` omitted), so the line stays
+/// parseable without inventing a timestamp.
+fn format_entry(fi: &storage::Fileinfo<PathBuf, OpendalMetadata>) -> String {
+    if fi.metadata.modified().is_ok() {
+        return fi.to_string();
+    }
+
+    let kind = if fi.metadata.is_dir() {
+        "type=dir"
+    } else {
+        "type=file"
+    };
+    let name = fi
+        .path
+        .file_name()
+        .map(|name| name.to_string_lossy().into_owned())
+        .unwrap_or_default();
+    format!("{kind};size={}; {name}", fi.metadata.len())
+}
+
 /// Convert an FTP path into a lexically normalized OpenDAL path.
 ///
 /// Collapses `.` and `..` segments and clamps `..` at the FTP root (`/`).
@@ -306,6 +329,49 @@ impl<User: UserDetail> StorageBackend<User> for 
OpendalStorage {
         Ok(ret)
     }
 
+    async fn list_fmt<P: AsRef<Path> + Send + Debug>(
+        &self,
+        user: &User,
+        path: P,
+    ) -> storage::Result<std::io::Cursor<Vec<u8>>>
+    where
+        Self::Metadata: storage::Metadata + 'static,
+    {
+        let list = self.list(user, path).await?;
+        let mut buffer = String::new();
+        for fi in &list {
+            buffer.push_str(&format_entry(fi));
+            buffer.push_str("\r\n");
+        }
+        Ok(std::io::Cursor::new(buffer.into_bytes()))
+    }
+
+    async fn list_vec<P: AsRef<Path> + Send + Debug>(
+        &self,
+        user: &User,
+        path: P,
+    ) -> storage::Result<Vec<String>>
+    where
+        Self::Metadata: storage::Metadata + 'static,
+    {
+        let list = self.list(user, path.as_ref()).await?;
+        if !list.is_empty() {
+            return Ok(list.iter().map(format_entry).collect());
+        }
+        // `STAT` can name a single entry. An empty listing means the path
+        // names an empty directory, whose own entry `list` filters out.
+        // Fall back to the entry itself so the client can stat it.
+        if path.as_ref().file_name().is_none() {
+            return Ok(vec![]);
+        }
+        let metadata = self.metadata(user, path.as_ref()).await?;
+        let entry = storage::Fileinfo {
+            path: path.as_ref().to_path_buf(),
+            metadata,
+        };
+        Ok(vec![format_entry(&entry)])
+    }
+
     async fn get<P: AsRef<Path> + Send + Debug>(
         &self,
         _: &User,
@@ -547,6 +613,23 @@ impl<User: UserDetail> StorageBackend<User> for 
OpendalStorage {
 mod tests {
     use super::*;
 
+    #[test]
+    fn missing_last_modified_returns_error() {
+        let dir = OpendalMetadata(opendal::MetadataBuilder::dir().build());
+        assert!(dir.modified().is_err());
+        let file = OpendalMetadata(opendal::MetadataBuilder::file(5).build());
+        assert!(file.modified().is_err());
+    }
+
+    #[test]
+    fn known_last_modified_returns_time() {
+        let ts = opendal::raw::Timestamp::new(1_700_000_000, 0).unwrap();
+        let mut builder = opendal::MetadataBuilder::file(5);
+        builder.last_modified(ts);
+        let file = OpendalMetadata(builder.build());
+        assert_eq!(file.modified().unwrap(), std::time::SystemTime::from(ts));
+    }
+
     #[test]
     fn convert_err_maps_opendal_error_kinds() {
         let cases = [
diff --git a/integrations/unftp-sbe/tests/ftp_loopback.rs 
b/integrations/unftp-sbe/tests/ftp_loopback.rs
index 23917c0d89..7cb3c10188 100644
--- a/integrations/unftp-sbe/tests/ftp_loopback.rs
+++ b/integrations/unftp-sbe/tests/ftp_loopback.rs
@@ -17,12 +17,13 @@
 
 use std::fmt::Debug;
 use std::net::Ipv4Addr;
-use std::time::Duration;
+use std::time::{Duration, SystemTime};
 
 use anyhow::{Context, Result};
 use libunftp::ServerBuilder;
 use opendal::{Operator, services};
 use suppaftp::Status;
+use suppaftp::list::File;
 use suppaftp::tokio::AsyncFtpStream;
 use suppaftp::types::{FileType, FtpError, FtpResult};
 use tempfile::tempdir;
@@ -33,10 +34,11 @@ use unftp_sbe_opendal::OpendalStorage;
 
 const SESSION_TIMEOUT: Duration = Duration::from_secs(15);
 
-async fn with_ftp_client(test: impl AsyncFnOnce(&mut AsyncFtpStream) -> 
Result<()>) -> Result<()> {
-    let root = tempdir()?;
-    let fs = 
services::Fs::default().root(root.path().to_str().context("non-UTF-8 test 
root")?);
-    let storage = OpendalStorage::new(Operator::new(fs)?);
+async fn with_ftp_client_for(
+    op: Operator,
+    test: impl AsyncFnOnce(&mut AsyncFtpStream) -> Result<()>,
+) -> Result<()> {
+    let storage = OpendalStorage::new(op);
     let server = ServerBuilder::new(Box::new(move || storage.clone()))
         .passive_ports(0..=0)
         .build()?;
@@ -70,6 +72,31 @@ async fn with_ftp_client(test: impl AsyncFnOnce(&mut 
AsyncFtpStream) -> Result<(
     server_result.context("FTP server session timed out")?
 }
 
+async fn with_ftp_client(test: impl AsyncFnOnce(&mut AsyncFtpStream) -> 
Result<()>) -> Result<()> {
+    let root = tempdir()?;
+    let fs = 
services::Fs::default().root(root.path().to_str().context("non-UTF-8 test 
root")?);
+    with_ftp_client_for(Operator::new(fs)?, test).await
+}
+
+/// A modification time counts as real when it is within the last hour: the
+/// entry was just written, so a clock far from now means the server invented
+/// the time.
+fn is_recent(modified: SystemTime) -> bool {
+    SystemTime::now()
+        .duration_since(modified)
+        .is_ok_and(|elapsed| elapsed < Duration::from_secs(3600))
+}
+
+fn parse_list_lines(lines: &[String]) -> Result<Vec<File>> {
+    lines
+        .iter()
+        .map(|line| {
+            line.parse::<File>()
+                .with_context(|| format!("parse LIST line {line:?}"))
+        })
+        .collect()
+}
+
 async fn retrieve(ftp: &mut AsyncFtpStream, path: &str) -> Result<Vec<u8>> {
     let mut stream = ftp
         .retr_as_stream(path)
@@ -232,6 +259,158 @@ async fn restart_is_unsupported() -> Result<()> {
     .await
 }
 
+/// STAT replies frame each listing line with the reply code (`200-` on the
+/// first line, `200 ` on the last). Strip that framing so the lines parse
+/// like the raw LIST output on the data connection.
+fn stat_lines(body: &str) -> Vec<String> {
+    body.lines()
+        .map(|l| {
+            let b = l.as_bytes();
+            if b.len() >= 4
+                && b[..3].iter().all(|c| c.is_ascii_digit())
+                && (b[3] == b'-' || b[3] == b' ')
+            {
+                l[4..].to_string()
+            } else {
+                l.to_string()
+            }
+        })
+        .filter(|l| !l.is_empty())
+        .collect()
+}
+
+/// Entries without a modification time stay listable on Memory: files and
+/// directories written there carry no `last_modified`, so `LIST` and `STAT`
+/// must still parse, while `MDTM` and `MLST` must not invent a time.
+#[tokio::test]
+async fn missing_mtime_entries_on_memory() -> Result<()> {
+    let op = Operator::new(services::Memory::default())?;
+    op.write("f.txt", "hello").await?;
+    op.create_dir("d/").await?;
+    with_ftp_client_for(op, async |ftp| {
+        let lines = ftp.list(None).await.context("LIST")?;
+        let files = parse_list_lines(&lines)?;
+        assert_eq!(files.len(), 2, "LIST lines: {lines:?}");
+        let file = files
+            .iter()
+            .find(|f| f.name() == "f.txt")
+            .context("f.txt in LIST")?;
+        assert!(file.is_file());
+        assert_eq!(file.size(), 5);
+        let dir = files
+            .iter()
+            .find(|f| f.name() == "d")
+            .context("d in LIST")?;
+        assert!(dir.is_directory());
+        assert!(
+            lines
+                .iter()
+                .all(|line| !line.contains("1970") && !line.contains("--- -- 
--:--")),
+            "LIST lines must neither invent a time nor use the unparsable 
placeholder: {lines:?}"
+        );
+
+        for path in ["f.txt", "d"] {
+            let response = ftp
+                .custom_command(format!("STAT /{path}"), &[Status::CommandOk])
+                .await
+                .with_context(|| format!("STAT /{path}"))?;
+            let body = String::from_utf8_lossy(&response.body);
+            let name = path.trim_end_matches('/');
+            assert!(
+                stat_lines(&body)
+                    .iter()
+                    .any(|line| line.parse::<File>().is_ok_and(|f| f.name() == 
name)),
+                "STAT /{path} must return a parseable line for {name}: {body}"
+            );
+            assert!(
+                !body.contains("1970"),
+                "STAT /{path} must not invent a time: {body}"
+            );
+        }
+
+        assert_reply(ftp.mdtm("f.txt").await, Status::ActionAborted, "MDTM 
f.txt");
+        assert_reply(ftp.mdtm("d").await, Status::ActionAborted, "MDTM d");
+
+        for (path, kind) in [("f.txt", "type=file"), ("d", "type=dir")] {
+            let facts = ftp
+                .mlst(Some(path))
+                .await
+                .with_context(|| format!("MLST {path}"))?;
+            assert!(facts.contains(kind), "MLST {path} must say {kind}: 
{facts}");
+            assert!(
+                !facts.contains("modify="),
+                "MLST {path} must not invent a time: {facts}"
+            );
+        }
+
+        ftp.cwd("d").await.context("CWD d")?;
+        Ok(())
+    })
+    .await
+}
+
+/// Entries with a known modification time keep the `ls`-style listing and
+/// report their real time through `MDTM` and `MLST`.
+#[tokio::test]
+async fn known_mtime_entries_on_fs() -> Result<()> {
+    with_ftp_client(async |ftp| {
+        ftp.put_file("f.txt", &mut "hello".as_bytes())
+            .await
+            .context("STOR f.txt")?;
+        ftp.mkdir("d").await.context("MKD d")?;
+
+        let lines = ftp.list(None).await.context("LIST")?;
+        let files = parse_list_lines(&lines)?;
+        let file = files
+            .iter()
+            .find(|f| f.name() == "f.txt")
+            .context("f.txt in LIST")?;
+        assert!(file.is_file());
+        assert!(is_recent(file.modified()), "f.txt mtime must be recent");
+        let dir = files
+            .iter()
+            .find(|f| f.name() == "d")
+            .context("d in LIST")?;
+        assert!(dir.is_directory());
+        assert!(is_recent(dir.modified()), "d mtime must be recent");
+
+        let response = ftp
+            .custom_command("STAT /f.txt", &[Status::CommandOk])
+            .await
+            .context("STAT /f.txt")?;
+        let body = String::from_utf8_lossy(&response.body);
+        assert!(
+            stat_lines(&body).iter().any(|line| line
+                .parse::<File>()
+                .is_ok_and(|f| { f.name() == "f.txt" && 
is_recent(f.modified()) })),
+            "STAT /f.txt must return a parseable line with a recent time: 
{body}"
+        );
+
+        let mdtm = ftp.mdtm("f.txt").await.context("MDTM f.txt")?;
+        let mdtm_ts = mdtm.and_utc().timestamp() as u64;
+        let now = SystemTime::now()
+            .duration_since(SystemTime::UNIX_EPOCH)
+            .context("system time before epoch")?
+            .as_secs();
+        assert!(
+            now - mdtm_ts < 3600,
+            "MDTM f.txt must be recent, got {mdtm}"
+        );
+
+        let facts = ftp.mlst(Some("f.txt")).await.context("MLST f.txt")?;
+        assert!(
+            facts.contains("modify="),
+            "MLST f.txt must carry modify: {facts}"
+        );
+        assert!(
+            !facts.contains("modify=19700101000000"),
+            "MLST f.txt must not report the epoch: {facts}"
+        );
+        Ok(())
+    })
+    .await
+}
+
 #[tokio::test]
 async fn parent_traversal_delete_errors_and_dir_rename() -> Result<()> {
     with_ftp_client(async |ftp| {

Reply via email to