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 8760af37b1 fix(services/moka,services/mini_moka): filter lister 
snapshot by requested prefix (#8741)
8760af37b1 is described below

commit 8760af37b151911b2248e4740576a95f243c5711
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 06:36:29 2026 +0800

    fix(services/moka,services/mini_moka): filter lister snapshot by requested 
prefix (#8741)
    
    * fix(services/moka,services/mini_moka): filter lister snapshot by 
requested prefix
    
    Both MokaLister and MiniMokaLister ignored the requested path and
    snapshotted the entire cache. In recursive mode the wrapping
    HierarchyLister trusts the inner lister, so list("a/") also returned
    entries from sibling prefixes like "ab/" and "b/"; even
    non-recursive lists cloned every unrelated key.
    
    Build the absolute listing prefix with build_absolute_path and filter
    cache entries by it before collecting the snapshot. Also normalize the
    empty relative path to "/" in MiniMokaLister, matching MokaLister and
    MemoryLister.
    
    * test(services/moka,services/mini_moka): exercise raw Service::list in 
lister tests
    
    Under --all-features, opendal-core's auto-simulate makes Operator::new's
    SimulateLayer intercept recursive listing and synthesize directory
    entries, so the tests were non-deterministic across feature sets and
    could not detect a raw prefix-filtering regression. Drive
    Service::list/Service::write directly instead, and cover a stored root
    marker key in both crates.
---
 core/Cargo.lock                        |   1 +
 core/services/mini_moka/Cargo.toml     |   3 +
 core/services/mini_moka/src/backend.rs | 108 +++++++++++++++++++++++++++++++
 core/services/mini_moka/src/lister.rs  |  12 +++-
 core/services/moka/src/backend.rs      | 115 ++++++++++++++++++++++++++++++++-
 core/services/moka/src/lister.rs       |   5 +-
 6 files changed, 239 insertions(+), 5 deletions(-)

diff --git a/core/Cargo.lock b/core/Cargo.lock
index 1b5608bc54..49c99a4fe5 100644
--- a/core/Cargo.lock
+++ b/core/Cargo.lock
@@ -8339,6 +8339,7 @@ dependencies = [
  "mini-moka",
  "opendal-core",
  "serde",
+ "tokio",
 ]
 
 [[package]]
diff --git a/core/services/mini_moka/Cargo.toml 
b/core/services/mini_moka/Cargo.toml
index b69b83b4dd..62388f937e 100644
--- a/core/services/mini_moka/Cargo.toml
+++ b/core/services/mini_moka/Cargo.toml
@@ -36,3 +36,6 @@ log = { workspace = true }
 mini-moka = "0.10"
 opendal-core = { path = "../../core", version = "0.59.5", default-features = 
false }
 serde = { workspace = true, features = ["derive"] }
+
+[dev-dependencies]
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
diff --git a/core/services/mini_moka/src/backend.rs 
b/core/services/mini_moka/src/backend.rs
index ecded34320..d9468be1be 100644
--- a/core/services/mini_moka/src/backend.rs
+++ b/core/services/mini_moka/src/backend.rs
@@ -138,6 +138,7 @@ impl Builder for MiniMokaBuilder {
 #[cfg(test)]
 mod tests {
     use super::*;
+    use opendal_core::raw::oio::{List as _, Write as _};
 
     #[test]
     fn builder_preserves_subsecond_durations() {
@@ -150,6 +151,113 @@ mod tests {
         assert_eq!(builder.time_to_live, Some(time_to_live));
         assert_eq!(builder.time_to_idle, Some(time_to_idle));
     }
+
+    /// Write a file through the raw service so tests exercise `Service::list`
+    /// directly instead of `Operator` (which composes `SimulateLayer` under
+    /// `--all-features` and would mask prefix filtering regressions).
+    async fn write_file<S>(service: &S, ctx: &OperationContext, path: &str) -> 
Result<()>
+    where
+        S: Service,
+        S::Writer: oio::Write,
+    {
+        let mut writer = service.write(ctx, path, OpWrite::default())?;
+        writer.write(Buffer::from("x")).await?;
+        writer.close().await?;
+        Ok(())
+    }
+
+    async fn list_paths<S>(
+        service: &S,
+        ctx: &OperationContext,
+        path: &str,
+        recursive: bool,
+    ) -> Result<Vec<String>>
+    where
+        S: Service,
+        S::Lister: oio::List,
+    {
+        let args: OpList = options::ListOptions {
+            recursive,
+            ..Default::default()
+        }
+        .into();
+        let mut lister = service.list(ctx, path, args)?;
+
+        let mut paths = Vec::new();
+        while let Some(entry) = lister.next().await? {
+            paths.push(entry.path().to_string());
+        }
+        paths.sort_unstable();
+        Ok(paths)
+    }
+
+    #[tokio::test]
+    async fn recursive_list_only_returns_entries_under_prefix() -> Result<()> {
+        let service = MiniMokaBuilder::default().build()?;
+        let ctx = OperationContext::default();
+        for path in ["a/1", "a/nested/2", "ab/1", "b/1"] {
+            write_file(&service, &ctx, path).await?;
+        }
+
+        assert_eq!(
+            list_paths(&service, &ctx, "a/", true).await?,
+            ["a/1", "a/nested/2"]
+        );
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn recursive_list_only_returns_entries_under_prefix_with_root() -> 
Result<()> {
+        let service = MiniMokaBuilder::default().root("/sub").build()?;
+        let ctx = OperationContext::default();
+        for path in ["a/1", "a/nested/2", "ab/1", "b/1"] {
+            write_file(&service, &ctx, path).await?;
+        }
+
+        assert_eq!(
+            list_paths(&service, &ctx, "a/", true).await?,
+            ["a/1", "a/nested/2"]
+        );
+        assert_eq!(
+            list_paths(&service, &ctx, "/", true).await?,
+            ["a/1", "a/nested/2", "ab/1", "b/1"]
+        );
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn non_recursive_list_and_root_list_still_work() -> Result<()> {
+        let core = MiniMokaCore {
+            cache: mini_moka::sync::Cache::builder().build(),
+        };
+        let service = MiniMokaBackend::new(Arc::new(core), "/".to_string());
+        let ctx = OperationContext::default();
+        for path in ["a/1", "a/nested/2", "ab/1", "b/1"] {
+            write_file(&service, &ctx, path).await?;
+        }
+        // A stored root marker key "" must be reported as the "/" entry.
+        service.core.cache.insert(
+            String::new(),
+            MiniMokaValue {
+                metadata: MetadataBuilder::dir().build(),
+                content: Buffer::new(),
+            },
+        );
+
+        assert_eq!(
+            list_paths(&service, &ctx, "a/", false).await?,
+            ["a/1", "a/nested/"]
+        );
+        assert_eq!(
+            list_paths(&service, &ctx, "/", false).await?,
+            ["/", "a/", "ab/", "b/"]
+        );
+        assert_eq!(
+            list_paths(&service, &ctx, "/", true).await?,
+            ["/", "a/1", "a/nested/2", "ab/1", "b/1"]
+        );
+        Ok(())
+    }
 }
 
 #[derive(Debug, Clone)]
diff --git a/core/services/mini_moka/src/lister.rs 
b/core/services/mini_moka/src/lister.rs
index d41a562314..9f0f60f05f 100644
--- a/core/services/mini_moka/src/lister.rs
+++ b/core/services/mini_moka/src/lister.rs
@@ -29,10 +29,13 @@ pub struct MiniMokaLister {
 }
 
 impl MiniMokaLister {
-    pub fn new(core: Arc<MiniMokaCore>, root: String, _path: String) -> Self {
+    /// `path` is the absolute listing prefix inside the cache, built by the
+    /// backend with `build_absolute_path`.
+    pub fn new(core: Arc<MiniMokaCore>, root: String, path: String) -> Self {
         let entries: Vec<(String, Metadata)> = core
             .cache
             .iter()
+            .filter(|entry| entry.key().starts_with(path.as_str()))
             .map(|entry| (entry.key().to_string(), 
entry.value().metadata.clone()))
             .collect();
 
@@ -47,9 +50,12 @@ impl oio::List for MiniMokaLister {
     async fn next(&mut self) -> Result<Option<oio::Entry>> {
         match self.entries.next() {
             Some((key, metadata)) => {
-                let rel_path = build_relative_path(&self.root, &key);
+                let mut path = build_relative_path(&self.root, &key);
+                if path.is_empty() {
+                    path = "/".to_string();
+                }
 
-                Ok(Some(oio::Entry::new(&rel_path, metadata)))
+                Ok(Some(oio::Entry::new(&path, metadata)))
             }
             None => Ok(None),
         }
diff --git a/core/services/moka/src/backend.rs 
b/core/services/moka/src/backend.rs
index 925127cad9..264931ff4d 100644
--- a/core/services/moka/src/backend.rs
+++ b/core/services/moka/src/backend.rs
@@ -339,7 +339,8 @@ impl Service for MokaBackend {
         let output: oio::HierarchyLister<MokaLister> = {
             // For moka, we don't distinguish between files and directories
             // Just return the lister to iterate through all matching keys
-            let lister = MokaLister::new(self.core.clone(), self.root.clone(), 
path.to_string());
+            let p = build_absolute_path(&self.root, path);
+            let lister = MokaLister::new(self.core.clone(), self.root.clone(), 
p);
             let lister = oio::HierarchyLister::new(lister, path, 
args.recursive());
             Ok(lister)
         }?;
@@ -389,6 +390,7 @@ impl Service for MokaBackend {
 #[cfg(test)]
 mod tests {
     use super::*;
+    use opendal_core::raw::oio::{List as _, Write as _};
 
     #[test]
     fn builder_preserves_subsecond_durations() {
@@ -401,4 +403,115 @@ mod tests {
         assert_eq!(builder.time_to_live, Some(time_to_live));
         assert_eq!(builder.time_to_idle, Some(time_to_idle));
     }
+
+    /// Write a file through the raw service so tests exercise `Service::list`
+    /// directly instead of `Operator` (which composes `SimulateLayer` under
+    /// `--all-features` and would mask prefix filtering regressions).
+    async fn write_file<S>(service: &S, ctx: &OperationContext, path: &str) -> 
Result<()>
+    where
+        S: Service,
+        S::Writer: oio::Write,
+    {
+        let mut writer = service.write(ctx, path, OpWrite::default())?;
+        writer.write(Buffer::from("x")).await?;
+        writer.close().await?;
+        Ok(())
+    }
+
+    async fn list_paths<S>(
+        service: &S,
+        ctx: &OperationContext,
+        path: &str,
+        recursive: bool,
+    ) -> Result<Vec<String>>
+    where
+        S: Service,
+        S::Lister: oio::List,
+    {
+        let args: OpList = options::ListOptions {
+            recursive,
+            ..Default::default()
+        }
+        .into();
+        let mut lister = service.list(ctx, path, args)?;
+
+        let mut paths = Vec::new();
+        while let Some(entry) = lister.next().await? {
+            paths.push(entry.path().to_string());
+        }
+        paths.sort_unstable();
+        Ok(paths)
+    }
+
+    #[tokio::test]
+    async fn recursive_list_only_returns_entries_under_prefix() -> Result<()> {
+        let service = MokaBuilder::default().build()?;
+        let ctx = OperationContext::default();
+        for path in ["a/1", "a/nested/2", "ab/1", "b/1"] {
+            write_file(&service, &ctx, path).await?;
+        }
+
+        assert_eq!(
+            list_paths(&service, &ctx, "a/", true).await?,
+            ["a/1", "a/nested/2"]
+        );
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn recursive_list_only_returns_entries_under_prefix_with_root() -> 
Result<()> {
+        let service = MokaBuilder::default().root("/sub").build()?;
+        let ctx = OperationContext::default();
+        for path in ["a/1", "a/nested/2", "ab/1", "b/1"] {
+            write_file(&service, &ctx, path).await?;
+        }
+
+        assert_eq!(
+            list_paths(&service, &ctx, "a/", true).await?,
+            ["a/1", "a/nested/2"]
+        );
+        assert_eq!(
+            list_paths(&service, &ctx, "/", true).await?,
+            ["a/1", "a/nested/2", "ab/1", "b/1"]
+        );
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn non_recursive_list_and_root_list_still_work() -> Result<()> {
+        let core = MokaCore {
+            cache: moka::future::Cache::builder().max_capacity(10_000).build(),
+        };
+        let service = MokaBackend::new(core);
+        let ctx = OperationContext::default();
+        for path in ["a/1", "a/nested/2", "ab/1", "b/1"] {
+            write_file(&service, &ctx, path).await?;
+        }
+        // A stored root marker key "" must be reported as the "/" entry.
+        service
+            .core
+            .cache
+            .insert(
+                String::new(),
+                MokaValue {
+                    metadata: MetadataBuilder::dir().build(),
+                    content: Buffer::new(),
+                },
+            )
+            .await;
+
+        assert_eq!(
+            list_paths(&service, &ctx, "a/", false).await?,
+            ["a/1", "a/nested/"]
+        );
+        assert_eq!(
+            list_paths(&service, &ctx, "/", false).await?,
+            ["/", "a/", "ab/", "b/"]
+        );
+        assert_eq!(
+            list_paths(&service, &ctx, "/", true).await?,
+            ["/", "a/1", "a/nested/2", "ab/1", "b/1"]
+        );
+        Ok(())
+    }
 }
diff --git a/core/services/moka/src/lister.rs b/core/services/moka/src/lister.rs
index 9fa80aa9ee..636e83a49f 100644
--- a/core/services/moka/src/lister.rs
+++ b/core/services/moka/src/lister.rs
@@ -29,10 +29,13 @@ pub struct MokaLister {
 }
 
 impl MokaLister {
-    pub fn new(core: Arc<MokaCore>, root: String, _path: String) -> Self {
+    /// `path` is the absolute listing prefix inside the cache, built by the
+    /// backend with `build_absolute_path`.
+    pub fn new(core: Arc<MokaCore>, root: String, path: String) -> Self {
         let entries: Vec<(String, Metadata)> = core
             .cache
             .iter()
+            .filter(|(key, _)| key.starts_with(path.as_str()))
             .map(|(key, value)| (key.to_string(), value.metadata.clone()))
             .collect();
 

Reply via email to