This is an automated email from the ASF dual-hosted git repository. Xuanwo pushed a commit to branch xuanwo/fix-mongodb-upsert-delete-nested-field-and-config in repository https://gitbox.apache.org/repos/asf/opendal.git
commit a20742798bdcad3bd72f82e61185c791bda98a03 Author: Xuanwo <[email protected]> AuthorDate: Tue Nov 24 01:50:40 2026 +0100 fix(services/mongodb): fix duplicate delete/E11000 upsert, nested value_field reads, and config/URI validation --- core/services/mongodb/src/backend.rs | 152 ++++++++++++++++++++++++++---- core/services/mongodb/src/config.rs | 100 +++++++++++++++++++- core/services/mongodb/src/core.rs | 175 +++++++++++++++++++++++++++++++---- core/services/mongodb/src/docs.md | 4 + 4 files changed, 392 insertions(+), 39 deletions(-) diff --git a/core/services/mongodb/src/backend.rs b/core/services/mongodb/src/backend.rs index f67c5988b4..7f056206f1 100644 --- a/core/services/mongodb/src/backend.rs +++ b/core/services/mongodb/src/backend.rs @@ -18,6 +18,7 @@ use std::sync::Arc; use asyncband::once::OnceCell; +use mongodb::options::ConnectionString; use super::MONGODB_SCHEME; use super::config::MongodbConfig; @@ -111,43 +112,63 @@ impl MongodbBuilder { } } +fn validate_field_path(name: &str, value: &str) -> Result<()> { + if value.is_empty() + || value.contains('\0') + || value + .split('.') + .any(|segment| segment.is_empty() || segment.starts_with('$')) + { + return Err( + Error::new(ErrorKind::ConfigInvalid, format!("{name} is invalid")) + .with_context("service", MONGODB_SCHEME) + .with_context("field", name), + ); + } + Ok(()) +} + impl Builder for MongodbBuilder { type Config = MongodbConfig; fn build(self) -> Result<impl Service> { - let conn = match &self.config.connection_string.clone() { - Some(v) => v.clone(), - None => { + let conn = match self.config.connection_string.as_deref() { + Some(v) if !v.is_empty() => v, + _ => { return Err( Error::new(ErrorKind::ConfigInvalid, "connection_string is required") .with_context("service", MONGODB_SCHEME), ); } }; - let database = match &self.config.database.clone() { - Some(v) => v.clone(), - None => { + let connection_string = ConnectionString::parse(conn).map_err(|err| { + Error::new(ErrorKind::ConfigInvalid, "connection_string is invalid") + .with_context("service", MONGODB_SCHEME) + .set_source(err) + })?; + let database = match self.config.database.as_deref() { + Some(v) if !v.is_empty() => v.to_string(), + _ => { return Err(Error::new(ErrorKind::ConfigInvalid, "database is required") .with_context("service", MONGODB_SCHEME)); } }; - let collection = match &self.config.collection.clone() { - Some(v) => v.clone(), - None => { + let collection = match self.config.collection.as_deref() { + Some(v) if !v.is_empty() => v.to_string(), + _ => { return Err( Error::new(ErrorKind::ConfigInvalid, "collection is required") .with_context("service", MONGODB_SCHEME), ); } }; - let key_field = match &self.config.key_field.clone() { - Some(v) => v.clone(), - None => "key".to_string(), - }; - let value_field = match &self.config.value_field.clone() { - Some(v) => v.clone(), - None => "value".to_string(), - }; + let key_field = self.config.key_field.unwrap_or_else(|| "key".to_string()); + validate_field_path("key_field", &key_field)?; + let value_field = self + .config + .value_field + .unwrap_or_else(|| "value".to_string()); + validate_field_path("value_field", &value_field)?; let root = normalize_root( self.config .root @@ -156,7 +177,7 @@ impl Builder for MongodbBuilder { .as_str(), ); Ok(MongodbBackend::new(MongodbCore { - connection_string: conn, + connection_string, database, collection, collection_instance: OnceCell::new(), @@ -328,3 +349,98 @@ impl Service for MongodbBackend { )) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn valid_config() -> MongodbConfig { + MongodbConfig { + connection_string: Some("mongodb://127.0.0.1:27017".to_string()), + database: Some("demo".to_string()), + collection: Some("demo".to_string()), + root: None, + key_field: None, + value_field: None, + } + } + + #[test] + fn build_rejects_empty_and_invalid_config() { + let mut cfg = valid_config(); + cfg.connection_string = Some(String::new()); + assert_eq!( + cfg.into_builder().build().err().unwrap().kind(), + ErrorKind::ConfigInvalid + ); + + let mut cfg = valid_config(); + cfg.connection_string = Some("not-a-mongodb-uri".to_string()); + assert_eq!( + cfg.into_builder().build().err().unwrap().kind(), + ErrorKind::ConfigInvalid + ); + + let mut cfg = valid_config(); + cfg.connection_string = Some("mongodb://:[email protected]:27017".to_string()); + assert_eq!( + cfg.into_builder().build().err().unwrap().kind(), + ErrorKind::ConfigInvalid + ); + + let mut cfg = valid_config(); + cfg.database = Some(String::new()); + assert_eq!( + cfg.into_builder().build().err().unwrap().kind(), + ErrorKind::ConfigInvalid + ); + + let mut cfg = valid_config(); + cfg.collection = Some(String::new()); + assert_eq!( + cfg.into_builder().build().err().unwrap().kind(), + ErrorKind::ConfigInvalid + ); + + for invalid in [ + "", + ".", + ".a", + "a.", + "a..b", + "$val", + "$ROOT", + "payload.$data", + "a\0b", + ] { + let mut cfg = valid_config(); + cfg.key_field = Some(invalid.to_string()); + assert_eq!( + cfg.into_builder().build().err().unwrap().kind(), + ErrorKind::ConfigInvalid, + "expected key_field {invalid:?} to fail validation" + ); + + let mut cfg = valid_config(); + cfg.value_field = Some(invalid.to_string()); + assert_eq!( + cfg.into_builder().build().err().unwrap().kind(), + ErrorKind::ConfigInvalid, + "expected value_field {invalid:?} to fail validation" + ); + } + } + + #[test] + fn build_accepts_flat_and_nested_fields() { + let mut cfg = valid_config(); + cfg.key_field = Some("_id".to_string()); + cfg.value_field = Some("payload.data".to_string()); + assert!(cfg.into_builder().build().is_ok()); + + let mut cfg = valid_config(); + cfg.key_field = Some("meta.key".to_string()); + cfg.value_field = Some("a.b.c".to_string()); + assert!(cfg.into_builder().build().is_ok()); + } +} diff --git a/core/services/mongodb/src/config.rs b/core/services/mongodb/src/config.rs index 8353a6c153..b5cabaf15c 100644 --- a/core/services/mongodb/src/config.rs +++ b/core/services/mongodb/src/config.rs @@ -53,6 +53,24 @@ impl Debug for MongodbConfig { } } +fn percent_encode_userinfo(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 opendal_core::Configurator for MongodbConfig { type Builder = MongodbBuilder; @@ -61,7 +79,19 @@ impl opendal_core::Configurator for MongodbConfig { if let Some(authority) = uri.authority() { map.entry("connection_string".to_string()) - .or_insert_with(|| format!("mongodb://{authority}")); + .or_insert_with(|| { + let userinfo = match (uri.username(), uri.password()) { + (Some(user), Some(pass)) => format!( + "{}:{}@", + percent_encode_userinfo(user), + percent_encode_userinfo(pass) + ), + (Some(user), None) => format!("{}@", percent_encode_userinfo(user)), + (None, Some(pass)) => format!(":{}@", percent_encode_userinfo(pass)), + (None, None) => String::new(), + }; + format!("mongodb://{userinfo}{authority}") + }); } if let Some(path) = uri.root() @@ -83,7 +113,8 @@ impl opendal_core::Configurator for MongodbConfig { 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()); } } @@ -98,6 +129,7 @@ impl opendal_core::Configurator for MongodbConfig { #[cfg(test)] mod tests { use super::*; + use mongodb::options::ConnectionString; use opendal_core::Configurator; use opendal_core::OperatorUri; @@ -118,4 +150,68 @@ mod tests { assert_eq!(cfg.collection.as_deref(), Some("events")); assert_eq!(cfg.root.as_deref(), Some("session")); } + + #[test] + fn from_uri_preserves_and_percent_encodes_credentials() { + let uri = OperatorUri::new( + "mongodb://alice%40corp.com:p%40ss%3Aword%[email protected]:27017/analytics/events", + Vec::<(String, String)>::new(), + ) + .unwrap(); + + let cfg = MongodbConfig::from_uri(&uri).unwrap(); + let conn_str = cfg.connection_string.as_deref().unwrap(); + assert_eq!( + conn_str, + "mongodb://alice%40corp.com:p%40ss%3Aword%[email protected]:27017" + ); + + let parsed = ConnectionString::parse(conn_str).unwrap(); + let cred = parsed.credential.unwrap(); + assert_eq!(cred.username.as_deref(), Some("[email protected]")); + assert_eq!(cred.password.as_deref(), Some("p@ss:word%1")); + + let user_only_uri = OperatorUri::new( + "mongodb://[email protected]:27017/analytics/events", + Vec::<(String, String)>::new(), + ) + .unwrap(); + let user_only_cfg = MongodbConfig::from_uri(&user_only_uri).unwrap(); + assert_eq!( + user_only_cfg.connection_string.as_deref(), + Some("mongodb://[email protected]:27017") + ); + + let pass_only_uri = OperatorUri::new( + "mongodb://:only%[email protected]:27017/analytics/events", + Vec::<(String, String)>::new(), + ) + .unwrap(); + let pass_only_cfg = MongodbConfig::from_uri(&pass_only_uri).unwrap(); + assert_eq!( + pass_only_cfg.connection_string.as_deref(), + Some("mongodb://:only%[email protected]:27017") + ); + } + + #[test] + fn from_uri_preserves_explicit_options_over_uri_components() { + let uri = OperatorUri::new( + "mongodb://root:[email protected]:27017/analytics/events/session?root=override", + vec![( + "connection_string".to_string(), + "mongodb://custom:27018".to_string(), + )], + ) + .unwrap(); + + let cfg = MongodbConfig::from_uri(&uri).unwrap(); + assert_eq!( + cfg.connection_string.as_deref(), + Some("mongodb://custom:27018") + ); + assert_eq!(cfg.database.as_deref(), Some("analytics")); + assert_eq!(cfg.collection.as_deref(), Some("events")); + assert_eq!(cfg.root.as_deref(), Some("override")); + } } diff --git a/core/services/mongodb/src/core.rs b/core/services/mongodb/src/core.rs index 57fd5f6980..26c10904aa 100644 --- a/core/services/mongodb/src/core.rs +++ b/core/services/mongodb/src/core.rs @@ -23,12 +23,15 @@ use mongodb::bson::Bson; use mongodb::bson::Document; use mongodb::bson::doc; use mongodb::options::ClientOptions; +use mongodb::options::ConnectionString; use opendal_core::*; +const DUPLICATE_KEY_ERROR_CODE: i32 = 11000; + #[derive(Clone)] pub struct MongodbCore { - pub connection_string: String, + pub connection_string: ConnectionString, pub database: String, pub collection: String, pub collection_instance: OnceCell<mongodb::Collection<Document>>, @@ -51,11 +54,11 @@ impl MongodbCore { async fn get_collection(&self) -> Result<&mongodb::Collection<Document>> { self.collection_instance .get_or_try_init(|| async { - let client_options = ClientOptions::parse(&self.connection_string) + let client_options = ClientOptions::parse(self.connection_string.clone()) .await - .map_err(parse_mongodb_error)?; - let client = - mongodb::Client::with_options(client_options).map_err(parse_mongodb_error)?; + .map_err(parse_mongodb_config_error)?; + let client = mongodb::Client::with_options(client_options) + .map_err(parse_mongodb_config_error)?; let database = client.database(&self.database); let collection = database.collection(&self.collection); Ok(collection) @@ -65,16 +68,14 @@ impl MongodbCore { pub async fn get(&self, path: &str) -> Result<Option<Buffer>> { let collection = self.get_collection().await?; - let filter = doc! {self.key_field.as_str():path}; + let filter = doc! {self.key_field.as_str(): path}; let result = collection .find_one(filter) .await .map_err(parse_mongodb_error)?; match result { Some(doc) => { - let value = doc - .get_binary_generic(&self.value_field) - .map_err(parse_bson_error)?; + let value = get_binary_field(&doc, &self.value_field)?; Ok(Some(Buffer::from(value.to_vec()))) } None => Ok(None), @@ -109,30 +110,109 @@ impl MongodbCore { pub async fn set(&self, path: &str, value: Buffer) -> Result<()> { let collection = self.get_collection().await?; - let filter = doc! { self.key_field.as_str(): path }; - let update = doc! { "$set": { self.value_field.as_str(): Binary { subtype: mongodb::bson::spec::BinarySubtype::Generic, bytes: value.to_vec() } } }; - collection - .update_one(filter, update) + let make_update = || { + doc! { + "$set": { + self.value_field.as_str(): Binary { + subtype: mongodb::bson::spec::BinarySubtype::Generic, + bytes: value.to_vec(), + } + } + } + }; + + match collection + .update_one(doc! { self.key_field.as_str(): path }, make_update()) .upsert(true) .await - .map_err(parse_mongodb_error)?; - - Ok(()) + { + Ok(_) => Ok(()), + // Concurrent upserts against a unique index on `key_field` can fail + // with E11000 (MongoDB SERVER-14322); retrying once updates the + // document inserted by the winning writer. + Err(err) if is_duplicate_key_error(&err) => collection + .update_one(doc! { self.key_field.as_str(): path }, make_update()) + .upsert(true) + .await + .map(|_| ()) + .map_err(|retry_err| { + let is_dup = is_duplicate_key_error(&retry_err); + let err = parse_mongodb_error(retry_err); + if is_dup { err.set_temporary() } else { err } + }), + Err(err) => Err(parse_mongodb_error(err)), + } } pub async fn delete(&self, path: &str) -> Result<()> { let collection = self.get_collection().await?; - let filter = doc! {self.key_field.as_str():path}; + let filter = doc! {self.key_field.as_str(): path}; collection - .delete_one(filter) + .delete_many(filter) .await .map_err(parse_mongodb_error)?; Ok(()) } } +fn get_binary_field<'a>(doc: &'a Document, field_path: &str) -> Result<&'a [u8]> { + let mut segments = field_path.split('.'); + let mut current = doc; + let mut segment = segments + .next() + .filter(|segment| !segment.is_empty()) + .ok_or_else(|| Error::new(ErrorKind::ConfigInvalid, "value_field is invalid"))?; + + for next in segments { + current = current.get_document(segment).map_err(parse_bson_error)?; + segment = next; + } + + current + .get_binary_generic(segment) + .map(Vec::as_slice) + .map_err(parse_bson_error) +} + +fn is_duplicate_key_error(err: &mongodb::error::Error) -> bool { + match err.kind.as_ref() { + mongodb::error::ErrorKind::Write(mongodb::error::WriteFailure::WriteError(write_err)) => { + write_err.code == DUPLICATE_KEY_ERROR_CODE + } + mongodb::error::ErrorKind::Command(cmd_err) => cmd_err.code == DUPLICATE_KEY_ERROR_CODE, + _ => false, + } +} + +fn parse_mongodb_config_error(err: mongodb::error::Error) -> Error { + match err.kind.as_ref() { + mongodb::error::ErrorKind::InvalidArgument { .. } + | mongodb::error::ErrorKind::InvalidTlsConfig { .. } => Error::new( + ErrorKind::ConfigInvalid, + "mongodb client configuration is invalid", + ) + .set_source(err), + _ => parse_mongodb_error(err), + } +} + fn parse_mongodb_error(err: mongodb::error::Error) -> Error { - Error::new(ErrorKind::Unexpected, "mongodb error").set_source(err) + let is_temporary = err.contains_label(mongodb::error::TRANSIENT_TRANSACTION_ERROR) + || err.contains_label(mongodb::error::RETRYABLE_WRITE_ERROR) + || matches!( + err.kind.as_ref(), + mongodb::error::ErrorKind::Io(_) + | mongodb::error::ErrorKind::ConnectionPoolCleared { .. } + | mongodb::error::ErrorKind::ServerSelection { .. } + | mongodb::error::ErrorKind::DnsResolve { .. } + ); + + let opendal_err = Error::new(ErrorKind::Unexpected, "mongodb error").set_source(err); + if is_temporary { + opendal_err.set_temporary() + } else { + opendal_err + } } fn parse_bson_error(err: mongodb::bson::document::ValueAccessError) -> Error { @@ -161,6 +241,7 @@ fn parse_bson_usize(value: Option<&Bson>) -> Result<Option<usize>> { #[cfg(test)] mod tests { use super::*; + use mongodb::bson::spec::BinarySubtype; #[test] fn test_parse_bson_usize() { @@ -170,4 +251,60 @@ mod tests { assert!(parse_bson_usize(Some(&Bson::Int32(-1))).is_err()); assert!(parse_bson_usize(Some(&Bson::String("6".to_string()))).is_err()); } + + #[test] + fn test_get_binary_field() { + let binary = Binary { + subtype: BinarySubtype::Generic, + bytes: b"hello".to_vec(), + }; + let doc = doc! { + "value": binary.clone(), + "payload": { + "data": binary.clone(), + "deep": { + "blob": binary, + }, + "not_a_doc": 42_i32, + "not_binary": "text", + }, + }; + + assert_eq!(get_binary_field(&doc, "value").unwrap(), b"hello"); + assert_eq!(get_binary_field(&doc, "payload.data").unwrap(), b"hello"); + assert_eq!( + get_binary_field(&doc, "payload.deep.blob").unwrap(), + b"hello" + ); + + assert_eq!( + get_binary_field(&doc, "payload.missing") + .unwrap_err() + .kind(), + ErrorKind::Unexpected + ); + assert_eq!( + get_binary_field(&doc, "missing.data").unwrap_err().kind(), + ErrorKind::Unexpected + ); + assert_eq!( + get_binary_field(&doc, "payload.not_a_doc.leaf") + .unwrap_err() + .kind(), + ErrorKind::Unexpected + ); + assert_eq!( + get_binary_field(&doc, "payload.not_binary") + .unwrap_err() + .kind(), + ErrorKind::Unexpected + ); + } + + #[test] + fn test_parse_mongodb_config_error_maps_invalid_argument() { + let invalid = ConnectionString::parse("not-a-mongodb-uri").unwrap_err(); + let err = parse_mongodb_config_error(invalid); + assert_eq!(err.kind(), ErrorKind::ConfigInvalid); + } } diff --git a/core/services/mongodb/src/docs.md b/core/services/mongodb/src/docs.md index c5698374de..572cd53125 100644 --- a/core/services/mongodb/src/docs.md +++ b/core/services/mongodb/src/docs.md @@ -21,6 +21,10 @@ Use [`crate::MongodbConfig`] for serializable configuration and this builder's methods for direct construction. The field and method documentation defines accepted values, defaults, and environment interaction. +Create a unique index on `key_field` (for example, +`db.<collection>.createIndex({ key: 1 }, { unique: true })`) so concurrent +writes to the same key cannot insert duplicate documents. + ## Example ### Via Builder
