This is an automated email from the ASF dual-hosted git repository.

Xuanwo pushed a commit to branch xuanwo/fix-dbfs-bugs
in repository https://gitbox.apache.org/repos/asf/opendal.git

commit e11d7806ff2f14bc237b2cf0aa19900857faf308
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 07:24:11 2026 +0100

    fix(services/dbfs): fix rename mkdirs target, root path trimming, stat 404, 
config, lister, and 429 error mapping
---
 core/Cargo.lock                   |   1 +
 core/services/dbfs/Cargo.toml     |   3 +-
 core/services/dbfs/src/backend.rs | 372 ++++++++++++++++++++++++++++++++++++--
 core/services/dbfs/src/core.rs    | 245 ++++++++++++++++++++++---
 core/services/dbfs/src/lister.rs  |  84 +++++++++
 5 files changed, 667 insertions(+), 38 deletions(-)

diff --git a/core/Cargo.lock b/core/Cargo.lock
index 920fe8bce5..9794299708 100644
--- a/core/Cargo.lock
+++ b/core/Cargo.lock
@@ -8223,6 +8223,7 @@ version = "0.59.5"
 dependencies = [
  "base64 0.23.1",
  "bytes",
+ "futures",
  "http 1.5.0",
  "log",
  "opendal-core",
diff --git a/core/services/dbfs/Cargo.toml b/core/services/dbfs/Cargo.toml
index 9371f12e38..b3bf1b80d3 100644
--- a/core/services/dbfs/Cargo.toml
+++ b/core/services/dbfs/Cargo.toml
@@ -41,4 +41,5 @@ serde = { workspace = true, features = ["derive"] }
 serde_json = { workspace = true }
 
 [dev-dependencies]
-tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+futures = { workspace = true }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] }
diff --git a/core/services/dbfs/src/backend.rs 
b/core/services/dbfs/src/backend.rs
index 597efd8f55..356913dd15 100644
--- a/core/services/dbfs/src/backend.rs
+++ b/core/services/dbfs/src/backend.rs
@@ -60,10 +60,11 @@ impl DbfsBuilder {
     /// - Azure: `https://adb-1234567890123456.78.azuredatabricks.net`
     /// - Aws: `https://dbc-123a5678-90bc.cloud.databricks.com`
     pub fn endpoint(mut self, endpoint: &str) -> Self {
+        let endpoint = endpoint.trim_end_matches('/');
         self.config.endpoint = if endpoint.is_empty() {
             None
         } else {
-            Some(endpoint.trim_end_matches('/').to_string())
+            Some(endpoint.to_string())
         };
         self
     }
@@ -88,20 +89,31 @@ impl Builder for DbfsBuilder {
         debug!("backend use root {root}");
 
         let endpoint = match &self.config.endpoint {
-            Some(endpoint) => Ok(endpoint.clone()),
-            None => Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is 
empty")
-                .with_operation("Builder::build")
-                .with_context("service", DBFS_SCHEME)),
-        }?;
+            Some(endpoint) => {
+                let endpoint = endpoint.trim_end_matches('/');
+                if endpoint.is_empty() {
+                    return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint 
is empty")
+                        .with_operation("Builder::build")
+                        .with_context("service", DBFS_SCHEME));
+                }
+                endpoint.to_string()
+            }
+            None => {
+                return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is 
empty")
+                    .with_operation("Builder::build")
+                    .with_context("service", DBFS_SCHEME));
+            }
+        };
         debug!("backend use endpoint: {}", endpoint);
 
         let token = match self.config.token {
-            Some(token) => token,
-            None => {
-                return Err(Error::new(
-                    ErrorKind::ConfigInvalid,
-                    "missing token for Dbfs",
-                ));
+            Some(token) if !token.is_empty() => token,
+            _ => {
+                return Err(
+                    Error::new(ErrorKind::ConfigInvalid, "missing token for 
Dbfs")
+                        .with_operation("Builder::build")
+                        .with_context("service", DBFS_SCHEME),
+                );
             }
         };
 
@@ -198,9 +210,6 @@ impl Service for DbfsBackend {
                 };
                 Ok(RpStat::new(meta.build()))
             }
-            StatusCode::NOT_FOUND if path.ends_with('/') => {
-                Ok(RpStat::new(MetadataBuilder::dir().build()))
-            }
             _ => Err(parse_error(
                 ErrorContext::new(ServiceOperation("GetStatus")),
                 resp,
@@ -305,3 +314,336 @@ struct DbfsStatus {
     file_size: i64,
     modification_time: i64,
 }
+
+#[cfg(test)]
+mod tests {
+    use std::time::Duration;
+
+    use http::Method;
+    use serde_json::Value;
+
+    use super::*;
+    use crate::core::test_support::RecordingTransport;
+
+    const TEST_TIMEOUT: Duration = Duration::from_secs(10);
+
+    #[test]
+    fn build_rejects_empty_endpoint_and_token() {
+        let invalid_configs = [
+            DbfsConfig {
+                endpoint: None,
+                token: Some("tok".to_string()),
+                root: None,
+            },
+            DbfsConfig {
+                endpoint: Some(String::new()),
+                token: Some("tok".to_string()),
+                root: None,
+            },
+            DbfsConfig {
+                endpoint: Some("///".to_string()),
+                token: Some("tok".to_string()),
+                root: None,
+            },
+            DbfsConfig {
+                endpoint: Some("https://example.databricks.com".to_string()),
+                token: None,
+                root: None,
+            },
+            DbfsConfig {
+                endpoint: Some("https://example.databricks.com".to_string()),
+                token: Some(String::new()),
+                root: None,
+            },
+        ];
+
+        for cfg in invalid_configs {
+            let err = cfg.into_builder().build().expect_err("config must 
fail");
+            assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+        }
+
+        let err = DbfsBuilder::default()
+            .endpoint("///")
+            .token("tok")
+            .build()
+            .expect_err("slash-only endpoint must fail");
+        assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+    }
+
+    #[tokio::test]
+    async fn build_trims_trailing_slash_from_config_endpoint() {
+        tokio::time::timeout(TEST_TIMEOUT, async {
+            let transport = RecordingTransport::new([(
+                StatusCode::OK,
+                
r#"{"is_dir":false,"file_size":3,"modification_time":1700000000000}"#,
+            )]);
+            let ctx = transport.context();
+
+            let backend = DbfsConfig {
+                endpoint: 
Some("https://example.databricks.com///".to_string()),
+                token: Some("tok".to_string()),
+                root: None,
+            }
+            .into_builder()
+            .build()
+            .unwrap();
+
+            backend
+                .stat(&ctx, "hello.txt", OpStat::default())
+                .await
+                .unwrap();
+
+            let reqs = transport.requests();
+            assert_eq!(reqs.len(), 1);
+            assert_eq!(
+                reqs[0].uri,
+                
"https://example.databricks.com/api/2.0/dbfs/get-status?path=/hello.txt";
+            );
+        })
+        .await
+        .expect("test timed out");
+    }
+
+    #[tokio::test]
+    async fn rename_ensures_parent_dir_not_destination_file() {
+        tokio::time::timeout(TEST_TIMEOUT, async {
+            let transport = RecordingTransport::new([
+                (
+                    StatusCode::NOT_FOUND,
+                    r#"{"error_code":"RESOURCE_DOES_NOT_EXIST","message":"not 
found"}"#,
+                ),
+                (StatusCode::OK, "{}"),
+                (StatusCode::OK, "{}"),
+            ]);
+            let ctx = transport.context();
+
+            let backend = DbfsBuilder::default()
+                .endpoint("https://example.databricks.com";)
+                .token("tok")
+                .root("/root")
+                .build()
+                .unwrap();
+
+            backend
+                .rename(&ctx, "a.txt", "dir/b.txt", OpRename::default())
+                .await
+                .unwrap();
+
+            let reqs = transport.requests();
+            assert_eq!(reqs.len(), 3);
+
+            assert_eq!(reqs[0].method, Method::GET);
+            assert_eq!(
+                reqs[0].uri,
+                
"https://example.databricks.com/api/2.0/dbfs/get-status?path=/root/dir";
+            );
+
+            assert_eq!(reqs[1].method, Method::POST);
+            assert_eq!(
+                reqs[1].uri,
+                "https://example.databricks.com/api/2.0/dbfs/mkdirs";
+            );
+            let mkdir_body: Value = 
serde_json::from_slice(&reqs[1].body).unwrap();
+            assert_eq!(mkdir_body["path"], "/root/dir");
+
+            assert_eq!(reqs[2].method, Method::POST);
+            assert_eq!(
+                reqs[2].uri,
+                "https://example.databricks.com/api/2.0/dbfs/move";
+            );
+            let move_body: Value = 
serde_json::from_slice(&reqs[2].body).unwrap();
+            assert_eq!(move_body["source_path"], "/root/a.txt");
+            assert_eq!(move_body["destination_path"], "/root/dir/b.txt");
+        })
+        .await
+        .expect("test timed out");
+    }
+
+    #[tokio::test]
+    async fn rename_skips_mkdirs_when_parent_already_exists() {
+        tokio::time::timeout(TEST_TIMEOUT, async {
+            let transport = RecordingTransport::new([
+                (
+                    StatusCode::OK,
+                    
r#"{"is_dir":true,"file_size":0,"modification_time":1700000000000}"#,
+                ),
+                (StatusCode::OK, "{}"),
+            ]);
+            let ctx = transport.context();
+
+            let backend = DbfsBuilder::default()
+                .endpoint("https://example.databricks.com";)
+                .token("tok")
+                .root("/root")
+                .build()
+                .unwrap();
+
+            backend
+                .rename(&ctx, "a.txt", "dir/b.txt", OpRename::default())
+                .await
+                .unwrap();
+
+            let reqs = transport.requests();
+            assert_eq!(reqs.len(), 2);
+            assert_eq!(reqs[0].method, Method::GET);
+            assert_eq!(
+                reqs[0].uri,
+                
"https://example.databricks.com/api/2.0/dbfs/get-status?path=/root/dir";
+            );
+            assert_eq!(reqs[1].method, Method::POST);
+            assert_eq!(
+                reqs[1].uri,
+                "https://example.databricks.com/api/2.0/dbfs/move";
+            );
+        })
+        .await
+        .expect("test timed out");
+    }
+
+    #[tokio::test]
+    async fn rename_skips_parent_check_when_root_and_parent_are_slash() {
+        tokio::time::timeout(TEST_TIMEOUT, async {
+            let transport = RecordingTransport::new([(StatusCode::OK, "{}")]);
+            let ctx = transport.context();
+
+            let backend = DbfsBuilder::default()
+                .endpoint("https://example.databricks.com";)
+                .token("tok")
+                .root("/")
+                .build()
+                .unwrap();
+
+            backend
+                .rename(&ctx, "a.txt", "b.txt", OpRename::default())
+                .await
+                .unwrap();
+
+            let reqs = transport.requests();
+            assert_eq!(reqs.len(), 1);
+            assert_eq!(reqs[0].method, Method::POST);
+            assert_eq!(
+                reqs[0].uri,
+                "https://example.databricks.com/api/2.0/dbfs/move";
+            );
+            let move_body: Value = 
serde_json::from_slice(&reqs[0].body).unwrap();
+            assert_eq!(move_body["source_path"], "/a.txt");
+            assert_eq!(move_body["destination_path"], "/b.txt");
+        })
+        .await
+        .expect("test timed out");
+    }
+
+    #[tokio::test]
+    async fn rename_ensures_configured_root_when_destination_is_at_root() {
+        tokio::time::timeout(TEST_TIMEOUT, async {
+            let transport = RecordingTransport::new([
+                (
+                    StatusCode::NOT_FOUND,
+                    r#"{"error_code":"RESOURCE_DOES_NOT_EXIST","message":"not 
found"}"#,
+                ),
+                (StatusCode::CREATED, "{}"),
+                (StatusCode::OK, "{}"),
+            ]);
+            let ctx = transport.context();
+
+            let backend = DbfsBuilder::default()
+                .endpoint("https://example.databricks.com";)
+                .token("tok")
+                .root("/root")
+                .build()
+                .unwrap();
+
+            backend
+                .rename(&ctx, "a.txt", "b.txt", OpRename::default())
+                .await
+                .unwrap();
+
+            let reqs = transport.requests();
+            assert_eq!(reqs.len(), 3);
+            assert_eq!(
+                reqs[0].uri,
+                
"https://example.databricks.com/api/2.0/dbfs/get-status?path=/root";
+            );
+            let mkdir_body: Value = 
serde_json::from_slice(&reqs[1].body).unwrap();
+            assert_eq!(mkdir_body["path"], "/root");
+            let move_body: Value = 
serde_json::from_slice(&reqs[2].body).unwrap();
+            assert_eq!(move_body["source_path"], "/root/a.txt");
+            assert_eq!(move_body["destination_path"], "/root/b.txt");
+        })
+        .await
+        .expect("test timed out");
+    }
+
+    #[tokio::test]
+    async fn rename_propagates_mkdirs_failure_without_calling_move() {
+        tokio::time::timeout(TEST_TIMEOUT, async {
+            let transport = RecordingTransport::new([
+                (
+                    StatusCode::NOT_FOUND,
+                    r#"{"error_code":"RESOURCE_DOES_NOT_EXIST","message":"not 
found"}"#,
+                ),
+                (
+                    StatusCode::INTERNAL_SERVER_ERROR,
+                    r#"{"error_code":"INTERNAL_ERROR","message":"mkdirs 
failed"}"#,
+                ),
+            ]);
+            let ctx = transport.context();
+
+            let backend = DbfsBuilder::default()
+                .endpoint("https://example.databricks.com";)
+                .token("tok")
+                .root("/root")
+                .build()
+                .unwrap();
+
+            let err = backend
+                .rename(&ctx, "a.txt", "dir/b.txt", OpRename::default())
+                .await
+                .unwrap_err();
+
+            assert_eq!(err.kind(), ErrorKind::Unexpected);
+            assert!(err.is_temporary());
+
+            let reqs = transport.requests();
+            assert_eq!(reqs.len(), 2);
+            assert_eq!(
+                reqs[1].uri,
+                "https://example.databricks.com/api/2.0/dbfs/mkdirs";
+            );
+        })
+        .await
+        .expect("test timed out");
+    }
+
+    #[tokio::test]
+    async fn stat_missing_trailing_slash_returns_not_found() {
+        tokio::time::timeout(TEST_TIMEOUT, async {
+            let transport = RecordingTransport::new([(
+                StatusCode::NOT_FOUND,
+                
r#"{"error_code":"RESOURCE_DOES_NOT_EXIST","message":"missing"}"#,
+            )]);
+            let ctx = transport.context();
+
+            let backend = DbfsBuilder::default()
+                .endpoint("https://example.databricks.com";)
+                .token("tok")
+                .build()
+                .unwrap();
+
+            // Root stat still succeeds without network calls.
+            let root_rp = backend.stat(&ctx, "/", 
OpStat::default()).await.unwrap();
+            assert_eq!(root_rp.into_metadata().mode(), EntryMode::DIR);
+            assert!(transport.requests().is_empty());
+
+            // Non-existent directory must return NotFound rather than 
fabricating a DIR.
+            let err = backend
+                .stat(&ctx, "missing/", OpStat::default())
+                .await
+                .unwrap_err();
+            assert_eq!(err.kind(), ErrorKind::NotFound);
+            assert_eq!(transport.requests().len(), 1);
+        })
+        .await
+        .expect("test timed out");
+    }
+}
diff --git a/core/services/dbfs/src/core.rs b/core/services/dbfs/src/core.rs
index ba82224fe4..c49978e119 100644
--- a/core/services/dbfs/src/core.rs
+++ b/core/services/dbfs/src/core.rs
@@ -47,6 +47,16 @@ impl Debug for DbfsCore {
 }
 
 impl DbfsCore {
+    fn dbfs_path(&self, path: &str) -> String {
+        let p = build_rooted_absolute_path(&self.root, path);
+        let trimmed = p.trim_end_matches('/');
+        if trimmed.is_empty() {
+            "/".to_string()
+        } else {
+            trimmed.to_string()
+        }
+    }
+
     pub async fn dbfs_create_dir(
         &self,
         ctx: &OperationContext,
@@ -58,9 +68,7 @@ impl DbfsCore {
         let auth_header_content = format!("Bearer {}", self.token);
         req = req.header(header::AUTHORIZATION, auth_header_content);
 
-        let p = build_rooted_absolute_path(&self.root, path)
-            .trim_end_matches('/')
-            .to_string();
+        let p = self.dbfs_path(path);
 
         let req_body = &json!({
             "path": p,
@@ -87,9 +95,7 @@ impl DbfsCore {
         let auth_header_content = format!("Bearer {}", self.token);
         req = req.header(header::AUTHORIZATION, auth_header_content);
 
-        let p = build_rooted_absolute_path(&self.root, path)
-            .trim_end_matches('/')
-            .to_string();
+        let p = self.dbfs_path(path);
 
         let request_body = &json!({
             "path": p,
@@ -140,9 +146,7 @@ impl DbfsCore {
     }
 
     pub async fn dbfs_list(&self, ctx: &OperationContext, path: &str) -> 
Result<Response<Buffer>> {
-        let p = build_rooted_absolute_path(&self.root, path)
-            .trim_end_matches('/')
-            .to_string();
+        let p = self.dbfs_path(path);
 
         let url = format!(
             "{}/api/2.0/dbfs/list?path={}",
@@ -191,9 +195,7 @@ impl DbfsCore {
         ctx: &OperationContext,
         path: &str,
     ) -> Result<Response<Buffer>> {
-        let p = build_rooted_absolute_path(&self.root, path)
-            .trim_end_matches('/')
-            .to_string();
+        let p = self.dbfs_path(path);
 
         let url = format!(
             "{}/api/2.0/dbfs/get-status?path={}",
@@ -216,21 +218,30 @@ impl DbfsCore {
     }
 
     pub async fn dbfs_ensure_parent_path(&self, ctx: &OperationContext, path: 
&str) -> Result<()> {
-        let resp = self.dbfs_get_status(ctx, path).await?;
+        let parent = get_parent(path);
+        if parent == "/" && self.root == "/" {
+            return Ok(());
+        }
+
+        let resp = self.dbfs_get_status(ctx, parent).await?;
 
         match resp.status() {
-            StatusCode::OK => return Ok(()),
+            StatusCode::OK => Ok(()),
             StatusCode::NOT_FOUND => {
-                self.dbfs_create_dir(ctx, path).await?;
-            }
-            _ => {
-                return Err(parse_error(
-                    ErrorContext::new(ServiceOperation("GetStatus")),
-                    resp,
-                ));
+                let resp = self.dbfs_create_dir(ctx, parent).await?;
+                match resp.status() {
+                    StatusCode::CREATED | StatusCode::OK => Ok(()),
+                    _ => Err(parse_error(
+                        ErrorContext::new(ServiceOperation("Mkdirs")),
+                        resp,
+                    )),
+                }
             }
+            _ => Err(parse_error(
+                ErrorContext::new(ServiceOperation("GetStatus")),
+                resp,
+            )),
         }
-        Ok(())
     }
 }
 
@@ -272,6 +283,7 @@ pub(crate) fn parse_error(ctx: ErrorContext, resp: 
Response<Buffer>) -> Error {
         StatusCode::NOT_FOUND => (ErrorKind::NotFound, false),
         StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => 
(ErrorKind::PermissionDenied, false),
         StatusCode::PRECONDITION_FAILED => (ErrorKind::ConditionNotMatch, 
false),
+        StatusCode::TOO_MANY_REQUESTS => (ErrorKind::RateLimited, true),
         StatusCode::INTERNAL_SERVER_ERROR
         | StatusCode::BAD_GATEWAY
         | StatusCode::SERVICE_UNAVAILABLE
@@ -295,3 +307,192 @@ pub(crate) fn parse_error(ctx: ErrorContext, resp: 
Response<Buffer>) -> Error {
 
     err
 }
+
+#[cfg(test)]
+pub(crate) mod test_support {
+    use std::collections::VecDeque;
+    use std::sync::Arc;
+    use std::sync::Mutex;
+
+    use bytes::Bytes;
+    use futures::stream;
+    use http::Method;
+    use http::Request;
+    use http::Response;
+    use http::StatusCode;
+    use opendal_core::Buffer;
+    use opendal_core::Error;
+    use opendal_core::ErrorKind;
+    use opendal_core::HttpBody;
+    use opendal_core::HttpTransport;
+    use opendal_core::HttpTransporter;
+    use opendal_core::OperationContext;
+    use opendal_core::Result;
+    use opendal_core::raw::new_request_build_error;
+
+    #[derive(Debug, Clone)]
+    pub(crate) struct RecordedRequest {
+        pub(crate) method: Method,
+        pub(crate) uri: String,
+        pub(crate) body: Bytes,
+    }
+
+    #[derive(Clone)]
+    pub(crate) struct RecordingTransport {
+        requests: Arc<Mutex<Vec<RecordedRequest>>>,
+        responses: Arc<Mutex<VecDeque<(StatusCode, String)>>>,
+    }
+
+    impl RecordingTransport {
+        pub(crate) fn new(
+            responses: impl IntoIterator<Item = (StatusCode, impl 
Into<String>)>,
+        ) -> Self {
+            let queue = responses
+                .into_iter()
+                .map(|(status, body)| (status, body.into()))
+                .collect();
+            Self {
+                requests: Arc::new(Mutex::new(Vec::new())),
+                responses: Arc::new(Mutex::new(queue)),
+            }
+        }
+
+        pub(crate) fn requests(&self) -> Vec<RecordedRequest> {
+            self.requests.lock().unwrap().clone()
+        }
+
+        pub(crate) fn context(&self) -> OperationContext {
+            
OperationContext::default().with_http_transport(HttpTransporter::new(self.clone()))
+        }
+    }
+
+    impl HttpTransport for RecordingTransport {
+        async fn fetch(&self, req: Request<Buffer>) -> 
Result<Response<HttpBody>> {
+            let (parts, body) = req.into_parts();
+            self.requests.lock().unwrap().push(RecordedRequest {
+                method: parts.method,
+                uri: parts.uri.to_string(),
+                body: body.to_bytes(),
+            });
+
+            let (status, resp_body) =
+                self.responses.lock().unwrap().pop_front().ok_or_else(|| {
+                    Error::new(
+                        ErrorKind::Unexpected,
+                        "unexpected extra HTTP request in mock transport",
+                    )
+                })?;
+
+            let payload = Buffer::from(resp_body);
+            let len = payload.len() as u64;
+            Response::builder()
+                .status(status)
+                .body(HttpBody::new(stream::iter([Ok(payload)]), Some(len)))
+                .map_err(new_request_build_error)
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use std::time::Duration;
+
+    use http::Method;
+    use serde_json::Value;
+
+    use super::test_support::RecordingTransport;
+    use super::*;
+
+    const TEST_TIMEOUT: Duration = Duration::from_secs(10);
+
+    #[tokio::test]
+    async fn root_path_operations_preserve_leading_slash() {
+        tokio::time::timeout(TEST_TIMEOUT, async {
+            let transport = RecordingTransport::new([
+                (StatusCode::OK, "{}"),
+                (StatusCode::OK, "{}"),
+                (StatusCode::OK, "{}"),
+                (StatusCode::OK, "{}"),
+            ]);
+            let ctx = transport.context();
+            let core = DbfsCore {
+                root: "/".to_string(),
+                endpoint: "https://example.databricks.com".to_string(),
+                token: "test-token".to_string(),
+            };
+
+            core.dbfs_create_dir(&ctx, "/").await.unwrap();
+            core.dbfs_delete(&ctx, "/").await.unwrap();
+            core.dbfs_list(&ctx, "/").await.unwrap();
+            core.dbfs_get_status(&ctx, "/").await.unwrap();
+
+            let reqs = transport.requests();
+            assert_eq!(reqs.len(), 4);
+
+            assert_eq!(reqs[0].method, Method::POST);
+            assert_eq!(
+                reqs[0].uri,
+                "https://example.databricks.com/api/2.0/dbfs/mkdirs";
+            );
+            let mkdir_body: Value = 
serde_json::from_slice(&reqs[0].body).unwrap();
+            assert_eq!(mkdir_body["path"], "/");
+
+            assert_eq!(reqs[1].method, Method::POST);
+            assert_eq!(
+                reqs[1].uri,
+                "https://example.databricks.com/api/2.0/dbfs/delete";
+            );
+            let delete_body: Value = 
serde_json::from_slice(&reqs[1].body).unwrap();
+            assert_eq!(delete_body["path"], "/");
+
+            assert_eq!(reqs[2].method, Method::GET);
+            assert_eq!(
+                reqs[2].uri,
+                "https://example.databricks.com/api/2.0/dbfs/list?path=/";
+            );
+
+            assert_eq!(reqs[3].method, Method::GET);
+            assert_eq!(
+                reqs[3].uri,
+                "https://example.databricks.com/api/2.0/dbfs/get-status?path=/";
+            );
+        })
+        .await
+        .expect("test timed out");
+    }
+
+    #[test]
+    fn dbfs_path_trims_non_root_trailing_slashes() {
+        let root_core = DbfsCore {
+            root: "/".to_string(),
+            endpoint: "https://example.databricks.com".to_string(),
+            token: "test-token".to_string(),
+        };
+        assert_eq!(root_core.dbfs_path("/"), "/");
+        assert_eq!(root_core.dbfs_path("dir/"), "/dir");
+        assert_eq!(root_core.dbfs_path("dir/file.txt"), "/dir/file.txt");
+
+        let sub_core = DbfsCore {
+            root: "/workspace/".to_string(),
+            endpoint: "https://example.databricks.com".to_string(),
+            token: "test-token".to_string(),
+        };
+        assert_eq!(sub_core.dbfs_path("/"), "/workspace");
+        assert_eq!(sub_core.dbfs_path("dir/"), "/workspace/dir");
+        assert_eq!(sub_core.dbfs_path("file.txt"), "/workspace/file.txt");
+    }
+
+    #[test]
+    fn parse_error_maps_too_many_requests_to_retryable_rate_limited() {
+        let resp = Response::builder()
+            .status(StatusCode::TOO_MANY_REQUESTS)
+            .body(Buffer::from(
+                r#"{"error_code":"REQUEST_LIMIT_EXCEEDED","message":"rate 
limit exceeded"}"#,
+            ))
+            .unwrap();
+
+        let err = 
parse_error(ErrorContext::new(ServiceOperation("GetStatus")), resp);
+        assert_eq!(err.kind(), ErrorKind::RateLimited);
+        assert!(err.is_temporary());
+    }
+}
diff --git a/core/services/dbfs/src/lister.rs b/core/services/dbfs/src/lister.rs
index cb19a00f74..dc65de51c2 100644
--- a/core/services/dbfs/src/lister.rs
+++ b/core/services/dbfs/src/lister.rs
@@ -81,6 +81,7 @@ impl oio::PageList for DbfsLister {
 
 #[derive(Debug, Deserialize)]
 struct DbfsOutputList {
+    #[serde(default)]
     files: Vec<DbfsStatus>,
 }
 
@@ -91,3 +92,86 @@ struct DbfsStatus {
     file_size: i64,
     modification_time: i64,
 }
+
+#[cfg(test)]
+mod tests {
+    use std::collections::VecDeque;
+    use std::time::Duration;
+
+    use opendal_core::raw::oio::PageList;
+
+    use super::*;
+    use crate::core::test_support::RecordingTransport;
+
+    const TEST_TIMEOUT: Duration = Duration::from_secs(10);
+
+    #[tokio::test]
+    async fn next_page_handles_empty_json_object_for_empty_dir() {
+        tokio::time::timeout(TEST_TIMEOUT, async {
+            let transport = RecordingTransport::new([(StatusCode::OK, "{}")]);
+            let ctx = transport.context();
+            let core = Arc::new(DbfsCore {
+                root: "/".to_string(),
+                endpoint: "https://example.databricks.com".to_string(),
+                token: "tok".to_string(),
+            });
+
+            let lister = DbfsLister::new(core, ctx, "/".to_string());
+            let mut page_ctx = oio::PageContext {
+                done: false,
+                token: String::new(),
+                entries: VecDeque::new(),
+            };
+            lister.next_page(&mut page_ctx).await.unwrap();
+
+            assert!(page_ctx.done);
+            assert!(page_ctx.entries.is_empty());
+
+            let reqs = transport.requests();
+            assert_eq!(reqs.len(), 1);
+            assert_eq!(
+                reqs[0].uri,
+                "https://example.databricks.com/api/2.0/dbfs/list?path=/";
+            );
+        })
+        .await
+        .expect("test timed out");
+    }
+
+    #[tokio::test]
+    async fn next_page_parses_files_and_dirs() {
+        tokio::time::timeout(TEST_TIMEOUT, async {
+            let body = r#"{
+                "files": [
+                    {"path": "/root/sub", "is_dir": true, "file_size": 0, 
"modification_time": 1700000000000},
+                    {"path": "/root/a.txt", "is_dir": false, "file_size": 42, 
"modification_time": 1700000001000}
+                ]
+            }"#;
+            let transport = RecordingTransport::new([(StatusCode::OK, body)]);
+            let ctx = transport.context();
+            let core = Arc::new(DbfsCore {
+                root: "/root/".to_string(),
+                endpoint: "https://example.databricks.com".to_string(),
+                token: "tok".to_string(),
+            });
+
+            let lister = DbfsLister::new(core, ctx, "/".to_string());
+            let mut page_ctx = oio::PageContext {
+                done: false,
+                token: String::new(),
+                entries: VecDeque::new(),
+            };
+            lister.next_page(&mut page_ctx).await.unwrap();
+
+            assert!(page_ctx.done);
+            assert_eq!(page_ctx.entries.len(), 2);
+            assert_eq!(page_ctx.entries[0].path(), "sub/");
+            assert_eq!(page_ctx.entries[0].metadata().mode(), EntryMode::DIR);
+            assert_eq!(page_ctx.entries[1].path(), "a.txt");
+            assert_eq!(page_ctx.entries[1].metadata().mode(), EntryMode::FILE);
+            assert_eq!(page_ctx.entries[1].metadata().content_length(), 42);
+        })
+        .await
+        .expect("test timed out");
+    }
+}

Reply via email to