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 3de03f9be1 fix(services/mongodb): fix duplicate delete/E11000 upsert,
nested value_field reads, and config/URI validation (#8961)
3de03f9be1 is described below
commit 3de03f9be11da783ef61a4e7b6ec53b64d8c8d38
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 09:53:13 2026 +0800
fix(services/mongodb): fix duplicate delete/E11000 upsert, nested
value_field reads, and config/URI validation (#8961)
* fix(services/mongodb): fix duplicate delete/E11000 upsert, nested
value_field reads, and config/URI validation
* fix(services/mongodb): include database in synthesized URI, scope E11000
retries to key_field, and narrow temporary IO errors
---
core/services/mongodb/src/backend.rs | 152 +++++++++++--
core/services/mongodb/src/config.rs | 165 +++++++++++++-
core/services/mongodb/src/core.rs | 407 +++++++++++++++++++++++++++++++++--
core/services/mongodb/src/docs.md | 4 +
4 files changed, 684 insertions(+), 44 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..f4f47a025e 100644
--- a/core/services/mongodb/src/config.rs
+++ b/core/services/mongodb/src/config.rs
@@ -53,17 +53,30 @@ impl Debug for MongodbConfig {
}
}
+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 opendal_core::Configurator for MongodbConfig {
type Builder = MongodbBuilder;
fn from_uri(uri: &opendal_core::OperatorUri) -> opendal_core::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()
{
@@ -83,10 +96,41 @@ 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());
}
}
+ 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, Some(_)) => {
+ return Err(opendal_core::Error::new(
+ opendal_core::ErrorKind::ConfigInvalid,
+ "mongodb URI password requires a username",
+ )
+ .with_context("service", crate::MONGODB_SCHEME));
+ }
+ (None, 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)
}
@@ -98,7 +142,11 @@ impl opendal_core::Configurator for MongodbConfig {
#[cfg(test)]
mod tests {
use super::*;
+ use mongodb::options::ClientOptions;
+ use mongodb::options::ConnectionString;
+ use opendal_core::Builder;
use opendal_core::Configurator;
+ use opendal_core::ErrorKind;
use opendal_core::OperatorUri;
#[test]
@@ -112,10 +160,113 @@ mod tests {
let cfg = MongodbConfig::from_uri(&uri).unwrap();
assert_eq!(
cfg.connection_string.as_deref(),
- Some("mongodb://mongo.internal:27017")
+ Some("mongodb://mongo.internal:27017/analytics")
);
assert_eq!(cfg.database.as_deref(), Some("analytics"));
assert_eq!(cfg.collection.as_deref(), Some("events"));
assert_eq!(cfg.root.as_deref(), Some("session"));
+
+ let parsed =
ConnectionString::parse(cfg.connection_string.as_deref().unwrap()).unwrap();
+ assert_eq!(parsed.default_database.as_deref(), Some("analytics"));
+ assert!(cfg.into_builder().build().is_ok());
+
+ let no_db_uri = OperatorUri::new(
+ "mongodb://mongo.internal:27017",
+ Vec::<(String, String)>::new(),
+ )
+ .unwrap();
+ let no_db_cfg = MongodbConfig::from_uri(&no_db_uri).unwrap();
+ assert_eq!(
+ no_db_cfg.connection_string.as_deref(),
+ Some("mongodb://mongo.internal:27017")
+ );
+ assert_eq!(no_db_cfg.database, None);
+ }
+
+ #[tokio::test]
+ async fn from_uri_preserves_and_percent_encodes_credentials_and_database()
{
+ let uri = OperatorUri::new(
+
"mongodb://alice%40corp.com:p%40ss%3Aword%[email protected]:27017/analytics%231/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/analytics%231"
+ );
+ assert_eq!(cfg.database.as_deref(), Some("analytics#1"));
+
+ let parsed = ConnectionString::parse(conn_str).unwrap();
+ assert_eq!(parsed.default_database.as_deref(), Some("analytics#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%1"));
+
+ let client_opts = ClientOptions::parse(parsed).await.unwrap();
+ assert_eq!(
+ client_opts
+ .credential
+ .as_ref()
+ .and_then(|c| c.source.as_deref()),
+ Some("analytics#1")
+ );
+ assert!(cfg.into_builder().build().is_ok());
+
+ 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/analytics")
+ );
+ assert!(user_only_cfg.into_builder().build().is_ok());
+
+ let pass_only_uri = OperatorUri::new(
+ "mongodb://:only%[email protected]:27017/analytics/events",
+ Vec::<(String, String)>::new(),
+ )
+ .unwrap();
+ let err = MongodbConfig::from_uri(&pass_only_uri).unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid);
+ }
+
+ #[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"));
+
+ let db_override_uri = OperatorUri::new(
+ "mongodb://demo_u:[email protected]:27017/ignored/events",
+ vec![("database".to_string(), "target_db".to_string())],
+ )
+ .unwrap();
+ let db_override_cfg =
MongodbConfig::from_uri(&db_override_uri).unwrap();
+ 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.collection.as_deref(), Some("events"));
}
}
diff --git a/core/services/mongodb/src/core.rs
b/core/services/mongodb/src/core.rs
index 57fd5f6980..7a99df1e66 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,160 @@ 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_key_field_duplicate_key_error(&err,
&self.key_field, path) => collection
+ .update_one(doc! { self.key_field.as_str(): path },
make_update())
+ .upsert(true)
+ .await
+ .map(|_| ())
+ .map_err(|retry_err| {
+ let is_key_dup =
+ is_key_field_duplicate_key_error(&retry_err,
&self.key_field, path);
+ let err = parse_mongodb_error(retry_err);
+ if is_key_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_key_field_duplicate_key_message(message: &str, key_field: &str, path:
&str) -> bool {
+ let Some((_, dup_key)) = message.split_once(" dup key: { ") else {
+ return false;
+ };
+ let Some(rest) = dup_key.strip_prefix(key_field) else {
+ return false;
+ };
+ let Some(rest) = rest.strip_prefix(": \"") else {
+ return false;
+ };
+ let Some(reported_value) = rest.strip_suffix("\" }") else {
+ return false;
+ };
+
+ reported_value == path
+ || reported_value.strip_suffix("...").is_some_and(|prefix| {
+ // MongoDB truncates long dup key values by byte length, which may
+ // end a multi-byte UTF-8 sequence with a replacement character.
+ let prefix = prefix.trim_end_matches('\u{FFFD}');
+ !prefix.is_empty() && path.len() > prefix.len() &&
path.starts_with(prefix)
+ })
+}
+
+fn is_key_field_duplicate_key_error(
+ err: &mongodb::error::Error,
+ key_field: &str,
+ path: &str,
+) -> bool {
+ let message = match err.kind.as_ref() {
+
mongodb::error::ErrorKind::Write(mongodb::error::WriteFailure::WriteError(write_err))
+ if write_err.code == DUPLICATE_KEY_ERROR_CODE =>
+ {
+ write_err.message.as_str()
+ }
+ mongodb::error::ErrorKind::Command(cmd_err) if cmd_err.code ==
DUPLICATE_KEY_ERROR_CODE => {
+ cmd_err.message.as_str()
+ }
+ _ => return false,
+ };
+
+ is_key_field_duplicate_key_message(message, key_field, path)
+}
+
+fn is_transient_io_error(err: &std::io::Error) -> bool {
+ matches!(
+ err.kind(),
+ std::io::ErrorKind::ConnectionReset
+ | std::io::ErrorKind::ConnectionAborted
+ | std::io::ErrorKind::BrokenPipe
+ | std::io::ErrorKind::TimedOut
+ | std::io::ErrorKind::Interrupted
+ | std::io::ErrorKind::WouldBlock
+ | std::io::ErrorKind::UnexpectedEof
+ | std::io::ErrorKind::ConnectionRefused
+ | std::io::ErrorKind::NotConnected
+ | std::io::ErrorKind::NetworkUnreachable
+ | std::io::ErrorKind::HostUnreachable
+ )
+}
+
+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)
+ || match err.kind.as_ref() {
+ mongodb::error::ErrorKind::Io(io_err) =>
is_transient_io_error(io_err),
+ mongodb::error::ErrorKind::ConnectionPoolCleared { .. }
+ | mongodb::error::ErrorKind::ServerSelection { .. }
+ | mongodb::error::ErrorKind::DnsResolve { .. } => true,
+ _ => false,
+ };
+
+ 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 +292,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 +302,241 @@ 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);
+ }
+
+ fn make_write_error(code: i32, errmsg: &str) -> mongodb::error::Error {
+ let write_err: mongodb::error::WriteError =
mongodb::bson::from_document(doc! {
+ "code": code,
+ "errmsg": errmsg,
+ })
+ .unwrap();
+ mongodb::error::Error::from(mongodb::error::ErrorKind::Write(
+ mongodb::error::WriteFailure::WriteError(write_err),
+ ))
+ }
+
+ fn make_command_error(code: i32, errmsg: &str) -> mongodb::error::Error {
+ let cmd_err: mongodb::error::CommandError =
mongodb::bson::from_document(doc! {
+ "code": code,
+ "codeName": "DuplicateKey",
+ "errmsg": errmsg,
+ })
+ .unwrap();
+
mongodb::error::Error::from(mongodb::error::ErrorKind::Command(cmd_err))
+ }
+
+ #[test]
+ fn test_is_key_field_duplicate_key_error() {
+ let flat_key = make_write_error(
+ 11000,
+ r#"Plan executor error during update :: caused by :: E11000
duplicate key error collection: demo.demo index: key_1 dup key: { key: "/a/b"
}"#,
+ );
+ assert!(is_key_field_duplicate_key_error(&flat_key, "key", "/a/b"));
+ assert!(!is_key_field_duplicate_key_error(
+ &flat_key, "key", "/other"
+ ));
+
+ let custom_idx = make_write_error(
+ 11000,
+ r#"Plan executor error during update :: caused by :: E11000
duplicate key error collection: demo.demo index: custom_unique_idx dup key: {
key: "/a/b" }"#,
+ );
+ assert!(is_key_field_duplicate_key_error(&custom_idx, "key", "/a/b"));
+
+ let nested_key = make_command_error(
+ 11000,
+ r#"E11000 duplicate key error collection: demo.demo index:
meta.key_1 dup key: { meta.key: "/a/b" }"#,
+ );
+ assert!(is_key_field_duplicate_key_error(
+ &nested_key,
+ "meta.key",
+ "/a/b"
+ ));
+
+ let id_key = make_write_error(
+ 11000,
+ r#"E11000 duplicate key error collection: demo.demo index: _id_
dup key: { _id: "/a/b" }"#,
+ );
+ assert!(is_key_field_duplicate_key_error(&id_key, "_id", "/a/b"));
+
+ let long_ascii = "x".repeat(200);
+ let truncated_ascii = make_write_error(
+ 11000,
+ &format!(
+ r#"E11000 duplicate key error collection: demo.demo index:
key_1 dup key: {{ key: "{}..." }}"#,
+ "x".repeat(150)
+ ),
+ );
+ assert!(is_key_field_duplicate_key_error(
+ &truncated_ascii,
+ "key",
+ &long_ascii
+ ));
+
+ let long_utf8 = "🚀".repeat(40);
+ let truncated_utf8 = make_write_error(
+ 11000,
+ &format!(
+ "E11000 duplicate key error collection: demo.demo index: key_1
dup key: {{ key: \"{}\u{FFFD}...\" }}",
+ "🚀".repeat(37)
+ ),
+ );
+ assert!(is_key_field_duplicate_key_error(
+ &truncated_utf8,
+ "key",
+ &long_utf8
+ ));
+
+ let value_dup = make_write_error(
+ 11000,
+ r#"Plan executor error during update :: caused by :: E11000
duplicate key error collection: demo.demo index: value_1 dup key: { value:
BinData(0, 616263) }"#,
+ );
+ assert!(!is_key_field_duplicate_key_error(&value_dup, "key", "/a/b"));
+
+ let prefix_field_dup = make_write_error(
+ 11000,
+ r#"E11000 duplicate key error collection: demo.demo index: key2_1
dup key: { key2: "/a/b" }"#,
+ );
+ assert!(!is_key_field_duplicate_key_error(
+ &prefix_field_dup,
+ "key",
+ "/a/b"
+ ));
+
+ let spoofed_value_dup = make_write_error(
+ 11000,
+ r#"Plan executor error during update :: caused by :: E11000
duplicate key error collection: demo.demo index: value_1 dup key: { value: "dup
key: { key: "/a/b" }" }"#,
+ );
+ assert!(!is_key_field_duplicate_key_error(
+ &spoofed_value_dup,
+ "key",
+ "/a/b"
+ ));
+
+ let compound_dup = make_write_error(
+ 11000,
+ r#"E11000 duplicate key error collection: demo.demo index:
key_1_other_1 dup key: { key: "/a/b", other: "o1" }"#,
+ );
+ assert!(!is_key_field_duplicate_key_error(
+ &compound_dup,
+ "key",
+ "/a/b"
+ ));
+
+ let non_dup_code = make_write_error(
+ 121,
+ r#"E11000 duplicate key error collection: demo.demo index: key_1
dup key: { key: "/a/b" }"#,
+ );
+ assert!(!is_key_field_duplicate_key_error(
+ &non_dup_code,
+ "key",
+ "/a/b"
+ ));
+ }
+
+ #[test]
+ fn test_parse_mongodb_error_io_temporary_classification() {
+ for transient_kind in [
+ std::io::ErrorKind::ConnectionReset,
+ std::io::ErrorKind::ConnectionAborted,
+ std::io::ErrorKind::BrokenPipe,
+ std::io::ErrorKind::TimedOut,
+ std::io::ErrorKind::Interrupted,
+ std::io::ErrorKind::WouldBlock,
+ std::io::ErrorKind::UnexpectedEof,
+ std::io::ErrorKind::ConnectionRefused,
+ std::io::ErrorKind::NotConnected,
+ std::io::ErrorKind::NetworkUnreachable,
+ std::io::ErrorKind::HostUnreachable,
+ ] {
+ let err =
parse_mongodb_error(mongodb::error::Error::from(std::io::Error::new(
+ transient_kind,
+ "transient io",
+ )));
+ assert_eq!(err.kind(), ErrorKind::Unexpected);
+ assert!(
+ err.is_temporary(),
+ "expected {transient_kind:?} to be temporary"
+ );
+ }
+
+ for permanent_kind in [
+ std::io::ErrorKind::InvalidData,
+ std::io::ErrorKind::InvalidInput,
+ std::io::ErrorKind::PermissionDenied,
+ std::io::ErrorKind::NotFound,
+ std::io::ErrorKind::Other,
+ ] {
+ let err =
parse_mongodb_error(mongodb::error::Error::from(std::io::Error::new(
+ permanent_kind,
+ "permanent io",
+ )));
+ assert_eq!(err.kind(), ErrorKind::Unexpected);
+ assert!(
+ !err.is_temporary(),
+ "expected {permanent_kind:?} to be permanent"
+ );
+ }
+
+ let value_dup_err = parse_mongodb_error(make_write_error(
+ 11000,
+ r#"Plan executor error during update :: caused by :: E11000
duplicate key error collection: demo.demo index: value_1 dup key: { value:
BinData(0, 616263) }"#,
+ ));
+ assert_eq!(value_dup_err.kind(), ErrorKind::Unexpected);
+ assert!(!value_dup_err.is_temporary());
+ }
}
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