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

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

commit d36ca1c2cdafba04483171e23ff84159e143f31f
Author: Xuanwo <[email protected]>
AuthorDate: Wed Nov 25 22:00:29 2026 +0100

    feat(services/b2): add restore support
---
 core/services/b2/src/backend.rs      | 129 ++++++++++++++++++++++++++-
 core/services/b2/src/core.rs         | 164 +++++++++++++++++++++++++++++------
 core/services/b2/src/docs.md         |  13 +++
 core/tests/behavior/async_restore.rs |   2 +-
 website/data/capabilities.json       |   2 +
 5 files changed, 281 insertions(+), 29 deletions(-)

diff --git a/core/services/b2/src/backend.rs b/core/services/b2/src/backend.rs
index 6dcc005187..524d0c9f38 100644
--- a/core/services/b2/src/backend.rs
+++ b/core/services/b2/src/backend.rs
@@ -29,7 +29,7 @@ use super::core::B2Signer;
 use super::core::constants;
 use super::core::parse_error;
 use super::core::parse_file_info;
-use super::core::{B2Core, ErrorContext};
+use super::core::{B2Core, ErrorContext, FileVersionAction};
 use super::deleter::B2Deleter;
 use super::lister::B2Lister;
 use super::reader::*;
@@ -187,6 +187,8 @@ impl Builder for B2Builder {
 
                     delete: true,
                     copy: true,
+                    restore: true,
+                    restore_with_version: true,
 
                     list: true,
                     list_with_limit: true,
@@ -337,7 +339,10 @@ impl Service for B2Backend {
                 return Err(Error::new(ErrorKind::IsADirectory, "is a 
directory"));
             };
 
-            let resp = core.copy_file(&ctx, source_file_id, &to).await?;
+            let req = core
+                .copy_file_request(&ctx, &source_file_id, &to, Operation::Copy)
+                .await?;
+            let resp = core.send(&ctx, req).await?;
 
             let status = resp.status();
 
@@ -354,6 +359,126 @@ impl Service for B2Backend {
         }))
     }
 
