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 bf000dd59f feat(services/gdrive): read binary files by revision ID
(#9309)
bf000dd59f is described below
commit bf000dd59f0a806fcaf521d8aa5ad5415eb8a034
Author: Xuanwo <[email protected]>
AuthorDate: Sat Nov 28 07:49:48 2026 +0800
feat(services/gdrive): read binary files by revision ID (#9309)
feat(services/gdrive): read binary file revisions
Expose the head revision from file metadata and route versioned reads
through the Drive revisions media endpoint.
Refs #2611
---
core/services/gdrive/src/backend.rs | 23 +++++++++++--------
core/services/gdrive/src/core.rs | 33 +++++++++++++++++++++-------
core/services/gdrive/src/docs.md | 9 ++++++++
core/services/gdrive/src/lister.rs | 1 +
core/services/gdrive/src/reader.rs | 44 ++++++++++++++-----------------------
website/data/capabilities.json | 1 +
6 files changed, 67 insertions(+), 44 deletions(-)
diff --git a/core/services/gdrive/src/backend.rs
b/core/services/gdrive/src/backend.rs
index 10bc46000f..b81b760f73 100644
--- a/core/services/gdrive/src/backend.rs
+++ b/core/services/gdrive/src/backend.rs
@@ -140,6 +140,7 @@ impl Builder for GdriveBuilder {
stat: true,
read: true,
+ read_with_version: true,
read_with_suffix: true,
list: true,
@@ -318,16 +319,20 @@ impl Service for GdriveBackend {
Ok(RpStat::new(metadata_from_gdrive_file(&gdrive_file)?))
}
fn read(&self, ctx: &OperationContext, path: &str, args: OpRead) ->
Result<Self::Reader> {
- let output: oio::StreamReader<GdriveReader> = {
- Ok(oio::StreamReader::new(GdriveReader::new(
- self.clone(),
- ctx.clone(),
- path,
- args,
- )))
- }?;
+ // These values cannot address a revision as a URL path segment.
+ if matches!(args.version(), Some("" | "." | "..")) {
+ return Err(Error::new(
+ ErrorKind::NotFound,
+ "invalid Google Drive revision ID",
+ ));
+ }
- Ok(output)
+ Ok(oio::StreamReader::new(GdriveReader::new(
+ self.clone(),
+ ctx.clone(),
+ path,
+ args,
+ )))
}
fn write(&self, ctx: &OperationContext, path: &str, _: OpWrite) ->
Result<Self::Writer> {
diff --git a/core/services/gdrive/src/core.rs b/core/services/gdrive/src/core.rs
index 8f5307ad96..ca7de2d4f1 100644
--- a/core/services/gdrive/src/core.rs
+++ b/core/services/gdrive/src/core.rs
@@ -244,10 +244,8 @@ impl GdriveCore {
ctx: &OperationContext,
file_id: &str,
) -> Result<Response<Buffer>> {
- // The file metadata in the Google Drive API is very complex.
- // For now, we only need the file id, name, mime type and modified
time.
let mut req = Request::get(format!(
-
"https://www.googleapis.com/drive/v3/files/{file_id}?fields=id,name,mimeType,size,modifiedTime&supportsAllDrives=true"
+
"https://www.googleapis.com/drive/v3/files/{file_id}?fields=id,name,mimeType,size,modifiedTime,headRevisionId&supportsAllDrives=true"
))
.extension(Operation::Stat)
.extension(ServiceOperation("GetFile"))
@@ -263,6 +261,7 @@ impl GdriveCore {
ctx: &OperationContext,
path: &str,
range: BytesRange,
+ version: Option<&str>,
) -> Result<Response<HttpBody>> {
let path = build_absolute_path(&self.root, path);
match self.recent_entry_for_path(&path).await {
@@ -287,9 +286,17 @@ impl GdriveCore {
},
};
- let url: String = format!(
-
"https://www.googleapis.com/drive/v3/files/{path_id}?alt=media&supportsAllDrives=true"
- );
+ let url = if let Some(revision_id) = version {
+ let file_id = percent_encode_path(&path_id).replace('/', "%2F");
+ let revision_id = percent_encode_path(revision_id).replace('/',
"%2F");
+ format!(
+
"https://www.googleapis.com/drive/v3/files/{file_id}/revisions/{revision_id}?alt=media"
+ )
+ } else {
+ format!(
+
"https://www.googleapis.com/drive/v3/files/{path_id}?alt=media&supportsAllDrives=true"
+ )
+ };
let mut req = Request::get(&url)
.extension(Operation::Read)
@@ -1039,6 +1046,7 @@ pub struct GdriveFile {
pub mime_type: String,
pub id: String,
pub name: String,
+ pub head_revision_id: Option<String>,
pub size: Option<String>,
// The modified time is not returned unless the `fields`
// query parameter contains `modifiedTime`.
@@ -1072,6 +1080,9 @@ pub(crate) fn metadata_from_gdrive_file(file:
&GdriveFile) -> Result<Metadata> {
MetadataBuilder::unknown()
};
metadata.content_type(file.mime_type.clone());
+ if let Some(revision_id) = &file.head_revision_id {
+ metadata.version(revision_id);
+ }
if let Some(modified_time) = &file.modified_time {
metadata.last_modified(modified_time.parse::<Timestamp>().map_err(|e| {
Error::new(ErrorKind::Unexpected, "parse last modified
time").set_source(e)
@@ -1256,6 +1267,7 @@ mod tests {
id: "file-id".to_string(),
name: "name".to_string(),
size: size.map(str::to_string),
+ head_revision_id: None,
modified_time: Some("2024-01-02T03:04:05.000Z".to_string()),
parents: vec![],
}
@@ -1272,16 +1284,21 @@ mod tests {
Some("application/vnd.google-apps.document")
);
assert!(metadata.last_modified().is_some());
+ assert_eq!(metadata.version(), None);
}
#[test]
- fn test_metadata_from_gdrive_file_with_size() {
- let file = gdrive_file("text/plain", Some("42"));
+ fn test_metadata_from_gdrive_file_with_revision() {
+ let file = serde_json::from_str(
+
r#"{"id":"file-id","name":"name","mimeType":"text/plain","size":"42","headRevisionId":"revision-id"}"#,
+ )
+ .unwrap();
let metadata = metadata_from_gdrive_file(&file).unwrap();
assert_eq!(metadata.mode(), EntryMode::FILE);
assert_eq!(metadata.content_length(), 42);
assert_eq!(metadata.content_type(), Some("text/plain"));
+ assert_eq!(metadata.version(), Some("revision-id"));
}
#[test]
diff --git a/core/services/gdrive/src/docs.md b/core/services/gdrive/src/docs.md
index b233f1babd..171621bcfb 100644
--- a/core/services/gdrive/src/docs.md
+++ b/core/services/gdrive/src/docs.md
@@ -5,6 +5,7 @@ Depending on its configuration and the backing system, this
service can expose:
- [x] create_dir
- [x] stat
- [x] read
+- [x] read_with_version
- [x] write
- [x] delete
- [x] list
@@ -23,6 +24,14 @@ modified match, falling back to the newer creation time if
needed.
Concurrent directory creation through an operator and its clones reuses work
for shared ancestors and allows independent paths to progress concurrently.
+### Binary file revisions
+
+For binary files, `stat` exposes the `headRevisionId` when Drive provides it.
+Pass that ID to the `version` option of a read to select that revision. Drive
+can purge older revisions and may require a revision to be marked Keep Forever
+before allowing its download. A missing revision returns `NotFound`. A download
+that Drive denies with HTTP 403 returns `PermissionDenied`.
+
### Resumable uploads and retries
Uploads up to 4 MiB use one request. Larger uploads use sequential resumable
diff --git a/core/services/gdrive/src/lister.rs
b/core/services/gdrive/src/lister.rs
index 7b9bff34a0..bae57f18d2 100644
--- a/core/services/gdrive/src/lister.rs
+++ b/core/services/gdrive/src/lister.rs
@@ -811,6 +811,7 @@ mod tests {
id: "dir-id".to_string(),
name: "dir".to_string(),
size: None,
+ head_revision_id: None,
modified_time: None,
parents: vec!["parent-id".to_string()],
})
diff --git a/core/services/gdrive/src/reader.rs
b/core/services/gdrive/src/reader.rs
index 45b02c5adc..47e0b82ed3 100644
--- a/core/services/gdrive/src/reader.rs
+++ b/core/services/gdrive/src/reader.rs
@@ -27,6 +27,7 @@ pub struct GdriveReader {
backend: GdriveBackend,
ctx: OperationContext,
path: String,
+ args: OpRead,
}
impl GdriveReader {
@@ -34,55 +35,44 @@ impl GdriveReader {
backend: GdriveBackend,
ctx: OperationContext,
path: &str,
- _: OpRead,
+ args: OpRead,
) -> Self {
Self {
backend,
ctx,
path: path.to_string(),
+ args,
}
}
}
impl oio::StreamRead for GdriveReader {
async fn open(&self, range: BytesRange) -> Result<(RpRead, Box<dyn
oio::ReadStreamDyn>)> {
- let backend = &self.backend;
+ let core = &self.backend.core;
let path = self.path.as_str();
- let abs_path = build_absolute_path(&backend.core.root, path);
- let resp = match backend.core.gdrive_get(&self.ctx, path, range).await
{
+ let abs_path = build_absolute_path(&core.root, path);
+ let version = self.args.version();
+ let resp = match core.gdrive_get(&self.ctx, path, range,
version).await {
Ok(resp) => resp,
Err(err) if err.kind() == ErrorKind::NotFound => {
- backend.core.refresh_path(&abs_path).await;
- backend.core.gdrive_get(&self.ctx, path, range).await?
+ core.refresh_path(&abs_path).await;
+ core.gdrive_get(&self.ctx, path, range, version).await?
}
Err(err) => return Err(err),
};
- let status = resp.status();
- let (rp, stream) = match status {
+ let resp = if resp.status() == StatusCode::NOT_FOUND {
+ core.refresh_path(&abs_path).await;
+ core.gdrive_get(&self.ctx, path, range, version).await?
+ } else {
+ resp
+ };
+
+ let (rp, stream) = match resp.status() {
StatusCode::OK | StatusCode::PARTIAL_CONTENT => (
RpRead::new(parse_into_metadata(path, resp.headers())?),
resp.into_body(),
),
- StatusCode::NOT_FOUND => {
- backend.core.refresh_path(&abs_path).await;
- let resp = backend.core.gdrive_get(&self.ctx, path,
range).await?;
- let status = resp.status();
- match status {
- StatusCode::OK | StatusCode::PARTIAL_CONTENT => (
- RpRead::new(parse_into_metadata(path,
resp.headers())?),
- resp.into_body(),
- ),
- _ => {
- let (part, mut body) = resp.into_parts();
- let buf = body.to_buffer().await?;
- return Err(parse_error(
-
ErrorContext::new(ServiceOperation("DownloadFile")),
- Response::from_parts(part, buf),
- ));
- }
- }
- }
_ => {
let (part, mut body) = resp.into_parts();
let buf = body.to_buffer().await?;
diff --git a/website/data/capabilities.json b/website/data/capabilities.json
index 6cc4e65497..7b0cdb52d9 100644
--- a/website/data/capabilities.json
+++ b/website/data/capabilities.json
@@ -1949,6 +1949,7 @@
"list_with_recursive": true,
"read": true,
"read_with_suffix": true,
+ "read_with_version": true,
"rename": true,
"shared": true,
"stat": true,