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 e222e7ea2e fix(services/gridfs): prevent overwrite data loss and fix
revision and URI bugs (#9009)
e222e7ea2e is described below
commit e222e7ea2e1a87fd8342438e62fc1f1e2db09462
Author: Xuanwo <[email protected]>
AuthorDate: Wed Nov 25 14:13:07 2026 +0800
fix(services/gridfs): prevent overwrite data loss and fix revision and URI
bugs (#9009)
* fix(services/gridfs): fix overwrite ordering, config validation, dir
metadata, and error mapping
* Trim GridFS audit changes to verified fixes
---
core/services/gridfs/Cargo.toml | 2 +-
core/services/gridfs/src/backend.rs | 94 ++++++---
core/services/gridfs/src/config.rs | 171 +++++++++++++++-
core/services/gridfs/src/core.rs | 125 +++++++++---
core/services/gridfs/tests/gridfs.rs | 377 +++++++++++++++++++++++++++++++++++
5 files changed, 701 insertions(+), 68 deletions(-)
diff --git a/core/services/gridfs/Cargo.toml b/core/services/gridfs/Cargo.toml
index eceb192bda..4913cd29f5 100644
--- a/core/services/gridfs/Cargo.toml
+++ b/core/services/gridfs/Cargo.toml
@@ -39,4 +39,4 @@ opendal-core = { path = "../../core", version = "0.59.5",
default-features = fal
serde = { workspace = true, features = ["derive"] }
[dev-dependencies]
-tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] }
diff --git a/core/services/gridfs/src/backend.rs
b/core/services/gridfs/src/backend.rs
index b298b91faa..e56191164c 100644
--- a/core/services/gridfs/src/backend.rs
+++ b/core/services/gridfs/src/backend.rs
@@ -111,38 +111,33 @@ impl Builder for GridfsBuilder {
type Config = GridfsConfig;
fn build(self) -> Result<impl Service> {
- let conn = match &self.config.connection_string.clone() {
- Some(v) => v.clone(),
- None => {
- return Err(
- Error::new(ErrorKind::ConfigInvalid, "connection_string is
required")
- .with_context("service", GRIDFS_SCHEME),
- );
- }
+ let Some(connection_string) = self.config.connection_string else {
+ return Err(
+ Error::new(ErrorKind::ConfigInvalid, "connection_string is
required")
+ .with_context("service", GRIDFS_SCHEME),
+ );
};
- let database = match &self.config.database.clone() {
- Some(v) => v.clone(),
- None => {
- return Err(Error::new(ErrorKind::ConfigInvalid, "database is
required")
- .with_context("service", GRIDFS_SCHEME));
- }
+ let Some(database) = self.config.database else {
+ return Err(Error::new(ErrorKind::ConfigInvalid, "database is
required")
+ .with_context("service", GRIDFS_SCHEME));
};
- let bucket = match &self.config.bucket.clone() {
- Some(v) => v.clone(),
- None => "fs".to_string(),
+ let bucket = self.config.bucket.unwrap_or_else(|| "fs".to_string());
+ let chunk_size = match self.config.chunk_size {
+ Some(0) => {
+ return Err(Error::new(
+ ErrorKind::ConfigInvalid,
+ "chunk_size must be greater than 0",
+ )
+ .with_context("service", GRIDFS_SCHEME));
+ }
+ Some(v) => v,
+ None => DEFAULT_CHUNK_SIZE_BYTES,
};
- let chunk_size =
self.config.chunk_size.unwrap_or(DEFAULT_CHUNK_SIZE_BYTES);
-
- let root = normalize_root(
- self.config
- .root
- .clone()
- .unwrap_or_else(|| "/".to_string())
- .as_str(),
- );
+
+ let root = normalize_root(self.config.root.as_deref().unwrap_or("/"));
Ok(GridfsBackend::new(GridfsCore {
- connection_string: conn,
+ connection_string,
database,
bucket,
chunk_size,
@@ -228,10 +223,14 @@ impl Service for GridfsBackend {
Ok(RpStat::new(MetadataBuilder::dir().build()))
} else {
match self.core.get_length(&p).await? {
- Some(len) => Ok(RpStat::new({
- let metadata = MetadataBuilder::file(len as u64);
- metadata.build()
- })),
+ Some(len) => {
+ let metadata = if p.ends_with('/') {
+ MetadataBuilder::dir()
+ } else {
+ MetadataBuilder::file(len)
+ };
+ Ok(RpStat::new(metadata.build()))
+ }
None => Err(Error::new(ErrorKind::NotFound, "kv not found in
gridfs")),
}
}
@@ -313,3 +312,36 @@ impl Service for GridfsBackend {
))
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn build_rejects_zero_chunk_size_from_iter() -> Result<()> {
+ let cfg = GridfsConfig::from_iter([
+ (
+ "connection_string".to_string(),
+ "mongodb://127.0.0.1:27017".to_string(),
+ ),
+ ("database".to_string(), "demo".to_string()),
+ ("chunk_size".to_string(), "0".to_string()),
+ ])?;
+ assert_eq!(
+ cfg.into_builder().build().err().unwrap().kind(),
+ ErrorKind::ConfigInvalid
+ );
+ Ok(())
+ }
+
+ #[test]
+ fn builder_setter_ignores_zero_chunk_size() -> Result<()> {
+ let default_builder_service = GridfsBuilder::default()
+ .connection_string("mongodb://127.0.0.1:27017")
+ .database("demo")
+ .chunk_size(0)
+ .build()?;
+ assert_eq!(default_builder_service.info().name().as_ref(), "demo/fs");
+ Ok(())
+ }
+}
diff --git a/core/services/gridfs/src/config.rs
b/core/services/gridfs/src/config.rs
index a06c011b03..0f72ecf0d1 100644
--- a/core/services/gridfs/src/config.rs
+++ b/core/services/gridfs/src/config.rs
@@ -51,17 +51,30 @@ impl Debug for GridfsConfig {
}
}
+fn percent_encode_uri_component(value: &str) -> String {
+ const HEX: &[u8; 16] = b"0123456789ABCDEF";
+ let mut encoded = String::with_capacity(value.len());
+ for byte in value.bytes() {
+ if matches!(
+ byte,
+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~'
+ ) {
+ encoded.push(byte as char);
+ } else {
+ encoded.push('%');
+ encoded.push(HEX[(byte >> 4) as usize] as char);
+ encoded.push(HEX[(byte & 0x0f) as usize] as char);
+ }
+ }
+ encoded
+}
+
impl Configurator for GridfsConfig {
type Builder = GridfsBuilder;
fn from_uri(uri: &OperatorUri) -> Result<Self> {
let mut map = uri.options().clone();
- if let Some(authority) = uri.authority() {
- map.entry("connection_string".to_string())
- .or_insert_with(|| format!("mongodb://{authority}"));
- }
-
if let Some(path) = uri.root()
&& !path.is_empty()
{
@@ -81,10 +94,34 @@ impl Configurator for GridfsConfig {
if let Some(rest) = segments.next()
&& !rest.is_empty()
{
- map.insert("root".to_string(), rest.to_string());
+ map.entry("root".to_string())
+ .or_insert_with(|| rest.to_string());
}
}
+ if let Some(authority) = uri.authority()
+ && !map.contains_key("connection_string")
+ {
+ let userinfo = match (uri.username(), uri.password()) {
+ (Some(user), Some(pass)) => format!(
+ "{}:{}@",
+ percent_encode_uri_component(user),
+ percent_encode_uri_component(pass)
+ ),
+ (Some(user), None) => format!("{}@",
percent_encode_uri_component(user)),
+ (None, _) => String::new(),
+ };
+ let db_path = map
+ .get("database")
+ .filter(|db| !db.is_empty())
+ .map(|db| format!("/{}", percent_encode_uri_component(db)))
+ .unwrap_or_default();
+ map.insert(
+ "connection_string".to_string(),
+ format!("mongodb://{userinfo}{authority}{db_path}"),
+ );
+ }
+
Self::from_iter(map)
}
@@ -95,7 +132,11 @@ impl Configurator for GridfsConfig {
#[cfg(test)]
mod tests {
+ use std::time::Duration;
+
use super::*;
+ use mongodb::options::ClientOptions;
+ use mongodb::options::ConnectionString;
#[test]
fn from_uri_sets_connection_database_bucket_and_root() -> Result<()> {
@@ -107,11 +148,127 @@ mod tests {
let cfg = GridfsConfig::from_uri(&uri)?;
assert_eq!(
cfg.connection_string.as_deref(),
- Some("mongodb://mongo.example.com:27017")
+ Some("mongodb://mongo.example.com:27017/app_files")
);
assert_eq!(cfg.database.as_deref(), Some("app_files"));
assert_eq!(cfg.bucket.as_deref(), Some("assets"));
assert_eq!(cfg.root.as_deref(), Some("images"));
+
+ let parsed =
ConnectionString::parse(cfg.connection_string.as_deref().unwrap()).unwrap();
+ assert_eq!(parsed.default_database.as_deref(), Some("app_files"));
+ assert!(cfg.into_builder().build().is_ok());
+
+ let no_db_uri = OperatorUri::new(
+ "gridfs://mongo.example.com:27017",
+ Vec::<(String, String)>::new(),
+ )?;
+ let no_db_cfg = GridfsConfig::from_uri(&no_db_uri)?;
+ assert_eq!(
+ no_db_cfg.connection_string.as_deref(),
+ Some("mongodb://mongo.example.com:27017")
+ );
+ assert_eq!(no_db_cfg.database, None);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn from_uri_preserves_and_percent_encodes_credentials_and_database()
-> Result<()> {
+ tokio::time::timeout(Duration::from_secs(10), async {
+ let uri = OperatorUri::new(
+
"gridfs://alice%40corp.com:p%40ss%[email protected]:27017/app%231/assets/images",
+ Vec::<(String, String)>::new(),
+ )?;
+
+ let cfg = GridfsConfig::from_uri(&uri)?;
+ let conn_str = cfg.connection_string.as_deref().unwrap();
+ assert_eq!(
+ conn_str,
+
"mongodb://alice%40corp.com:p%40ss%[email protected]:27017/app%231"
+ );
+ assert_eq!(cfg.database.as_deref(), Some("app#1"));
+ assert_eq!(cfg.bucket.as_deref(), Some("assets"));
+ assert_eq!(cfg.root.as_deref(), Some("images"));
+
+ let parsed = ConnectionString::parse(conn_str).unwrap();
+ assert_eq!(parsed.default_database.as_deref(), Some("app#1"));
+ let cred = parsed.credential.as_ref().unwrap();
+ assert_eq!(cred.username.as_deref(), Some("[email protected]"));
+ assert_eq!(cred.password.as_deref(), Some("p@ss:word"));
+
+ let client_opts = ClientOptions::parse(parsed).await.unwrap();
+ assert_eq!(
+ client_opts
+ .credential
+ .as_ref()
+ .and_then(|c| c.source.as_deref()),
+ Some("app#1")
+ );
+ assert!(cfg.into_builder().build().is_ok());
+
+ let user_only_uri = OperatorUri::new(
+ "gridfs://[email protected]:27017/app_files/assets",
+ Vec::<(String, String)>::new(),
+ )?;
+ let user_only_cfg = GridfsConfig::from_uri(&user_only_uri)?;
+ assert_eq!(
+ user_only_cfg.connection_string.as_deref(),
+ Some("mongodb://[email protected]:27017/app_files")
+ );
+ assert!(user_only_cfg.into_builder().build().is_ok());
+
+ Ok(())
+ })
+ .await
+ .expect("test timed out")
+ }
+
+ #[test]
+ fn from_uri_preserves_explicit_options_over_uri_components() -> Result<()>
{
+ let uri = OperatorUri::new(
+
"gridfs://root:[email protected]:27017/app_files/assets/images?root=override",
+ vec![(
+ "connection_string".to_string(),
+ "mongodb://custom:27018".to_string(),
+ )],
+ )?;
+
+ let cfg = GridfsConfig::from_uri(&uri)?;
+ assert_eq!(
+ cfg.connection_string.as_deref(),
+ Some("mongodb://custom:27018")
+ );
+ assert_eq!(cfg.database.as_deref(), Some("app_files"));
+ assert_eq!(cfg.bucket.as_deref(), Some("assets"));
+ assert_eq!(cfg.root.as_deref(), Some("override"));
+
+ let db_override_uri = OperatorUri::new(
+ "gridfs://demo_u:[email protected]:27017/ignored/assets",
+ vec![("database".to_string(), "target_db".to_string())],
+ )?;
+ let db_override_cfg = GridfsConfig::from_uri(&db_override_uri)?;
+ assert_eq!(
+ db_override_cfg.connection_string.as_deref(),
+ Some("mongodb://demo_u:[email protected]:27017/target_db")
+ );
+ assert_eq!(db_override_cfg.database.as_deref(), Some("target_db"));
+ assert_eq!(db_override_cfg.bucket.as_deref(), Some("assets"));
+ Ok(())
+ }
+
+ #[test]
+ fn from_uri_rejects_zero_chunk_size_on_build() -> Result<()> {
+ let uri = OperatorUri::new(
+ "gridfs://127.0.0.1:27017/app_files/fs?chunk_size=0",
+ Vec::<(String, String)>::new(),
+ )?;
+ let cfg = GridfsConfig::from_uri(&uri)?;
+ assert_eq!(cfg.chunk_size, Some(0));
+
+ let err = cfg
+ .into_builder()
+ .build()
+ .expect_err("chunk_size=0 must fail build");
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
Ok(())
}
}
diff --git a/core/services/gridfs/src/core.rs b/core/services/gridfs/src/core.rs
index cd3c39bf0a..860b64a9cb 100644
--- a/core/services/gridfs/src/core.rs
+++ b/core/services/gridfs/src/core.rs
@@ -20,6 +20,8 @@ use std::fmt::Debug;
use asyncband::once::OnceCell;
use futures::AsyncReadExt;
use futures::AsyncWriteExt;
+use futures::TryStreamExt;
+use mongodb::bson::Bson;
use mongodb::bson::doc;
use mongodb::gridfs::{FilesCollectionDocument, GridFsBucket};
use mongodb::options::ClientOptions;
@@ -72,49 +74,90 @@ impl GridfsCore {
path: &str,
) -> Result<Option<FilesCollectionDocument>> {
let filter = doc! { "filename": path };
- let doc = bucket.find_one(filter).await.map_err(parse_mongodb_error)?;
+ let doc = bucket
+ .find_one(filter)
+ .sort(doc! { "uploadDate": -1, "_id": -1 })
+ .await
+ .map_err(parse_mongodb_error)?;
Ok(doc)
}
- pub async fn get(&self, path: &str) -> Result<Option<Buffer>> {
- let bucket = self.get_bucket().await?;
- let Some(doc) = Self::get_one_doc(bucket, path).await? else {
- return Ok(None);
- };
+ async fn delete_doc_by_id(bucket: &GridFsBucket, file_id: Bson) ->
Result<()> {
+ match bucket.delete(file_id).await {
+ Ok(()) => Ok(()),
+ Err(err) if is_gridfs_file_not_found(&err) => Ok(()),
+ Err(err) => Err(parse_mongodb_error(err)),
+ }
+ }
- let mut destination = Vec::new();
- let file_id = doc.id;
- let mut stream = bucket
- .open_download_stream(file_id)
+ async fn delete_superseded_docs(bucket: &GridFsBucket, path: &str) ->
Result<()> {
+ let mut cursor = bucket
+ .find(doc! { "filename": path })
+ .sort(doc! { "uploadDate": -1, "_id": -1 })
.await
.map_err(parse_mongodb_error)?;
- stream
- .read_to_end(&mut destination)
- .await
- .map_err(new_std_io_error)?;
- Ok(Some(Buffer::from(destination)))
+
+ // Keep the newest revision under `(uploadDate, _id)` so concurrent
writers
+ // cannot delete each other's latest revision.
+ cursor.try_next().await.map_err(parse_mongodb_error)?;
+ while let Some(doc) =
cursor.try_next().await.map_err(parse_mongodb_error)? {
+ Self::delete_doc_by_id(bucket, doc.id).await?;
+ }
+
+ Ok(())
+ }
+
+ pub async fn get(&self, path: &str) -> Result<Option<Buffer>> {
+ let bucket = self.get_bucket().await?;
+ for _ in 0..2 {
+ let Some(doc) = Self::get_one_doc(bucket, path).await? else {
+ return Ok(None);
+ };
+
+ let file_id = doc.id;
+ let mut stream = match
bucket.open_download_stream(file_id.clone()).await {
+ Ok(stream) => stream,
+ Err(err) if is_gridfs_file_not_found(&err) => continue,
+ Err(err) => return Err(parse_mongodb_error(err)),
+ };
+ let mut destination = Vec::new();
+ match stream.read_to_end(&mut destination).await {
+ Ok(_) => return Ok(Some(Buffer::from(destination))),
+ Err(err) => {
+ // GridFS deletes the file document before its chunks.
Missing chunks
+ // indicate a race only if the selected file document is
gone too.
+ if is_gridfs_missing_chunk(&err)
+ && bucket
+ .find_one(doc! { "_id": &file_id })
+ .await
+ .map_err(parse_mongodb_error)?
+ .is_none()
+ {
+ continue;
+ }
+ return Err(new_std_io_error(err));
+ }
+ }
+ }
+
+ Ok(None)
}
/// Get the byte length of the file.
- pub async fn get_length(&self, path: &str) -> Result<Option<usize>> {
+ pub async fn get_length(&self, path: &str) -> Result<Option<u64>> {
let bucket = self.get_bucket().await?;
let Some(doc) = Self::get_one_doc(bucket, path).await? else {
return Ok(None);
};
- Ok(Some(doc.length as usize))
+ Ok(Some(doc.length))
}
pub async fn set(&self, path: &str, value: Buffer) -> Result<()> {
let bucket = self.get_bucket().await?;
- // delete old file if exists
- if let Some(doc) = Self::get_one_doc(bucket, path).await? {
- let file_id = doc.id;
- bucket.delete(file_id).await.map_err(parse_mongodb_error)?;
- };
-
- // set new file
+ // Upload the new revision before cleaning up older revisions so a
failed
+ // upload does not lose the previous version.
let mut upload_stream = bucket
.open_upload_stream(path)
.await
@@ -125,21 +168,45 @@ impl GridfsCore {
.map_err(new_std_io_error)?;
upload_stream.close().await.map_err(new_std_io_error)?;
+ Self::delete_superseded_docs(bucket, path).await?;
+
Ok(())
}
pub async fn delete(&self, path: &str) -> Result<()> {
let bucket = self.get_bucket().await?;
- let Some(doc) = Self::get_one_doc(bucket, path).await? else {
- return Ok(());
- };
+ let mut cursor = bucket
+ .find(doc! { "filename": path })
+ .await
+ .map_err(parse_mongodb_error)?;
+
+ while let Some(doc) =
cursor.try_next().await.map_err(parse_mongodb_error)? {
+ Self::delete_doc_by_id(bucket, doc.id).await?;
+ }
- let file_id = doc.id;
- bucket.delete(file_id).await.map_err(parse_mongodb_error)?;
Ok(())
}
}
+fn is_gridfs_file_not_found(err: &mongodb::error::Error) -> bool {
+ matches!(
+ err.kind.as_ref(),
+
mongodb::error::ErrorKind::GridFs(mongodb::error::GridFsErrorKind::FileNotFound
{ .. })
+ )
+}
+
+fn is_gridfs_missing_chunk(err: &std::io::Error) -> bool {
+ let mongo_error = err
+ .get_ref()
+ .and_then(|inner| inner.downcast_ref::<mongodb::error::Error>());
+ matches!(
+ mongo_error.map(|err| err.kind.as_ref()),
+ Some(mongodb::error::ErrorKind::GridFs(
+ mongodb::error::GridFsErrorKind::MissingChunk { .. }
+ ))
+ )
+}
+
fn parse_mongodb_error(err: mongodb::error::Error) -> Error {
Error::new(ErrorKind::Unexpected, "mongodb error").set_source(err)
}
diff --git a/core/services/gridfs/tests/gridfs.rs
b/core/services/gridfs/tests/gridfs.rs
new file mode 100644
index 0000000000..9ac6d7e9b3
--- /dev/null
+++ b/core/services/gridfs/tests/gridfs.rs
@@ -0,0 +1,377 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use futures::AsyncWriteExt;
+use mongodb::bson::DateTime;
+use mongodb::bson::Document;
+use mongodb::bson::doc;
+use mongodb::bson::oid::ObjectId;
+use mongodb::options::GridFsBucketOptions;
+use opendal_core::EntryMode;
+use opendal_core::ErrorKind;
+use opendal_core::Operator;
+use opendal_core::Result;
+use opendal_service_gridfs::Gridfs;
+
+fn connection_string() -> String {
+ std::env::var("OPENDAL_GRIDFS_CONNECTION_STRING")
+ .unwrap_or_else(|_| "mongodb://127.0.0.1:27017".to_string())
+}
+
+async fn upload_revision(bucket: &mongodb::gridfs::GridFsBucket, filename:
&str, data: &[u8]) {
+ let mut stream = bucket.open_upload_stream(filename).await.unwrap();
+ stream.write_all(data).await.unwrap();
+ stream.close().await.unwrap();
+}
+
+#[tokio::test]
+#[ignore = "requires a running MongoDB server
(OPENDAL_GRIDFS_CONNECTION_STRING)"]
+async fn test_live_duplicate_revisions_read_newest_and_delete_all() ->
Result<()> {
+ tokio::time::timeout(Duration::from_secs(30), async {
+ let conn = connection_string();
+ let db_name = format!("opendal_gridfs_dup_{}",
ObjectId::new().to_hex());
+ let bucket_name = "fs";
+
+ let client = mongodb::Client::with_uri_str(&conn).await.unwrap();
+ let db = client.database(&db_name);
+ let bucket = db.gridfs_bucket(
+ GridFsBucketOptions::builder()
+ .bucket_name(Some(bucket_name.to_string()))
+ .chunk_size_bytes(Some(16))
+ .build(),
+ );
+
+ let op = Operator::new(
+ Gridfs::default()
+ .connection_string(&conn)
+ .database(&db_name)
+ .bucket(bucket_name)
+ .chunk_size(16),
+ )?;
+
+ // Upload two revisions with distinct uploadDate values.
+ upload_revision(&bucket, "rev.txt", b"older-v1").await;
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ upload_revision(&bucket, "rev.txt", b"newer-v2-payload-longer").await;
+
+ let files_coll =
db.collection::<Document>(&format!("{bucket_name}.files"));
+ let chunks_coll =
db.collection::<Document>(&format!("{bucket_name}.chunks"));
+ assert_eq!(
+ files_coll
+ .count_documents(doc! { "filename": "rev.txt" })
+ .await
+ .unwrap(),
+ 2
+ );
+
+ // stat and read must return the newest revision, not the oldest.
+ let meta = op.stat("rev.txt").await?;
+ assert_eq!(meta.mode(), EntryMode::FILE);
+ assert_eq!(
+ meta.content_length(),
+ b"newer-v2-payload-longer".len() as u64
+ );
+ assert_eq!(
+ op.read("rev.txt").await?.to_bytes(),
+ &b"newer-v2-payload-longer"[..]
+ );
+
+ // Give the two real SDK uploads the same timestamp to exercise the ID
tie-breaker.
+ files_coll
+ .update_many(
+ doc! { "filename": "rev.txt" },
+ doc! { "$set": { "uploadDate": DateTime::now() } },
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ op.read("rev.txt").await?.to_bytes(),
+ &b"newer-v2-payload-longer"[..]
+ );
+
+ // Delete must remove both revisions and their chunks.
+ op.delete("rev.txt").await?;
+ assert_eq!(
+ files_coll
+ .count_documents(doc! { "filename": "rev.txt" })
+ .await
+ .unwrap(),
+ 0
+ );
+ assert_eq!(chunks_coll.count_documents(doc! {}).await.unwrap(), 0);
+ assert_eq!(
+ op.stat("rev.txt").await.unwrap_err().kind(),
+ ErrorKind::NotFound
+ );
+ assert_eq!(
+ op.read("rev.txt").await.unwrap_err().kind(),
+ ErrorKind::NotFound
+ );
+
+ // A subsequent overwrite cleans up multiple already committed
revisions.
+ upload_revision(&bucket, "rev.txt", b"older-before-overwrite").await;
+ upload_revision(&bucket, "rev.txt", b"newer-before-overwrite").await;
+ op.write("rev.txt", "replaced-v3").await?;
+ assert_eq!(op.read("rev.txt").await?.to_bytes(), &b"replaced-v3"[..]);
+ assert_eq!(
+ files_coll
+ .count_documents(doc! { "filename": "rev.txt" })
+ .await
+ .unwrap(),
+ 1
+ );
+ assert_eq!(chunks_coll.count_documents(doc! {}).await.unwrap(), 1);
+
+ let _ = db.drop().await;
+ Ok(())
+ })
+ .await
+ .expect("test timed out")
+}
+
+#[tokio::test]
+#[ignore = "requires a running MongoDB server
(OPENDAL_GRIDFS_CONNECTION_STRING)"]
+async fn test_live_upload_failure_preserves_existing_revision() -> Result<()> {
+ tokio::time::timeout(Duration::from_secs(30), async {
+ let conn = connection_string();
+ let db_name = format!("opendal_gridfs_fail_{}",
ObjectId::new().to_hex());
+ let bucket_name = "fs";
+
+ let client = mongodb::Client::with_uri_str(&conn).await.unwrap();
+ let db = client.database(&db_name);
+
+ let op = Operator::new(
+ Gridfs::default()
+ .connection_string(&conn)
+ .database(&db_name)
+ .bucket(bucket_name)
+ .chunk_size(32),
+ )?;
+
+ op.write("safe.txt", "original-data").await?;
+ assert_eq!(op.read("safe.txt").await?.to_bytes(),
&b"original-data"[..]);
+
+ let chunks = db.collection::<Document>("fs.chunks");
+ let original_chunks = chunks.count_documents(doc! {}).await.unwrap();
+
+ // Reject the later chunks after accepting the first chunks of the
upload.
+ db.run_command(doc! {
+ "collMod": "fs.chunks",
+ "validator": { "n": { "$lt": 2 } },
+ })
+ .await
+ .unwrap();
+ let err = op
+ .write("safe.txt", vec![b'x'; 128])
+ .await
+ .expect_err("chunk validator must reject upload");
+ assert_eq!(err.kind(), ErrorKind::Unexpected);
+ assert_eq!(op.read("safe.txt").await?.to_bytes(),
&b"original-data"[..]);
+ assert_eq!(
+ chunks.count_documents(doc! {}).await.unwrap(),
+ original_chunks
+ );
+
+ db.run_command(doc! { "collMod": "fs.chunks", "validator": {} })
+ .await
+ .unwrap();
+
+ // Reject the files document after writing the chunks.
+ db.run_command(doc! {
+ "collMod": format!("{bucket_name}.files"),
+ "validator": { "length": { "$lte": 64 } },
+ })
+ .await
+ .unwrap();
+
+ let err = op
+ .write("safe.txt", vec![b'x'; 128])
+ .await
+ .expect_err("validator must reject oversized upload");
+ assert_eq!(err.kind(), ErrorKind::Unexpected);
+
+ assert_eq!(op.read("safe.txt").await?.to_bytes(),
&b"original-data"[..]);
+ assert_eq!(
+ chunks.count_documents(doc! {}).await.unwrap(),
+ original_chunks
+ );
+
+ let _ = db.drop().await;
+ Ok(())
+ })
+ .await
+ .expect("test timed out")
+}
+
+#[tokio::test]
+#[ignore = "requires a running MongoDB server
(OPENDAL_GRIDFS_CONNECTION_STRING)"]
+async fn test_live_concurrent_writes_reads_and_deletes() -> Result<()> {
+ tokio::time::timeout(Duration::from_secs(60), async {
+ let conn = connection_string();
+ let db_name = format!("opendal_gridfs_conc_{}",
ObjectId::new().to_hex());
+ let bucket_name = "fs";
+
+ let client = mongodb::Client::with_uri_str(&conn).await.unwrap();
+ let db = client.database(&db_name);
+
+ let op = Operator::new(
+ Gridfs::default()
+ .connection_string(&conn)
+ .database(&db_name)
+ .bucket(bucket_name)
+ .chunk_size(16),
+ )?;
+
+ // Phase A: Concurrent overwrites must never leave 0 documents or fail
readers with Unexpected.
+ op.write("concurrent_write.txt", vec![b'0'; 48]).await?;
+ let mut handles = Vec::new();
+ for worker in 0..6u8 {
+ let op = op.clone();
+ handles.push(tokio::spawn(async move {
+ for iter in 0..10u8 {
+ let byte = b'a' + ((worker + iter) % 26);
+ let payload = vec![byte; 40 + usize::from(iter)];
+ op.write("concurrent_write.txt", payload).await?;
+ }
+ Ok::<_, opendal_core::Error>(())
+ }));
+ }
+ for _ in 0..3 {
+ let op = op.clone();
+ handles.push(tokio::spawn(async move {
+ for _ in 0..15 {
+ match op.read("concurrent_write.txt").await {
+ Ok(buf) => {
+ let bytes = buf.to_bytes();
+ assert!((40..=49).contains(&bytes.len()));
+ assert!(bytes.iter().all(|byte| *byte ==
bytes[0]));
+ }
+ Err(err) if err.kind() == ErrorKind::NotFound => {}
+ Err(err) => return Err(err),
+ }
+ match op.stat("concurrent_write.txt").await {
+ Ok(meta) => assert_eq!(meta.mode(), EntryMode::FILE),
+ Err(err) if err.kind() == ErrorKind::NotFound => {}
+ Err(err) => return Err(err),
+ }
+ }
+ Ok(())
+ }));
+ }
+ for handle in handles {
+ handle.await.unwrap()?;
+ }
+
+ let files_coll =
db.collection::<Document>(&format!("{bucket_name}.files"));
+ assert_eq!(
+ files_coll
+ .count_documents(doc! { "filename": "concurrent_write.txt" })
+ .await
+ .unwrap(),
+ 1,
+ "concurrent overwrites must keep exactly one surviving revision"
+ );
+ assert!(!op.read("concurrent_write.txt").await?.is_empty());
+
+ // Phase B: Concurrent writes + deletes + reads must never fail with
Unexpected (FileNotFound).
+ let mut churn_handles = Vec::new();
+ for worker in 0..4u8 {
+ let op = op.clone();
+ churn_handles.push(tokio::spawn(async move {
+ for iter in 0..15u8 {
+ let payload = vec![b'A' + ((worker + iter) % 26); 48];
+ op.write("concurrent_churn.txt", payload).await?;
+ }
+ Ok::<_, opendal_core::Error>(())
+ }));
+ }
+ for _ in 0..4 {
+ let op = op.clone();
+ churn_handles.push(tokio::spawn(async move {
+ for _ in 0..15 {
+ op.delete("concurrent_churn.txt").await?;
+ }
+ Ok(())
+ }));
+ }
+ for _ in 0..4 {
+ let op = op.clone();
+ churn_handles.push(tokio::spawn(async move {
+ for _ in 0..15 {
+ match op.read("concurrent_churn.txt").await {
+ Ok(_) => {}
+ Err(err) if err.kind() == ErrorKind::NotFound => {}
+ Err(err) => return Err(err),
+ }
+ }
+ Ok(())
+ }));
+ }
+ for handle in churn_handles {
+ handle.await.unwrap()?;
+ }
+
+ op.delete("concurrent_churn.txt").await?;
+ assert_eq!(
+ files_coll
+ .count_documents(doc! { "filename": "concurrent_churn.txt" })
+ .await
+ .unwrap(),
+ 0
+ );
+ assert_eq!(
+ op.stat("concurrent_churn.txt").await.unwrap_err().kind(),
+ ErrorKind::NotFound
+ );
+
+ let _ = db.drop().await;
+ Ok(())
+ })
+ .await
+ .expect("test timed out")
+}
+
+#[tokio::test]
+#[ignore = "requires a running MongoDB server
(OPENDAL_GRIDFS_CONNECTION_STRING)"]
+async fn test_live_stat_reports_directory_marker() -> Result<()> {
+ tokio::time::timeout(Duration::from_secs(30), async {
+ let conn = connection_string();
+ let db_name = format!("opendal_gridfs_dir_{}",
ObjectId::new().to_hex());
+ let client = mongodb::Client::with_uri_str(&conn).await.unwrap();
+ let db = client.database(&db_name);
+ let bucket = db.gridfs_bucket(None);
+ upload_revision(&bucket, "a/", b"").await;
+
+ let op = Operator::new(
+ Gridfs::default()
+ .connection_string(&conn)
+ .database(&db_name),
+ )?;
+ assert_eq!(op.stat("a/").await?.mode(), EntryMode::DIR);
+ assert_eq!(
+ op.stat("missing/").await.unwrap_err().kind(),
+ ErrorKind::NotFound
+ );
+
+ let _ = db.drop().await;
+ Ok(())
+ })
+ .await
+ .expect("test timed out")
+}