+    async fn restore(
+        &self,
+        ctx: &OperationContext,
+        path: &str,
+        args: OpRestore,
+    ) -> Result<RpRestore> {
+        args.check(&self.capability())?;
+
+        let key = build_absolute_path(&self.core.root, path);
+        if let Some(version) = args.version() {
+            if version.is_empty() {
+                return Err(Error::new(
+                    ErrorKind::ConfigInvalid,
+                    "empty restore version ID",
+                ));
+            }
+            // A B2 file ID can name a version of a different file or bucket.
+            let source = self.core.get_file_version(ctx, version).await?;
+            if source.file_name != key
+                || source.bucket_id != self.core.bucket_id
+                || !matches!(
+                    source.action,
+                    FileVersionAction::Upload | FileVersionAction::Copy
+                )
+            {
+                return Err(Error::new(
+                    ErrorKind::NotFound,
+                    "no such data version for this path",
+                ));
+            }
+
+            let req = self
+                .core
+                .copy_file_request(ctx, version, path, Operation::Restore)
+                .await?;
+            // A lost copy response can otherwise cause a second promotion.
+            let resp = self
+                .core
+                .send(ctx, req)
+                .await
+                .map_err(Error::set_permanent)?;
+            return match resp.status() {
+                StatusCode::OK => Ok(RpRestore::new()),
+                status => Err(
+                    
parse_error(ErrorContext::new(ServiceOperation("CopyFile")), resp)
+                        .with_permanent(status.is_server_error()),
+                ),
+            };
+        }
+
+        let mut start_file_id = None;
+        let mut current_marker = None;
+        let marker = 'history: loop {
+            let page = self
+                .core
+                .list_file_versions(ctx, &key, start_file_id.as_deref())
+                .await?;
+            for file in page.files {
+                if file.file_name != key {
+                    break 'history None;
+                }
+                match file.action {
+                    FileVersionAction::Upload | FileVersionAction::Copy => {
+                        if current_marker.is_none() {
+                            return Ok(RpRestore::new());
+                        }
+                        break 'history current_marker;
+                    }
+                    FileVersionAction::Hide if current_marker.is_none() => {
+                        current_marker = Some(file.file_id);
+                    }
+                    FileVersionAction::Hide | FileVersionAction::Start => {}
+                }
+            }
+
+            // A hide marker can remain after all data versions are gone.
+            if page.next_file_name.as_deref() != Some(&key) {
+                break None;
+            }
+            start_file_id = Some(
+                page.next_file_id
+                    .filter(|next| !next.is_empty() && Some(next) != 
start_file_id.as_ref())
+                    .ok_or_else(|| {
+                        Error::new(ErrorKind::Unexpected, "version listing did 
not advance")
+                    })?,
+            );
+        };
+        let Some(marker) = marker else {
+            return Err(Error::new(
+                ErrorKind::NotFound,
+                "no live or recoverable version exists",
+            ));
+        };
+        if marker.is_empty() {
+            return Err(Error::new(
+                ErrorKind::Unexpected,
+                "current hide marker has no version ID",
+            ));
+        }
+
+        let req = self
+            .core
+            .delete_file_version_request(ctx, &key, &marker)
+            .await?;
+        // Replaying discovery after a lost delete response can remove another 
marker.
+        let resp = self
+            .core
+            .send(ctx, req)
+            .await
+            .map_err(Error::set_permanent)?;
+        match resp.status() {
+            StatusCode::OK => Ok(RpRestore::new()),
+            status => Err(parse_error(
+                ErrorContext::new(ServiceOperation("DeleteFileVersion")),
+                resp,
+            )
+            .with_permanent(status.is_server_error())),
+        }
+    }
+
     async fn rename(
         &self,
         _ctx: &OperationContext,
diff --git a/core/services/b2/src/core.rs b/core/services/b2/src/core.rs
index 07d2a93973..eecab74cae 100644
--- a/core/services/b2/src/core.rs
+++ b/core/services/b2/src/core.rs
@@ -595,40 +595,110 @@ impl B2Core {
         self.send(ctx, req).await
     }
 
-    pub async fn copy_file(
+    pub async fn list_file_versions(
         &self,
         ctx: &OperationContext,
-        source_file_id: String,
-        to: &str,
-    ) -> Result<Response<Buffer>> {
-        let to = build_absolute_path(&self.root, to);
-
+        key: &str,
+        start_file_id: Option<&str>,
+    ) -> Result<ListFileVersionsResponse> {
         let auth_info = self.get_auth_info(ctx).await?;
+        let body = ListFileVersionsRequest {
+            bucket_id: &self.bucket_id,
+            prefix: key,
+            max_file_count: 2,
+            start_file_name: start_file_id.map(|_| key),
+            start_file_id,
+        };
+        let body = 
serde_json::to_vec(&body).map_err(new_json_serialize_error)?;
+        let req = Request::post(format!(
+            "{}/b2api/v2/b2_list_file_versions",
+            auth_info.api_url
+        ))
+        .header(header::AUTHORIZATION, auth_info.authorization_token)
+        .header(header::CONTENT_TYPE, "application/json")
+        .extension(Operation::Restore)
+        .extension(ServiceOperation("ListFileVersions"))
+        .body(Buffer::from(body))
+        .map_err(new_request_build_error)?;
+        let resp = self.send(ctx, req).await?;
+        match resp.status() {
+            StatusCode::OK => 
serde_json::from_reader(resp.into_body().reader())
+                .map_err(new_json_deserialize_error)
+                .map_err(Error::set_temporary),
+            _ => Err(parse_error(
+                ErrorContext::new(ServiceOperation("ListFileVersions")),
+                resp,
+            )),
+        }
+    }
 
-        let url = format!("{}/b2api/v2/b2_copy_file", auth_info.api_url);
-
-        let mut req = Request::post(url);
-
-        req = req.header(header::AUTHORIZATION, auth_info.authorization_token);
+    pub async fn get_file_version(
+        &self,
+        ctx: &OperationContext,
+        file_id: &str,
+    ) -> Result<FileVersion> {
+        let auth_info = self.get_auth_info(ctx).await?;
+        let body = serde_json::json!({ "fileId": file_id });
+        let body = 
serde_json::to_vec(&body).map_err(new_json_serialize_error)?;
+        let req = Request::post(format!("{}/b2api/v2/b2_get_file_info", 
auth_info.api_url))
+            .header(header::AUTHORIZATION, auth_info.authorization_token)
+            .header(header::CONTENT_TYPE, "application/json")
+            .extension(Operation::Restore)
+            .extension(ServiceOperation("GetFileInfo"))
+            .body(Buffer::from(body))
+            .map_err(new_request_build_error)?;
+        let resp = self.send(ctx, req).await?;
+        match resp.status() {
+            StatusCode::OK => 
serde_json::from_reader(resp.into_body().reader())
+                .map_err(new_json_deserialize_error),
+            _ => Err(parse_error(
+                ErrorContext::new(ServiceOperation("GetFileInfo")),
+                resp,
+            )),
+        }
+    }
 
-        let req = req
-            .extension(Operation::Copy)
-            .extension(ServiceOperation("CopyFile"));
+    pub async fn delete_file_version_request(
+        &self,
+        ctx: &OperationContext,
+        key: &str,
+        file_id: &str,
+    ) -> Result<Request<Buffer>> {
+        let auth_info = self.get_auth_info(ctx).await?;
+        let body = serde_json::json!({ "fileName": key, "fileId": file_id });
+        let body = 
serde_json::to_vec(&body).map_err(new_json_serialize_error)?;
+        Request::post(format!(
+            "{}/b2api/v2/b2_delete_file_version",
+            auth_info.api_url
+        ))
+        .header(header::AUTHORIZATION, auth_info.authorization_token)
+        .header(header::CONTENT_TYPE, "application/json")
+        .extension(Operation::Restore)
+        .extension(ServiceOperation("DeleteFileVersion"))
+        .body(Buffer::from(body))
+        .map_err(new_request_build_error)
+    }
 
+    pub async fn copy_file_request(
+        &self,
+        ctx: &OperationContext,
+        source_file_id: &str,
+        to: &str,
+        operation: Operation,
+    ) -> Result<Request<Buffer>> {
+        let to = build_absolute_path(&self.root, to);
+        let auth_info = self.get_auth_info(ctx).await?;
         let body = CopyFileRequest {
             source_file_id,
             file_name: to,
         };
-
         let body = 
serde_json::to_vec(&body).map_err(new_json_serialize_error)?;
-        let body = bytes::Bytes::from(body);
-
-        // Set body
-        let req = req
+        Request::post(format!("{}/b2api/v2/b2_copy_file", auth_info.api_url))
+            .header(header::AUTHORIZATION, auth_info.authorization_token)
+            .extension(operation)
+            .extension(ServiceOperation("CopyFile"))
             .body(Buffer::from(body))
-            .map_err(new_request_build_error)?;
-
-        self.send(ctx, req).await
+            .map_err(new_request_build_error)
     }
 
     pub async fn hide_file(&self, ctx: &OperationContext, path: &str) -> 
Result<Response<Buffer>> {
@@ -800,6 +870,44 @@ pub struct ListFileNamesResponse {
     pub next_file_name: Option<String>,
 }
 
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct ListFileVersionsRequest<'a> {
+    bucket_id: &'a str,
+    prefix: &'a str,
+    max_file_count: usize,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    start_file_name: Option<&'a str>,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    start_file_id: Option<&'a str>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ListFileVersionsResponse {
+    pub files: Vec<FileVersion>,
+    pub next_file_name: Option<String>,
+    pub next_file_id: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FileVersion {
+    pub action: FileVersionAction,
+    pub bucket_id: String,
+    pub file_name: String,
+    pub file_id: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum FileVersionAction {
+    Upload,
+    Copy,
+    Hide,
+    Start,
+}
+
 /// Response of 
[b2-finish-large-file](https://www.backblaze.com/apidocs/b2-finish-large-file).
 #[derive(Debug, Clone, Deserialize)]
 #[serde(rename_all = "camelCase")]
@@ -831,6 +939,10 @@ pub(super) fn parse_file_info(file: &File) -> Metadata {
 
     let mut metadata = MetadataBuilder::file(file.content_length);
 
+    if let Some(file_id) = &file.file_id {
+        metadata.version(file_id);
+    }
+
     if let Some(content_md5) = &file.content_md5 {
         metadata.content_md5(content_md5);
     }
@@ -858,9 +970,9 @@ pub(super) fn parse_file_info(file: &File) -> Metadata {
 
 #[derive(Debug, Serialize)]
 #[serde(rename_all = "camelCase")]
-pub struct CopyFileRequest {
-    pub source_file_id: String,
-    pub file_name: String,
+struct CopyFileRequest<'a> {
+    source_file_id: &'a str,
+    file_name: String,
 }
 
 #[derive(Debug, Serialize)]
@@ -946,7 +1058,7 @@ pub(crate) fn parse_error(ctx: ErrorContext, resp: 
Response<Buffer>) -> Error {
 pub(crate) fn parse_b2_error_code(code: &str) -> Option<(ErrorKind, bool)> {
     match code {
         "already_hidden" => Some((ErrorKind::AlreadyExists, false)),
-        "no_such_file" => Some((ErrorKind::NotFound, false)),
+        "no_such_file" | "file_not_present" => Some((ErrorKind::NotFound, 
false)),
         _ => None,
     }
 }
diff --git a/core/services/b2/src/docs.md b/core/services/b2/src/docs.md
index 6d4ae7f63e..ba78bea1c3 100644
--- a/core/services/b2/src/docs.md
+++ b/core/services/b2/src/docs.md
@@ -9,12 +9,25 @@ Depending on its configuration and the backing system, this 
service can expose:
 - [x] delete
 - [x] list
 - [x] copy
+- [x] restore
 - [ ] rename
 - [x] presign
 
 Inspect the effective capability set with [`opendal_core::Operator::info`] and
 [`opendal_core::OperatorInfo::capability`] after building an operator.
 
+## Restore
+
+`restore(path)` removes one current B2 hide marker when a data version still
+exists for the path. A live file keeps its current version, and a path with no
+remaining data versions returns `NotFound`. The application key needs 
`listFiles`
+and `deleteFiles` permissions to remove the marker.
+
+`restore_with(path).version(file_id)` copies a data version of the same file to
+make it current. `stat` and `list` expose current file IDs through
+`Metadata::version()`. Version promotion requires `readFiles` and `writeFiles`
+and is subject to the [B2 Copy File size 
limit](https://www.backblaze.com/apidocs/b2-copy-file).
+
 ## Configuration
 
 Use [`crate::B2Config`] for serializable configuration and this builder's
diff --git a/core/tests/behavior/async_restore.rs 
b/core/tests/behavior/async_restore.rs
index 7bedf17f63..3dbf46ef76 100644
--- a/core/tests/behavior/async_restore.rs
+++ b/core/tests/behavior/async_restore.rs
@@ -33,7 +33,7 @@ pub fn tests(op: &Operator, tests: &mut Vec<Trial>) {
         ));
     }
 
-    if cap.restore && cap.restore_with_version && cap.read && cap.write && 
cap.stat_with_version {
+    if cap.restore && cap.restore_with_version && cap.read && cap.write && 
cap.stat {
         tests.extend(async_trials!(op, test_restore_with_version));
     }
 
diff --git a/website/data/capabilities.json b/website/data/capabilities.json
index 481fd01220..131fa9dcdb 100644
--- a/website/data/capabilities.json
+++ b/website/data/capabilities.json
@@ -981,6 +981,8 @@
         "presign_write": true,
         "read": true,
         "read_with_suffix": true,
+        "restore": true,
+        "restore_with_version": true,
         "shared": true,
         "stat": true,
         "write": true,

Reply via email to