diff --git a/Cargo.lock b/Cargo.lock index c9964eac3..0289d568b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -237,7 +237,7 @@ dependencies = [ [[package]] name = "bson" version = "3.0.0" -source = "git+https://github.com/mongodb/bson-rust?branch=main#8389d37175a6e9018ac82dacd62b20415e9c4469" +source = "git+https://github.com/mongodb/bson-rust?branch=main#1669bc07652999f15e15d73ba658e63c0dace815" dependencies = [ "ahash", "base64 0.22.1", @@ -1524,8 +1524,8 @@ dependencies = [ [[package]] name = "mongocrypt" -version = "0.3.0" -source = "git+https://github.com/mongodb/libmongocrypt-rust.git?branch=main#6e4bb967f47ea564102e0a0a6d27468d2949e381" +version = "0.3.1" +source = "git+https://github.com/mongodb/libmongocrypt-rust.git?branch=main#66c4ee29a2184c26ff5d7b290a23b5fdcf9c7d26" dependencies = [ "bson 2.15.0", "bson 3.0.0", @@ -1537,7 +1537,7 @@ dependencies = [ [[package]] name = "mongocrypt-sys" version = "0.1.4+1.12.0" -source = "git+https://github.com/mongodb/libmongocrypt-rust.git?branch=main#6e4bb967f47ea564102e0a0a6d27468d2949e381" +source = "git+https://github.com/mongodb/libmongocrypt-rust.git?branch=main#66c4ee29a2184c26ff5d7b290a23b5fdcf9c7d26" [[package]] name = "mongodb" diff --git a/Cargo.toml b/Cargo.toml index df35d4758..e9cfb1eed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -134,11 +134,12 @@ branch = "main" package = "bson" version = "3.0.0" optional = true +features = ["serde"] [dependencies.mongocrypt] git = "https://github.com/mongodb/libmongocrypt-rust.git" branch = "main" -version = "0.3.0" +version = "0.3.1" default-features = false optional = true diff --git a/src/action/find_and_modify.rs b/src/action/find_and_modify.rs index 02bfed20e..72be715c3 100644 --- a/src/action/find_and_modify.rs +++ b/src/action/find_and_modify.rs @@ -107,7 +107,8 @@ impl Collection { FindOneAndReplace { coll: self, filter, - replacement: crate::bson::to_raw_document_buf(replacement.borrow()).map_err(Into::into), + replacement: crate::bson_compat::serialize_to_raw_document_buf(replacement.borrow()) + .map_err(Into::into), options: None, session: None, } diff --git a/src/action/insert_many.rs b/src/action/insert_many.rs index ab5d7a289..62754ba4e 100644 --- a/src/action/insert_many.rs +++ b/src/action/insert_many.rs @@ -34,7 +34,10 @@ impl Collection { coll: CollRef::new(self), docs: docs .into_iter() - .map(|v| crate::bson::to_raw_document_buf(v.borrow()).map_err(Into::into)) + .map(|v| { + crate::bson_compat::serialize_to_raw_document_buf(v.borrow()) + .map_err(Into::into) + }) .collect(), options: None, session: None, diff --git a/src/action/insert_one.rs b/src/action/insert_one.rs index 73fba689c..b08a0d7d5 100644 --- a/src/action/insert_one.rs +++ b/src/action/insert_one.rs @@ -32,7 +32,8 @@ impl Collection { pub fn insert_one(&self, doc: impl Borrow) -> InsertOne { InsertOne { coll: CollRef::new(self), - doc: crate::bson::to_raw_document_buf(doc.borrow()).map_err(Into::into), + doc: crate::bson_compat::serialize_to_raw_document_buf(doc.borrow()) + .map_err(Into::into), options: None, session: None, } diff --git a/src/action/list_databases.rs b/src/action/list_databases.rs index 34b4942e8..2d2c59dd1 100644 --- a/src/action/list_databases.rs +++ b/src/action/list_databases.rs @@ -106,7 +106,7 @@ impl<'a> Action for ListDatabases<'a, ListSpecifications> { .and_then(|dbs| { dbs.into_iter() .map(|db_spec| { - crate::bson::from_slice(db_spec.as_bytes()) + crate::bson_compat::deserialize_from_slice(db_spec.as_bytes()) .map_err(crate::error::Error::from) }) .collect() diff --git a/src/action/replace_one.rs b/src/action/replace_one.rs index 06979dce5..af3d31392 100644 --- a/src/action/replace_one.rs +++ b/src/action/replace_one.rs @@ -31,7 +31,8 @@ impl Collection { ReplaceOne { coll: CollRef::new(self), query, - replacement: crate::bson::to_raw_document_buf(replacement.borrow()).map_err(Into::into), + replacement: crate::bson_compat::serialize_to_raw_document_buf(replacement.borrow()) + .map_err(Into::into), options: None, session: None, } diff --git a/src/bson_compat.rs b/src/bson_compat.rs index 9b927757d..3ce3682f4 100644 --- a/src/bson_compat.rs +++ b/src/bson_compat.rs @@ -1,31 +1,132 @@ -#[cfg(feature = "bson-3")] -pub(crate) trait RawDocumentBufExt { - fn append_ref<'a>( +use crate::bson::RawBson; + +pub(crate) trait RawDocumentBufExt: Sized { + fn append_err(&mut self, key: impl AsRef, value: impl Into) -> RawResult<()>; + + fn append_ref_err<'a>( &mut self, key: impl AsRef, value: impl Into>, - ); + ) -> RawResult<()>; + + #[cfg(not(feature = "bson-3"))] + fn decode_from_bytes(data: Vec) -> RawResult; } #[cfg(feature = "bson-3")] impl RawDocumentBufExt for crate::bson::RawDocumentBuf { - fn append_ref<'a>( + fn append_err(&mut self, key: impl AsRef, value: impl Into) -> RawResult<()> { + self.append(key, value.into()) + } + + fn append_ref_err<'a>( &mut self, key: impl AsRef, value: impl Into>, - ) { + ) -> RawResult<()> { self.append(key, value) } } +#[cfg(not(feature = "bson-3"))] +impl RawDocumentBufExt for crate::bson::RawDocumentBuf { + fn append_err(&mut self, key: impl AsRef, value: impl Into) -> RawResult<()> { + self.append(key, value); + Ok(()) + } + + fn append_ref_err<'a>( + &mut self, + key: impl AsRef, + value: impl Into>, + ) -> RawResult<()> { + self.append_ref(key, value); + Ok(()) + } + + fn decode_from_bytes(data: Vec) -> RawResult { + Self::from_bytes(data) + } +} + +pub(crate) trait RawArrayBufExt: Sized { + #[allow(dead_code)] + fn from_iter_err, I: IntoIterator>(iter: I) -> RawResult; + + fn push_err(&mut self, value: impl Into) -> RawResult<()>; +} + #[cfg(feature = "bson-3")] -pub(crate) use crate::bson::error::Result as RawResult; +impl RawArrayBufExt for crate::bson::RawArrayBuf { + fn from_iter_err, I: IntoIterator>(iter: I) -> RawResult { + Self::from_iter(iter.into_iter().map(|v| v.into())) + } + + fn push_err(&mut self, value: impl Into) -> RawResult<()> { + self.push(value.into()) + } +} #[cfg(not(feature = "bson-3"))] -pub(crate) use crate::bson::raw::Result as RawResult; +impl RawArrayBufExt for crate::bson::RawArrayBuf { + fn from_iter_err, I: IntoIterator>(iter: I) -> RawResult { + Ok(Self::from_iter(iter)) + } -#[cfg(feature = "bson-3")] -pub(crate) use crate::bson::error::Error as RawError; + fn push_err(&mut self, value: impl Into) -> RawResult<()> { + self.push(value); + Ok(()) + } +} #[cfg(not(feature = "bson-3"))] -pub(crate) use crate::bson::raw::Error as RawError; +pub(crate) trait RawDocumentExt { + fn decode_from_bytes + ?Sized>(data: &D) -> RawResult<&Self>; +} + +#[cfg(not(feature = "bson-3"))] +impl RawDocumentExt for crate::bson::RawDocument { + fn decode_from_bytes + ?Sized>(data: &D) -> RawResult<&Self> { + Self::from_bytes(data) + } +} + +#[cfg(not(feature = "bson-3"))] +#[allow(dead_code)] +pub(crate) trait DocumentExt { + fn encode_to_vec(&self) -> crate::bson::ser::Result>; +} + +#[cfg(not(feature = "bson-3"))] +impl DocumentExt for crate::bson::Document { + fn encode_to_vec(&self) -> crate::bson::ser::Result> { + let mut out = vec![]; + self.to_writer(&mut out)?; + Ok(out) + } +} + +macro_rules! use_either { + ($($name:ident => $path3:path | $path2:path);+;) => { + $( + #[cfg(feature = "bson-3")] + pub(crate) use crate::bson::{$path3 as $name}; + + #[cfg(not(feature = "bson-3"))] + #[allow(unused_imports)] + pub(crate) use crate::bson::{$path2 as $name}; + )+ + }; +} + +// Exported name => bson3 import | bson2 import +use_either! { + RawResult => error::Result | raw::Result; + RawError => error::Error | raw::Error; + serialize_to_raw_document_buf => serialize_to_raw_document_buf | to_raw_document_buf; + serialize_to_document => serialize_to_document | to_document; + serialize_to_bson => serialize_to_bson | to_bson; + deserialize_from_slice => deserialize_from_slice | from_slice; + deserialize_from_document => deserialize_from_document | from_document; + deserialize_from_bson => deserialize_from_bson | from_bson; +} diff --git a/src/bson_util.rs b/src/bson_util.rs index 159c2c124..48ab584b9 100644 --- a/src/bson_util.rs +++ b/src/bson_util.rs @@ -17,14 +17,12 @@ use crate::{ RawBsonRef, RawDocumentBuf, }, + bson_compat::{RawArrayBufExt, RawDocumentBufExt as _}, checked::Checked, error::{Error, ErrorKind, Result}, runtime::SyncLittleEndianRead, }; -#[cfg(feature = "bson-3")] -use crate::bson_compat::RawDocumentBufExt as _; - /// Coerce numeric types into an `i64` if it would be lossless to do so. If this Bson is not numeric /// or the conversion would be lossy (e.g. 1.5 -> 1), this returns `None`. #[allow(clippy::cast_possible_truncation)] @@ -80,14 +78,14 @@ pub(crate) fn to_bson_array(docs: &[Document]) -> Bson { pub(crate) fn to_raw_bson_array(docs: &[Document]) -> Result { let mut array = RawArrayBuf::new(); for doc in docs { - array.push(RawDocumentBuf::from_document(doc)?); + array.push_err(RawDocumentBuf::from_document(doc)?)?; } Ok(RawBson::Array(array)) } pub(crate) fn to_raw_bson_array_ser(values: &[T]) -> Result { let mut array = RawArrayBuf::new(); for value in values { - array.push(crate::bson::to_raw_document_buf(value)?); + array.push_err(crate::bson_compat::serialize_to_raw_document_buf(value)?)?; } Ok(RawBson::Array(array)) } @@ -149,12 +147,12 @@ pub(crate) fn array_entry_size_bytes(index: usize, doc_len: usize) -> Result) -> RawArrayBuf { +pub(crate) fn vec_to_raw_array_buf(docs: Vec) -> Result { let mut array = RawArrayBuf::new(); for doc in docs { - array.push(doc); + array.push_err(doc)?; } - array + Ok(array) } /// The number of digits in `n` in base 10. @@ -202,7 +200,7 @@ pub(crate) fn extend_raw_document_buf( k ))); } - this.append(k, v.to_raw_bson()); + this.append_err(k, v.to_raw_bson())?; } Ok(()) } @@ -216,13 +214,13 @@ pub(crate) fn append_ser( struct Helper { value: T, } - let raw_doc = crate::bson::to_raw_document_buf(&Helper { value })?; - this.append_ref( + let raw_doc = crate::bson_compat::serialize_to_raw_document_buf(&Helper { value })?; + this.append_ref_err( key, raw_doc .get("value")? .ok_or_else(|| Error::internal("no value"))?, - ); + )?; Ok(()) } @@ -243,7 +241,7 @@ pub(crate) fn get_or_prepend_id_field(doc: &mut RawDocumentBuf) -> Result let new_length: i32 = Checked::new(new_bytes.len()).try_into()?; new_bytes[0..4].copy_from_slice(&new_length.to_le_bytes()); - *doc = RawDocumentBuf::from_bytes(new_bytes)?; + *doc = RawDocumentBuf::decode_from_bytes(new_bytes)?; Ok(id.into()) } diff --git a/src/change_stream.rs b/src/change_stream.rs index 8bf21510a..12ba1ae12 100644 --- a/src/change_stream.rs +++ b/src/change_stream.rs @@ -158,7 +158,9 @@ where /// ``` pub async fn next_if_any(&mut self) -> Result> { Ok(match NextInBatchFuture::new(self).await? { - BatchValue::Some { doc, .. } => Some(crate::bson::from_slice(doc.as_bytes())?), + BatchValue::Some { doc, .. } => { + Some(crate::bson_compat::deserialize_from_slice(doc.as_bytes())?) + } BatchValue::Empty | BatchValue::Exhausted => None, }) } diff --git a/src/change_stream/session.rs b/src/change_stream/session.rs index f94793271..f741a559d 100644 --- a/src/change_stream/session.rs +++ b/src/change_stream/session.rs @@ -148,7 +148,9 @@ where match bv { BatchValue::Some { doc, .. } => { self.data.document_returned = true; - return Ok(Some(crate::bson::from_slice(doc.as_bytes())?)); + return Ok(Some(crate::bson_compat::deserialize_from_slice( + doc.as_bytes(), + )?)); } BatchValue::Empty | BatchValue::Exhausted => return Ok(None), } diff --git a/src/client/auth.rs b/src/client/auth.rs index 5f7c9dcb4..3c53c1a29 100644 --- a/src/client/auth.rs +++ b/src/client/auth.rs @@ -14,7 +14,7 @@ mod x509; use std::{borrow::Cow, fmt::Debug, str::FromStr}; -use crate::bson::RawDocumentBuf; +use crate::{bson::RawDocumentBuf, bson_compat::RawDocumentBufExt as _}; use derive_where::derive_where; use hmac::{digest::KeyInit, Mac}; use rand::Rng; @@ -240,7 +240,7 @@ impl AuthMechanism { Ok(Some(ClientFirst::Scram(ScramVersion::Sha256, client_first))) } Self::MongoDbX509 => Ok(Some(ClientFirst::X509(Box::new( - x509::build_speculative_client_first(credential), + x509::build_speculative_client_first(credential)?, )))), Self::Plain => Ok(None), Self::MongoDbOidc => Ok(oidc::build_speculative_client_first(credential) @@ -447,13 +447,17 @@ impl Credential { /// If the mechanism is missing, append the appropriate mechanism negotiation key-value-pair to /// the provided hello or legacy hello command document. - pub(crate) fn append_needed_mechanism_negotiation(&self, command: &mut RawDocumentBuf) { + pub(crate) fn append_needed_mechanism_negotiation( + &self, + command: &mut RawDocumentBuf, + ) -> Result<()> { if let (Some(username), None) = (self.username.as_ref(), self.mechanism.as_ref()) { - command.append( + command.append_err( "saslSupportedMechs", format!("{}.{}", self.resolved_source(), username), - ); + )?; } + Ok(()) } /// Attempts to authenticate a stream according to this credential, returning an error @@ -551,12 +555,12 @@ pub(crate) enum ClientFirst { } impl ClientFirst { - pub(crate) fn to_document(&self) -> RawDocumentBuf { - match self { - Self::Scram(version, client_first) => client_first.to_command(version).body, + pub(crate) fn to_document(&self) -> Result { + Ok(match self { + Self::Scram(version, client_first) => client_first.to_command(version)?.body, Self::X509(command) => command.body.clone(), Self::Oidc(command) => command.body.clone(), - } + }) } pub(crate) fn into_first_round(self, server_first: Document) -> FirstRound { diff --git a/src/client/auth/aws.rs b/src/client/auth/aws.rs index ea72cbbd3..cb9a938b5 100644 --- a/src/client/auth/aws.rs +++ b/src/client/auth/aws.rs @@ -25,6 +25,9 @@ use crate::{ serde_util, }; +#[cfg(not(feature = "bson-3"))] +use crate::bson_compat::DocumentExt as _; + const AWS_ECS_IP: &str = "169.254.170.2"; const AWS_EC2_IP: &str = "169.254.169.254"; const AWS_LONG_DATE_FMT: &str = "%Y%m%dT%H%M%SZ"; @@ -72,8 +75,7 @@ async fn authenticate_stream_inner( // channel binding is not supported. "p": 110i32, }; - let mut client_first_payload_bytes = Vec::new(); - client_first_payload.to_writer(&mut client_first_payload_bytes)?; + let client_first_payload_bytes = client_first_payload.encode_to_vec()?; let sasl_start = SaslStart::new( source.into(), @@ -81,7 +83,7 @@ async fn authenticate_stream_inner( client_first_payload_bytes, server_api.cloned(), ); - let client_first = sasl_start.into_command(); + let client_first = sasl_start.into_command()?; let server_first_response = conn.send_message(client_first).await?; @@ -123,8 +125,7 @@ async fn authenticate_stream_inner( client_second_payload.insert("t", security_token); } - let mut client_second_payload_bytes = Vec::new(); - client_second_payload.to_writer(&mut client_second_payload_bytes)?; + let client_second_payload_bytes = client_second_payload.encode_to_vec()?; let sasl_continue = SaslContinue::new( source.into(), @@ -287,7 +288,7 @@ impl AwsCredential { .map_err(|_| Error::unknown_authentication_error(MECH_NAME))? .to_owned(); - Ok(crate::bson::from_document(credential)?) + Ok(crate::bson_compat::deserialize_from_document(credential)?) } /// Obtains credentials from the ECS endpoint. @@ -512,7 +513,7 @@ impl ServerFirst { let ServerFirstPayload { server_nonce, sts_host, - } = crate::bson::from_slice(payload.as_slice()) + } = crate::bson_compat::deserialize_from_slice(payload.as_slice()) .map_err(|_| Error::invalid_authentication_response(MECH_NAME))?; Ok(Self { diff --git a/src/client/auth/oidc.rs b/src/client/auth/oidc.rs index 4655a2438..f3e91eec4 100644 --- a/src/client/auth/oidc.rs +++ b/src/client/auth/oidc.rs @@ -9,6 +9,7 @@ use typed_builder::TypedBuilder; use crate::{ bson::{doc, rawdoc, spec::BinarySubtype, Binary, Document}, + bson_compat::RawDocumentBufExt as _, client::options::{ServerAddress, ServerApi}, cmap::{Command, Connection}, error::{Error, Result}, @@ -619,9 +620,9 @@ async fn send_sasl_start_command( ) -> Result { let mut start_doc = rawdoc! {}; if let Some(access_token) = access_token { - start_doc.append("jwt", access_token); + start_doc.append_err("jwt", access_token)?; } else if let Some(username) = credential.username.as_deref() { - start_doc.append("n", username); + start_doc.append_err("n", username)?; } let sasl_start = SaslStart::new( source.to_string(), @@ -629,7 +630,7 @@ async fn send_sasl_start_command( start_doc.into_bytes(), server_api.cloned(), ) - .into_command(); + .into_command()?; send_sasl_command(conn, sasl_start).await } @@ -687,8 +688,8 @@ async fn do_two_step_function( return Err(invalid_auth_response()); } - let server_info: IdpServerInfo = - crate::bson::from_slice(&response.payload).map_err(|_| invalid_auth_response())?; + let server_info: IdpServerInfo = crate::bson_compat::deserialize_from_slice(&response.payload) + .map_err(|_| invalid_auth_response())?; let idp_response = { let cb_context = CallbackContext { timeout: Some(Instant::now() + timeout), diff --git a/src/client/auth/plain.rs b/src/client/auth/plain.rs index 4b1ae5e2f..0772cd914 100644 --- a/src/client/auth/plain.rs +++ b/src/client/auth/plain.rs @@ -33,7 +33,7 @@ pub(crate) async fn authenticate_stream( payload_bytes(username, password), server_api.cloned(), ) - .into_command(); + .into_command()?; let response = conn.send_message(sasl_start).await?; let sasl_response = SaslResponse::parse("PLAIN", response.auth_response_body("PLAIN")?)?; diff --git a/src/client/auth/sasl.rs b/src/client/auth/sasl.rs index 087134a5f..89d340fb9 100644 --- a/src/client/auth/sasl.rs +++ b/src/client/auth/sasl.rs @@ -2,6 +2,7 @@ use crate::bson::{rawdoc, RawBson}; use crate::{ bson::{spec::BinarySubtype, Binary, Bson, Document}, + bson_compat::RawDocumentBufExt as _, bson_util, client::{auth::AuthMechanism, options::ServerApi}, cmap::Command, @@ -32,7 +33,7 @@ impl SaslStart { } } - pub(super) fn into_command(self) -> Command { + pub(super) fn into_command(self) -> Result { let mut body = rawdoc! { "saslStart": 1, "mechanism": self.mechanism.as_str(), @@ -41,7 +42,7 @@ impl SaslStart { if self.mechanism == AuthMechanism::ScramSha1 || self.mechanism == AuthMechanism::ScramSha256 { - body.append("options", rawdoc! { "skipEmptyExchange": true }); + body.append_err("options", rawdoc! { "skipEmptyExchange": true })?; } let mut command = Command::new("saslStart", self.source, body); @@ -49,7 +50,7 @@ impl SaslStart { command.set_server_api(&server_api); } - command + Ok(command) } } @@ -104,9 +105,9 @@ fn validate_command_success(auth_mechanism: &str, response: &Document) -> Result match bson_util::get_int(ok) { Some(1) => Ok(()), Some(_) => { - let source = crate::bson::from_bson::>( - Bson::Document(response.clone()), - ) + let source = crate::bson_compat::deserialize_from_bson::< + CommandResponse, + >(Bson::Document(response.clone())) .map(|cmd_resp| cmd_resp.body.into()) .ok(); Err(Error::authentication_error( diff --git a/src/client/auth/scram.rs b/src/client/auth/scram.rs index 82a6a46ca..dfb70eca7 100644 --- a/src/client/auth/scram.rs +++ b/src/client/auth/scram.rs @@ -19,6 +19,7 @@ use tokio::sync::RwLock; use crate::{ bson::{Bson, Document}, + bson_compat::RawDocumentBufExt as _, client::{ auth::{ self, @@ -149,7 +150,7 @@ impl ScramVersion { ) -> Result { let client_first = self.build_client_first(credential, false, server_api)?; - let command = client_first.to_command(self); + let command = client_first.to_command(self)?; let server_first = conn.send_message(command).await?; @@ -447,7 +448,7 @@ impl ClientFirst { &self.message[..] } - pub(super) fn to_command(&self, scram: &ScramVersion) -> Command { + pub(super) fn to_command(&self, scram: &ScramVersion) -> Result { let payload = self.message().as_bytes().to_vec(); let auth_mech = AuthMechanism::from_scram_version(scram); let sasl_start = SaslStart::new( @@ -457,13 +458,13 @@ impl ClientFirst { self.server_api.clone(), ); - let mut cmd = sasl_start.into_command(); + let mut cmd = sasl_start.into_command()?; if self.include_db { - cmd.body.append("db", self.source.clone()); + cmd.body.append_err("db", self.source.clone())?; } - cmd + Ok(cmd) } } diff --git a/src/client/auth/test.rs b/src/client/auth/test.rs index 7f186bcda..d707fa0f3 100644 --- a/src/client/auth/test.rs +++ b/src/client/auth/test.rs @@ -70,7 +70,7 @@ fn negotiate_mangled() { fn scram_sasl_first_options(mechanism: AuthMechanism) { let sasl_first = SaslStart::new(String::new(), mechanism, Vec::new(), None); - let command = sasl_first.into_command(); + let command = sasl_first.into_command().unwrap(); let options = match command.body.get_document("options") { Ok(options) => options, Err(_) => panic!("SaslStart should contain options document"), @@ -93,7 +93,7 @@ fn sasl_first_options_specified() { #[test] fn sasl_first_options_not_specified() { let sasl_first = SaslStart::new(String::new(), AuthMechanism::MongoDbX509, Vec::new(), None); - let command = sasl_first.into_command(); + let command = sasl_first.into_command().unwrap(); assert!( command.body.get_document("options").is_err(), "SaslStart should not contain options document for X.509 authentication" diff --git a/src/client/auth/x509.rs b/src/client/auth/x509.rs index 8932a8f71..9c8297b0a 100644 --- a/src/client/auth/x509.rs +++ b/src/client/auth/x509.rs @@ -2,6 +2,7 @@ use crate::bson::rawdoc; use crate::{ bson::Document, + bson_compat::RawDocumentBufExt as _, client::options::ServerApi, cmap::{Command, Connection, RawCommandResponse}, error::{Error, Result}, @@ -9,7 +10,7 @@ use crate::{ }; /// Constructs the first client message in the X.509 handshake for speculative authentication -pub(crate) fn build_speculative_client_first(credential: &Credential) -> Command { +pub(crate) fn build_speculative_client_first(credential: &Credential) -> Result { self::build_client_first(credential, None) } @@ -17,14 +18,14 @@ pub(crate) fn build_speculative_client_first(credential: &Credential) -> Command pub(crate) fn build_client_first( credential: &Credential, server_api: Option<&ServerApi>, -) -> Command { +) -> Result { let mut auth_command_doc = rawdoc! { "authenticate": 1, "mechanism": "MONGODB-X509", }; if let Some(ref username) = credential.username { - auth_command_doc.append("username", username.as_str()); + auth_command_doc.append_err("username", username.as_str())?; } let mut command = Command::new("authenticate", "$external", auth_command_doc); @@ -32,7 +33,7 @@ pub(crate) fn build_client_first( command.set_server_api(server_api); } - command + Ok(command) } /// Sends the first client message in the X.509 handshake. @@ -41,7 +42,7 @@ pub(crate) async fn send_client_first( credential: &Credential, server_api: Option<&ServerApi>, ) -> Result { - let command = build_client_first(credential, server_api); + let command = build_client_first(credential, server_api)?; conn.send_message(command).await } diff --git a/src/client/csfle.rs b/src/client/csfle.rs index 2cff5632c..fd4c772d3 100644 --- a/src/client/csfle.rs +++ b/src/client/csfle.rs @@ -102,10 +102,11 @@ impl ClientState { .retry_kms(true)? .use_range_v2()?; if let Some(m) = &opts.schema_map { - builder = builder.schema_map(&crate::bson::to_document(m)?)?; + builder = builder.schema_map(&crate::bson_compat::serialize_to_document(m)?)?; } if let Some(m) = &opts.encrypted_fields_map { - builder = builder.encrypted_field_config_map(&crate::bson::to_document(m)?)?; + builder = builder + .encrypted_field_config_map(&crate::bson_compat::serialize_to_document(m)?)?; } #[cfg(not(test))] let disable_crypt_shared = false; diff --git a/src/client/csfle/client_encryption/create_data_key.rs b/src/client/csfle/client_encryption/create_data_key.rs index 7cb4b7853..faca26041 100644 --- a/src/client/csfle/client_encryption/create_data_key.rs +++ b/src/client/csfle/client_encryption/create_data_key.rs @@ -44,7 +44,7 @@ impl ClientEncryption { let mut builder = self.crypt.ctx_builder(); let mut key_doc = doc! { "provider": kms_provider.as_string() }; if !matches!(master_key, MasterKey::Local(_)) { - let master_doc = crate::bson::to_document(&master_key)?; + let master_doc = crate::bson_compat::serialize_to_document(&master_key)?; key_doc.extend(master_doc); } if let Some(opts) = opts { diff --git a/src/client/csfle/client_encryption/encrypt.rs b/src/client/csfle/client_encryption/encrypt.rs index 98305f010..8e46950e6 100644 --- a/src/client/csfle/client_encryption/encrypt.rs +++ b/src/client/csfle/client_encryption/encrypt.rs @@ -86,7 +86,7 @@ impl ClientEncryption { builder = builder.query_type(qtype)?; } if let Some(range_options) = &opts.range_options { - let options_doc = crate::bson::to_document(range_options)?; + let options_doc = crate::bson_compat::serialize_to_document(range_options)?; builder = builder.algorithm_range(options_doc)?; } Ok(builder) diff --git a/src/client/csfle/options.rs b/src/client/csfle/options.rs index b4866c0a1..d137ed0df 100644 --- a/src/client/csfle/options.rs +++ b/src/client/csfle/options.rs @@ -129,7 +129,9 @@ impl KmsProviders { } pub(crate) fn credentials_doc(&self) -> Result { - Ok(crate::bson::to_document(&self.credentials)?) + Ok(crate::bson_compat::serialize_to_document( + &self.credentials, + )?) } pub(crate) fn tls_options(&self) -> Option<&KmsProvidersTlsOptions> { diff --git a/src/client/csfle/state_machine.rs b/src/client/csfle/state_machine.rs index 4237002a2..a2fbe27c9 100644 --- a/src/client/csfle/state_machine.rs +++ b/src/client/csfle/state_machine.rs @@ -5,7 +5,10 @@ use std::{ time::Duration, }; -use crate::bson::{rawdoc, Document, RawDocument, RawDocumentBuf}; +use crate::{ + bson::{rawdoc, Document, RawDocument, RawDocumentBuf}, + bson_compat::RawDocumentBufExt as _, +}; use futures_util::{stream, TryStreamExt}; use mongocrypt::ctx::{Ctx, KmsCtx, KmsProviderType, State}; use rayon::ThreadPool; @@ -261,9 +264,9 @@ impl CryptExecutor { "secretAccessKey": aws_creds.secret_key(), }; if let Some(token) = aws_creds.session_token() { - creds.append("sessionToken", token); + creds.append_err("sessionToken", token)?; } - kms_providers.append(provider.as_string(), creds); + kms_providers.append_err(provider.as_string(), creds)?; } #[cfg(not(feature = "aws-auth"))] { @@ -276,10 +279,10 @@ impl CryptExecutor { KmsProviderType::Azure => { #[cfg(feature = "azure-kms")] { - kms_providers.append( + kms_providers.append_err( provider.as_string(), self.azure.get_token().await?, - ); + )?; } #[cfg(not(feature = "azure-kms"))] { @@ -327,10 +330,10 @@ impl CryptExecutor { .send() .await .map_err(|e| kms_error(e.to_string()))?; - kms_providers.append( + kms_providers.append_err( "gcp", rawdoc! { "accessToken": response.access_token }, - ); + )?; } #[cfg(not(feature = "gcp-kms"))] { diff --git a/src/client/executor.rs b/src/client/executor.rs index 33f9da7c8..50a0bec51 100644 --- a/src/client/executor.rs +++ b/src/client/executor.rs @@ -1,6 +1,8 @@ #[cfg(feature = "in-use-encryption")] use crate::bson::RawDocumentBuf; use crate::bson::{doc, RawBsonRef, RawDocument, Timestamp}; +#[cfg(not(feature = "bson-3"))] +use crate::bson_compat::RawDocumentExt as _; #[cfg(feature = "in-use-encryption")] use futures_core::future::BoxFuture; use once_cell::sync::Lazy; @@ -816,7 +818,7 @@ impl Client { is_sharded: bool, response: RawCommandResponse, ) -> Result { - let raw_doc = RawDocument::from_bytes(response.as_bytes())?; + let raw_doc = RawDocument::decode_from_bytes(response.as_bytes())?; let ok = match raw_doc.get("ok")? { Some(b) => { @@ -835,7 +837,7 @@ impl Client { let cluster_time: Option = raw_doc .get("$clusterTime")? .and_then(RawBsonRef::as_document) - .map(|d| crate::bson::from_slice(d.as_bytes())) + .map(|d| crate::bson_compat::deserialize_from_slice(d.as_bytes())) .transpose()?; let at_cluster_time = op.extract_at_cluster_time(raw_doc)?; @@ -858,7 +860,7 @@ impl Client { let recovery_token = raw_doc .get("recoveryToken")? .and_then(RawBsonRef::as_document) - .map(|d| crate::bson::from_slice(d.as_bytes())) + .map(|d| crate::bson_compat::deserialize_from_slice(d.as_bytes())) .transpose()?; session.transaction.recovery_token = recovery_token; } diff --git a/src/client/options/bulk_write.rs b/src/client/options/bulk_write.rs index 916a19dbf..2f436438d 100644 --- a/src/client/options/bulk_write.rs +++ b/src/client/options/bulk_write.rs @@ -7,6 +7,7 @@ use typed_builder::TypedBuilder; use crate::{ bson::{rawdoc, Array, Bson, Document, RawDocumentBuf}, + bson_compat::RawDocumentBufExt as _, bson_util::{get_or_prepend_id_field, replacement_document_check, update_document_check}, error::Result, options::{UpdateModifications, WriteConcern}, @@ -299,7 +300,7 @@ where /// Note that the returned value must be provided to [`bulk_write`](crate::Client::bulk_write) /// for the insert to be performed. pub fn insert_one_model(&self, document: impl Borrow) -> Result { - let document = crate::bson::to_document(document.borrow())?; + let document = crate::bson_compat::serialize_to_document(document.borrow())?; Ok(InsertOneModel::builder() .namespace(self.namespace()) .document(document) @@ -316,7 +317,7 @@ where filter: Document, replacement: impl Borrow, ) -> Result { - let replacement = crate::bson::to_document(replacement.borrow())?; + let replacement = crate::bson_compat::serialize_to_document(replacement.borrow())?; Ok(ReplaceOneModel::builder() .namespace(self.namespace()) .filter(filter) @@ -389,13 +390,13 @@ impl WriteModel { (rawdoc! { "document": insert_document }, Some(inserted_id)) } _ => { - let model_document = crate::bson::to_raw_document_buf(&self)?; + let model_document = crate::bson_compat::serialize_to_raw_document_buf(&self)?; (model_document, None) } }; if let Some(multi) = self.multi() { - model_document.append("multi", multi); + model_document.append_err("multi", multi)?; } Ok((model_document, inserted_id)) diff --git a/src/client/options/test.rs b/src/client/options/test.rs index 989d3ba54..107a46caf 100644 --- a/src/client/options/test.rs +++ b/src/client/options/test.rs @@ -121,8 +121,8 @@ async fn run_tests(path: &[&str], skipped_files: &[&str]) { ); } - let mut actual_options = - crate::bson::to_document(&client_options).expect(&test_case.description); + let mut actual_options = crate::bson_compat::serialize_to_document(&client_options) + .expect(&test_case.description); if let Some(mode) = actual_options.remove("mode") { actual_options.insert("readPreference", mode); diff --git a/src/cmap/conn/command.rs b/src/cmap/conn/command.rs index 9324249ee..8904d172d 100644 --- a/src/cmap/conn/command.rs +++ b/src/cmap/conn/command.rs @@ -185,11 +185,13 @@ pub(crate) struct RawCommandResponse { impl RawCommandResponse { #[cfg(test)] pub(crate) fn with_document_and_address(source: ServerAddress, doc: Document) -> Result { - let mut raw = Vec::new(); - doc.to_writer(&mut raw)?; + #[cfg(not(feature = "bson-3"))] + use crate::bson_compat::{DocumentExt as _, RawDocumentBufExt as _}; + + let raw = doc.encode_to_vec()?; Ok(Self { source, - raw: RawDocumentBuf::from_bytes(raw)?, + raw: RawDocumentBuf::decode_from_bytes(raw)?, }) } @@ -202,7 +204,7 @@ impl RawCommandResponse { } pub(crate) fn body<'a, T: Deserialize<'a>>(&'a self) -> Result { - crate::bson::from_slice(self.raw.as_bytes()).map_err(|e| { + crate::bson_compat::deserialize_from_slice(self.raw.as_bytes()).map_err(|e| { Error::from(ErrorKind::InvalidResponse { message: format!("{}", e), }) diff --git a/src/cmap/conn/wire/message.rs b/src/cmap/conn/wire/message.rs index a4b0fd93f..6c50deb35 100644 --- a/src/cmap/conn/wire/message.rs +++ b/src/cmap/conn/wire/message.rs @@ -62,7 +62,7 @@ impl TryFrom for Message { type Error = Error; fn try_from(command: Command) -> Result { - let document_payload = crate::bson::to_raw_document_buf(&command)?; + let document_payload = crate::bson_compat::serialize_to_raw_document_buf(&command)?; #[cfg(any( feature = "zstd-compression", feature = "zlib-compression", @@ -424,11 +424,14 @@ enum MessageSection { impl MessageSection { /// Reads bytes from `reader` and deserializes them into a MessageSection. fn read(reader: &mut R) -> Result { + #[cfg(not(feature = "bson-3"))] + use crate::bson_compat::RawDocumentBufExt as _; + let payload_type = reader.read_u8_sync()?; if payload_type == 0 { let bytes = bson_util::read_document_bytes(reader)?; - let document = RawDocumentBuf::from_bytes(bytes)?; + let document = RawDocumentBuf::decode_from_bytes(bytes)?; return Ok(MessageSection::Document(document)); } @@ -443,7 +446,7 @@ impl MessageSection { while length_remaining.get()? > count_reader.bytes_read() { let bytes = bson_util::read_document_bytes(&mut count_reader)?; - let document = RawDocumentBuf::from_bytes(bytes)?; + let document = RawDocumentBuf::decode_from_bytes(bytes)?; documents.push(document); } diff --git a/src/cmap/establish.rs b/src/cmap/establish.rs index c2600491a..58873a052 100644 --- a/src/cmap/establish.rs +++ b/src/cmap/establish.rs @@ -74,7 +74,7 @@ impl EstablisherOptions { impl ConnectionEstablisher { /// Creates a new ConnectionEstablisher from the given options. pub(crate) fn new(options: EstablisherOptions) -> Result { - let handshaker = Handshaker::new(options.handshake_options); + let handshaker = Handshaker::new(options.handshake_options)?; let tls_config = if let Some(tls_options) = options.tls_options { Some(TlsConfig::new(tls_options)?) diff --git a/src/cmap/establish/handshake.rs b/src/cmap/establish/handshake.rs index b78821dbd..b3aaaff75 100644 --- a/src/cmap/establish/handshake.rs +++ b/src/cmap/establish/handshake.rs @@ -3,7 +3,10 @@ mod test; use std::env; -use crate::bson::{rawdoc, RawBson, RawDocumentBuf}; +use crate::{ + bson::{rawdoc, RawBson, RawDocumentBuf}, + bson_compat::RawDocumentBufExt as _, +}; use once_cell::sync::Lazy; use tokio::sync::broadcast; @@ -74,66 +77,63 @@ pub(crate) enum FaasEnvironmentName { Vercel, } -impl From<&ClientMetadata> for RawDocumentBuf { - fn from(metadata: &ClientMetadata) -> Self { +impl TryFrom<&ClientMetadata> for RawDocumentBuf { + type Error = crate::error::Error; + fn try_from(metadata: &ClientMetadata) -> Result { let mut metadata_doc = RawDocumentBuf::new(); if let Some(application) = &metadata.application { - metadata_doc.append("application", rawdoc! { "name": application.name.as_str() }); + metadata_doc + .append_err("application", rawdoc! { "name": application.name.as_str() })?; } - metadata_doc.append( + metadata_doc.append_err( "driver", rawdoc! { "name": metadata.driver.name.as_str(), "version": metadata.driver.version.as_str(), }, - ); + )?; - metadata_doc.append("os", &metadata.os); - metadata_doc.append("platform", metadata.platform.as_str()); + let raw_os: RawBson = (&metadata.os).try_into()?; + metadata_doc.append_err("os", raw_os)?; + metadata_doc.append_err("platform", metadata.platform.as_str())?; if let Some(env) = &metadata.env { - metadata_doc.append("env", env); + let raw_env: RawBson = env.try_into()?; + metadata_doc.append_err("env", raw_env)?; } - metadata_doc + Ok(metadata_doc) } } -impl From<&OsMetadata> for RawBson { - fn from(metadata: &OsMetadata) -> Self { +impl TryFrom<&OsMetadata> for RawBson { + type Error = crate::error::Error; + + fn try_from(metadata: &OsMetadata) -> Result { let mut doc = rawdoc! { "type": metadata.os_type.as_str() }; if let Some(name) = &metadata.name { - doc.append("name", name.as_str()); + doc.append_err("name", name.as_str())?; } if let Some(arch) = &metadata.architecture { - doc.append("architecture", arch.as_str()); + doc.append_err("architecture", arch.as_str())?; } if let Some(version) = &metadata.version { - doc.append("version", version.as_str()); + doc.append_err("version", version.as_str())?; } - RawBson::Document(doc) + Ok(RawBson::Document(doc)) } } -#[cfg(feature = "bson-3")] -impl crate::bson::raw::BindRawBsonRef for &OsMetadata { - fn bind(self, f: F) -> R - where - F: for<'a> FnOnce(bson3::RawBsonRef<'a>) -> R, - { - let raw: RawBson = self.into(); - raw.bind(f) - } -} +impl TryFrom<&RuntimeEnvironment> for RawBson { + type Error = crate::error::Error; -impl From<&RuntimeEnvironment> for RawBson { - fn from(env: &RuntimeEnvironment) -> Self { + fn try_from(env: &RuntimeEnvironment) -> Result { let RuntimeEnvironment { name, runtime, @@ -145,38 +145,27 @@ impl From<&RuntimeEnvironment> for RawBson { } = env; let mut out = rawdoc! {}; if let Some(name) = name { - out.append("name", name.name()); + out.append_err("name", name.name())?; } if let Some(rt) = runtime { - out.append("runtime", rt.as_str()); + out.append_err("runtime", rt.as_str())?; } if let Some(t) = timeout_sec { - out.append("timeout_sec", *t); + out.append_err("timeout_sec", *t)?; } if let Some(m) = memory_mb { - out.append("memory_mb", *m); + out.append_err("memory_mb", *m)?; } if let Some(r) = region { - out.append("region", r.as_str()); + out.append_err("region", r.as_str())?; } if let Some(u) = url { - out.append("url", u.as_str()); + out.append_err("url", u.as_str())?; } if let Some(c) = container { - out.append("container", c.clone()); + out.append_err("container", c.clone())?; } - RawBson::Document(out) - } -} - -#[cfg(feature = "bson-3")] -impl crate::bson::raw::BindRawBsonRef for &RuntimeEnvironment { - fn bind(self, f: F) -> R - where - F: for<'a> FnOnce(bson3::RawBsonRef<'a>) -> R, - { - let raw: RawBson = self.into(); - raw.bind(f) + Ok(RawBson::Document(out)) } } @@ -222,10 +211,12 @@ impl RuntimeEnvironment { } let mut container = rawdoc! {}; if std::path::Path::new("/.dockerenv").exists() { - container.append("runtime", "docker"); + // Unwrap safety: key and value are static known-valid strings. + container.append_err("runtime", "docker").unwrap(); } if var_set("KUBERNETES_SERVICE_HOST") { - container.append("orchestrator", "kubernetes"); + // Unwrap safety: key and value are static known-valid strings. + container.append_err("orchestrator", "kubernetes").unwrap(); } if !container.is_empty() { out.container = Some(container); @@ -364,7 +355,7 @@ pub(crate) static TEST_METADATA: std::sync::OnceLock = std::sync impl Handshaker { /// Creates a new Handshaker. - pub(crate) fn new(options: HandshakerOptions) -> Self { + pub(crate) fn new(options: HandshakerOptions) -> Result { let mut metadata = BASE_CLIENT_METADATA.clone(); let mut command = hello_command( @@ -396,7 +387,7 @@ impl Handshaker { metadata.env = RuntimeEnvironment::new(); if options.load_balanced { - command.body.append("loadBalanced", true); + command.body.append_err("loadBalanced", true)?; } #[cfg(any( @@ -405,16 +396,17 @@ impl Handshaker { feature = "snappy-compression" ))] if let Some(ref compressors) = options.compressors { - command.body.append( + use crate::bson::RawArrayBuf; + + use crate::bson_compat::RawArrayBufExt as _; + + command.body.append_err( "compression", - compressors - .iter() - .map(|compressor| compressor.name()) - .collect::(), - ); + RawArrayBuf::from_iter_err(compressors.iter().map(|compressor| compressor.name()))?, + )?; } - Self { + Ok(Self { command, #[cfg(any( feature = "zstd-compression", @@ -426,7 +418,7 @@ impl Handshaker { metadata, #[cfg(feature = "aws-auth")] http_client: crate::runtime::HttpClient::default(), - } + }) } async fn build_command( @@ -436,7 +428,7 @@ impl Handshaker { let mut command = self.command.clone(); if let Some(cred) = credential { - cred.append_needed_mechanism_negotiation(&mut command.body); + cred.append_needed_mechanism_negotiation(&mut command.body)?; command.target_db = cred.resolved_source().to_string(); } @@ -445,19 +437,19 @@ impl Handshaker { let body = &mut command.body; let body_size = body.as_bytes().len(); let mut metadata = self.metadata.clone(); - let mut meta_doc: RawDocumentBuf = (&metadata).into(); + let mut meta_doc: RawDocumentBuf = (&metadata).try_into()?; const OVERHEAD: usize = 1 /* tag */ + 6 /* name */ + 1 /* null */; for trunc_fn in METADATA_TRUNCATIONS { if body_size + OVERHEAD + meta_doc.as_bytes().len() <= MAX_HELLO_SIZE { break; } trunc_fn(&mut metadata); - meta_doc = (&metadata).into(); + meta_doc = (&metadata).try_into()?; } #[cfg(test)] #[allow(clippy::incompatible_msrv)] let _ = TEST_METADATA.set(metadata); - body.append("client", meta_doc); + body.append_err("client", meta_doc)?; Ok((command, client_first)) } @@ -575,7 +567,7 @@ async fn set_speculative_auth_info( None => return Ok(None), }; - command.append("speculativeAuthenticate", client_first.to_document()); + command.append_err("speculativeAuthenticate", client_first.to_document()?)?; Ok(Some(client_first)) } diff --git a/src/cmap/establish/handshake/test.rs b/src/cmap/establish/handshake/test.rs index 2b0519e91..ff861c2eb 100644 --- a/src/cmap/establish/handshake/test.rs +++ b/src/cmap/establish/handshake/test.rs @@ -18,7 +18,8 @@ async fn metadata_no_options() { driver_info: None, server_api: None, load_balanced: false, - }); + }) + .unwrap(); let command = handshaker.build_command(None).await.unwrap().0; let metadata = command.body.get_document("client").unwrap(); @@ -67,7 +68,7 @@ async fn metadata_with_options() { load_balanced: false, }; - let handshaker = Handshaker::new(options); + let handshaker = Handshaker::new(options).unwrap(); let command = handshaker.build_command(None).await.unwrap().0; let metadata = command.body.get_document("client").unwrap(); assert_eq!( diff --git a/src/cmap/test/integration.rs b/src/cmap/test/integration.rs index 2c3c0c2c4..c4faeab65 100644 --- a/src/cmap/test/integration.rs +++ b/src/cmap/test/integration.rs @@ -72,7 +72,8 @@ async fn acquire_connection_and_send_command() { assert!(doc_response.is_success()); - let response: ListDatabasesResponse = crate::bson::from_document(doc_response.body).unwrap(); + let response: ListDatabasesResponse = + crate::bson_compat::deserialize_from_document(doc_response.body).unwrap(); let names: Vec<_> = response .databases diff --git a/src/concern/test.rs b/src/concern/test.rs index f342b1416..d897c95fe 100644 --- a/src/concern/test.rs +++ b/src/concern/test.rs @@ -45,7 +45,7 @@ fn write_concern_is_acknowledged() { #[test] fn write_concern_deserialize() { let w_1 = doc! { "w": 1 }; - let wc: WriteConcern = crate::bson::from_bson(Bson::Document(w_1)).unwrap(); + let wc: WriteConcern = crate::bson_compat::deserialize_from_bson(Bson::Document(w_1)).unwrap(); assert_eq!( wc, WriteConcern { @@ -56,7 +56,8 @@ fn write_concern_deserialize() { ); let w_majority = doc! { "w": "majority" }; - let wc: WriteConcern = crate::bson::from_bson(Bson::Document(w_majority)).unwrap(); + let wc: WriteConcern = + crate::bson_compat::deserialize_from_bson(Bson::Document(w_majority)).unwrap(); assert_eq!( wc, WriteConcern { @@ -67,7 +68,8 @@ fn write_concern_deserialize() { ); let w_timeout = doc! { "w": "majority", "wtimeout": 100 }; - let wc: WriteConcern = crate::bson::from_bson(Bson::Document(w_timeout)).unwrap(); + let wc: WriteConcern = + crate::bson_compat::deserialize_from_bson(Bson::Document(w_timeout)).unwrap(); assert_eq!( wc, WriteConcern { @@ -78,7 +80,8 @@ fn write_concern_deserialize() { ); let journal = doc! { "w": "majority", "j": true }; - let wc: WriteConcern = crate::bson::from_bson(Bson::Document(journal)).unwrap(); + let wc: WriteConcern = + crate::bson_compat::deserialize_from_bson(Bson::Document(journal)).unwrap(); assert_eq!( wc, WriteConcern { diff --git a/src/cursor.rs b/src/cursor.rs index d8dd1c004..7080235a7 100644 --- a/src/cursor.rs +++ b/src/cursor.rs @@ -272,7 +272,7 @@ impl Cursor { where T: Deserialize<'a>, { - crate::bson::from_slice(self.current().as_bytes()).map_err(Error::from) + crate::bson_compat::deserialize_from_slice(self.current().as_bytes()).map_err(Error::from) } /// Update the type streamed values will be parsed as. diff --git a/src/cursor/common.rs b/src/cursor/common.rs index 342c4a6aa..092bd2c83 100644 --- a/src/cursor/common.rs +++ b/src/cursor/common.rs @@ -277,7 +277,9 @@ where Poll::Pending => return Poll::Pending, Poll::Ready(bv) => match bv? { BatchValue::Some { doc, .. } => { - return Poll::Ready(Some(Ok(crate::bson::from_slice(doc.as_bytes())?))) + return Poll::Ready(Some(Ok(crate::bson_compat::deserialize_from_slice( + doc.as_bytes(), + )?))) } BatchValue::Empty => continue, BatchValue::Exhausted => return Poll::Ready(None), diff --git a/src/cursor/session.rs b/src/cursor/session.rs index 78f69275b..33f17ca76 100644 --- a/src/cursor/session.rs +++ b/src/cursor/session.rs @@ -304,7 +304,7 @@ impl SessionCursor { where T: Deserialize<'a>, { - crate::bson::from_slice(self.current().as_bytes()).map_err(Error::from) + crate::bson_compat::deserialize_from_slice(self.current().as_bytes()).map_err(Error::from) } /// Update the type streamed values will be parsed as. diff --git a/src/hello.rs b/src/hello.rs index 63de1d9c8..f521ee3e2 100644 --- a/src/hello.rs +++ b/src/hello.rs @@ -1,6 +1,9 @@ use std::time::Duration; -use crate::bson::{rawdoc, RawDocumentBuf}; +use crate::{ + bson::{rawdoc, RawDocumentBuf}, + bson_compat::RawDocumentBufExt, +}; use serde::{Deserialize, Serialize}; use tokio::sync::broadcast; @@ -48,20 +51,24 @@ pub(crate) fn hello_command( } else { let mut body = rawdoc! { LEGACY_HELLO_COMMAND_NAME: 1 }; if hello_ok.is_none() { - body.append("helloOk", true); + // Unwrap safety: key and value are static known-good values. + body.append_err("helloOk", true).unwrap(); } (body, LEGACY_HELLO_COMMAND_NAME) }; if let Some(opts) = awaitable_options { - body.append("topologyVersion", opts.topology_version); - body.append( + // Unwrap safety: keys are static and values are types without cstrings. + body.append_err("topologyVersion", opts.topology_version) + .unwrap(); + body.append_err( "maxAwaitTimeMS", opts.max_await_time .as_millis() .try_into() .unwrap_or(i64::MAX), - ); + ) + .unwrap(); } let mut command = Command::new(command_name, "admin", body); diff --git a/src/operation.rs b/src/operation.rs index 393f1c37c..cf23f86f0 100644 --- a/src/operation.rs +++ b/src/operation.rs @@ -389,7 +389,7 @@ pub(crate) fn append_options( options: Option<&T>, ) -> Result<()> { if let Some(options) = options { - let options_doc = bson::to_document(options)?; + let options_doc = crate::bson_compat::serialize_to_document(options)?; doc.extend(options_doc); } Ok(()) @@ -400,7 +400,7 @@ pub(crate) fn append_options_to_raw_document( options: Option<&T>, ) -> Result<()> { if let Some(options) = options { - let options_raw_doc = bson::to_raw_document_buf(options)?; + let options_raw_doc = crate::bson_compat::serialize_to_raw_document_buf(options)?; extend_raw_document_buf(doc, options_raw_doc)?; } Ok(()) diff --git a/src/operation/bulk_write.rs b/src/operation/bulk_write.rs index 62761fcd4..7d3f40d44 100644 --- a/src/operation/bulk_write.rs +++ b/src/operation/bulk_write.rs @@ -7,6 +7,7 @@ use futures_util::{FutureExt, TryStreamExt}; use crate::{ bson::{rawdoc, Bson, RawDocumentBuf}, + bson_compat::RawDocumentBufExt as _, bson_util::{self, extend_raw_document_buf}, checked::Checked, cmap::{Command, RawCommandResponse, StreamDescription}, @@ -93,7 +94,7 @@ where loop { for response_document in &responses { let response: SingleOperationResponse = - crate::bson::from_slice(response_document.as_bytes())?; + crate::bson_compat::deserialize_from_slice(response_document.as_bytes())?; self.handle_individual_response(response, result, error)?; } @@ -278,10 +279,10 @@ where let mut command_body = rawdoc! { Self::NAME: 1 }; let mut options = match self.options { - Some(options) => crate::bson::to_raw_document_buf(options), - None => crate::bson::to_raw_document_buf(&BulkWriteOptions::default()), + Some(options) => crate::bson_compat::serialize_to_raw_document_buf(options), + None => crate::bson_compat::serialize_to_raw_document_buf(&BulkWriteOptions::default()), }?; - options.append("errorsOnly", R::errors_only()); + options.append_err("errorsOnly", R::errors_only())?; bson_util::extend_raw_document_buf(&mut command_body, options)?; let max_document_sequences_size: usize = (Checked::new(max_message_size) diff --git a/src/operation/delete.rs b/src/operation/delete.rs index b6641b63c..b999fee8f 100644 --- a/src/operation/delete.rs +++ b/src/operation/delete.rs @@ -51,11 +51,14 @@ impl OperationWithDefaults for Delete { }; if let Some(ref collation) = self.collation { - delete.insert("collation", crate::bson::to_bson(&collation)?); + delete.insert( + "collation", + crate::bson_compat::serialize_to_bson(&collation)?, + ); } if let Some(ref hint) = self.hint { - delete.insert("hint", crate::bson::to_bson(&hint)?); + delete.insert("hint", crate::bson_compat::serialize_to_bson(&hint)?); } let mut body = doc! { diff --git a/src/operation/find.rs b/src/operation/find.rs index ae049a032..e3da43dfb 100644 --- a/src/operation/find.rs +++ b/src/operation/find.rs @@ -2,6 +2,7 @@ use crate::bson::RawDocumentBuf; use crate::{ bson::{rawdoc, Document}, + bson_compat::RawDocumentBufExt as _, cmap::{Command, RawCommandResponse, StreamDescription}, cursor::CursorSpecification, error::{Error, Result}, @@ -41,7 +42,7 @@ impl OperationWithDefaults for Find { if let Some(ref mut options) = self.options { // negative limits should be interpreted as request for single batch as per crud spec. if options.limit.map(|limit| limit < 0) == Some(true) { - body.append("singleBatch", true); + body.append_err("singleBatch", true)?; } if let Some(ref mut batch_size) = options.batch_size { @@ -59,11 +60,11 @@ impl OperationWithDefaults for Find { match options.cursor_type { Some(CursorType::Tailable) => { - body.append("tailable", true); + body.append_err("tailable", true)?; } Some(CursorType::TailableAwait) => { - body.append("tailable", true); - body.append("awaitData", true); + body.append_err("tailable", true)?; + body.append_err("awaitData", true)?; } _ => {} }; @@ -72,7 +73,7 @@ impl OperationWithDefaults for Find { append_options_to_raw_document(&mut body, self.options.as_ref())?; let raw_filter: RawDocumentBuf = (&self.filter).try_into()?; - body.append("filter", raw_filter); + body.append_err("filter", raw_filter)?; Ok(Command::new_read( Self::NAME.to_string(), diff --git a/src/operation/find_and_modify.rs b/src/operation/find_and_modify.rs index 7f1bf91d0..7c67e26cf 100644 --- a/src/operation/find_and_modify.rs +++ b/src/operation/find_and_modify.rs @@ -6,7 +6,8 @@ use serde::{de::DeserializeOwned, Deserialize}; use self::options::FindAndModifyOptions; use crate::{ - bson::{doc, from_slice, rawdoc, Document, RawBson, RawDocumentBuf}, + bson::{doc, rawdoc, Document, RawBson, RawDocumentBuf}, + bson_compat::{deserialize_from_slice, RawDocumentBufExt as _}, bson_util, cmap::{Command, RawCommandResponse, StreamDescription}, coll::{options::UpdateModifications, Namespace}, @@ -75,7 +76,7 @@ impl OperationWithDefaults for FindAndModify { }; match &self.modification { - Modification::Delete => body.append("remove", true), + Modification::Delete => body.append_err("remove", true)?, Modification::Update(update_or_replace) => { update_or_replace.append_to_rawdoc(&mut body, "update")? } @@ -102,7 +103,7 @@ impl OperationWithDefaults for FindAndModify { let response: Response = response.body()?; match response.value { - RawBson::Document(doc) => Ok(Some(from_slice(doc.as_bytes())?)), + RawBson::Document(doc) => Ok(Some(deserialize_from_slice(doc.as_bytes())?)), RawBson::Null => Ok(None), other => Err(ErrorKind::InvalidResponse { message: format!( diff --git a/src/operation/get_more.rs b/src/operation/get_more.rs index b0deac27b..88cf72a6a 100644 --- a/src/operation/get_more.rs +++ b/src/operation/get_more.rs @@ -1,6 +1,9 @@ use std::{collections::VecDeque, time::Duration}; -use crate::bson::{rawdoc, RawBson}; +use crate::{ + bson::{rawdoc, RawBson}, + bson_compat::RawDocumentBufExt as _, +}; use serde::Deserialize; use crate::{ @@ -60,20 +63,20 @@ impl OperationWithDefaults for GetMore<'_> { if let Some(batch_size) = self.batch_size { let batch_size = Checked::from(batch_size).try_into::()?; if batch_size != 0 { - body.append("batchSize", batch_size); + body.append_err("batchSize", batch_size)?; } } if let Some(ref max_time) = self.max_time { - body.append( + body.append_err( "maxTimeMS", max_time.as_millis().try_into().unwrap_or(i32::MAX), - ); + )?; } if let Some(comment) = &self.comment { let raw_comment: RawBson = comment.clone().try_into()?; - body.append("comment", raw_comment); + body.append_err("comment", raw_comment)?; } Ok(Command::new( diff --git a/src/operation/insert.rs b/src/operation/insert.rs index 8e33189e4..6f0e48969 100644 --- a/src/operation/insert.rs +++ b/src/operation/insert.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use crate::{ bson::{rawdoc, Bson, RawDocument}, + bson_compat::RawDocumentBufExt as _, bson_util::{ array_entry_size_bytes, extend_raw_document_buf, @@ -64,7 +65,7 @@ impl OperationWithDefaults for Insert<'_> { let max_operations: usize = Checked::new(description.max_write_batch_size).try_into()?; let mut command_body = rawdoc! { Self::NAME: self.ns.coll.clone() }; - let options = crate::bson::to_raw_document_buf(&self.options)?; + let options = crate::bson_compat::serialize_to_raw_document_buf(&self.options)?; extend_raw_document_buf(&mut command_body, options)?; let max_document_sequence_size: usize = (Checked::new(max_message_size) @@ -75,7 +76,7 @@ impl OperationWithDefaults for Insert<'_> { let mut docs = Vec::new(); let mut current_size = Checked::new(0); for (i, document) in self.documents.iter().take(max_operations).enumerate() { - let mut document = crate::bson::to_raw_document_buf(document)?; + let mut document = crate::bson_compat::serialize_to_raw_document_buf(document)?; let id = get_or_prepend_id_field(&mut document)?; let doc_size = document.as_bytes().len(); @@ -114,12 +115,12 @@ impl OperationWithDefaults for Insert<'_> { Self::NAME: self.ns.coll.clone(), }; - let options_doc = crate::bson::to_raw_document_buf(&self.options)?; + let options_doc = crate::bson_compat::serialize_to_raw_document_buf(&self.options)?; extend_raw_document_buf(&mut body, options_doc)?; if self.encrypted { // Auto-encryption does not support document sequences - body.append("documents", vec_to_raw_array_buf(docs)); + body.append_err("documents", vec_to_raw_array_buf(docs)?)?; Ok(Command::new(Self::NAME, &self.ns.db, body)) } else { let mut command = Command::new(Self::NAME, &self.ns.db, body); diff --git a/src/operation/list_collections.rs b/src/operation/list_collections.rs index d2c0bfa81..fba2e3848 100644 --- a/src/operation/list_collections.rs +++ b/src/operation/list_collections.rs @@ -1,6 +1,7 @@ use crate::bson::rawdoc; use crate::{ + bson_compat::RawDocumentBufExt as _, cmap::{Command, RawCommandResponse, StreamDescription}, cursor::CursorSpecification, error::Result, @@ -47,7 +48,7 @@ impl OperationWithDefaults for ListCollections { name_only = false; } } - body.append("nameOnly", name_only); + body.append_err("nameOnly", name_only)?; append_options_to_raw_document(&mut body, self.options.as_ref())?; diff --git a/src/operation/list_indexes.rs b/src/operation/list_indexes.rs index 452024a12..7de76ea21 100644 --- a/src/operation/list_indexes.rs +++ b/src/operation/list_indexes.rs @@ -1,6 +1,7 @@ use crate::bson::rawdoc; use crate::{ + bson_compat::RawDocumentBufExt as _, checked::Checked, cmap::{Command, RawCommandResponse, StreamDescription}, cursor::CursorSpecification, @@ -35,7 +36,7 @@ impl OperationWithDefaults for ListIndexes { }; if let Some(size) = self.options.as_ref().and_then(|o| o.batch_size) { let size = Checked::from(size).try_into::()?; - body.append("cursor", rawdoc! { "batchSize": size }); + body.append_err("cursor", rawdoc! { "batchSize": size })?; } append_options_to_raw_document(&mut body, self.options.as_ref())?; diff --git a/src/operation/update.rs b/src/operation/update.rs index b6a0a3273..13cc358f9 100644 --- a/src/operation/update.rs +++ b/src/operation/update.rs @@ -2,6 +2,7 @@ use serde::Deserialize; use crate::{ bson::{doc, rawdoc, Document, RawArrayBuf, RawBson, RawDocumentBuf}, + bson_compat::{RawArrayBufExt as _, RawDocumentBufExt as _}, bson_util, cmap::{Command, RawCommandResponse, StreamDescription}, error::{convert_insert_many_error, Result}, @@ -13,9 +14,6 @@ use crate::{ use super::ExecutionContext; -#[cfg(feature = "bson-3")] -use crate::bson_compat::RawDocumentBufExt as _; - #[derive(Clone, Debug)] pub(crate) enum UpdateOrReplace { UpdateModifications(UpdateModifications), @@ -28,16 +26,16 @@ impl UpdateOrReplace { Self::UpdateModifications(update_modifications) => match update_modifications { UpdateModifications::Document(document) => { let raw = RawDocumentBuf::from_document(document)?; - doc.append(key, raw); + doc.append_err(key, raw)?; } UpdateModifications::Pipeline(pipeline) => { let raw = bson_util::to_raw_bson_array(pipeline)?; - doc.append(key, raw); + doc.append_err(key, raw)?; } }, Self::Replacement(replacement_doc) => { bson_util::replacement_raw_document_check(replacement_doc)?; - doc.append_ref(key, replacement_doc); + doc.append_ref_err(key, replacement_doc)?; } } @@ -111,55 +109,61 @@ impl OperationWithDefaults for Update { if let Some(ref options) = self.options { if let Some(upsert) = options.upsert { - update.append("upsert", upsert); + update.append_err("upsert", upsert)?; } if let Some(ref array_filters) = options.array_filters { - update.append("arrayFilters", bson_util::to_raw_bson_array(array_filters)?); + update.append_err("arrayFilters", bson_util::to_raw_bson_array(array_filters)?)?; } if let Some(ref hint) = options.hint { - update.append("hint", hint.to_raw_bson()?); + update.append_err("hint", hint.to_raw_bson()?)?; } if let Some(ref collation) = options.collation { - update.append("collation", crate::bson::to_raw_document_buf(&collation)?); + update.append_err( + "collation", + crate::bson_compat::serialize_to_raw_document_buf(&collation)?, + )?; } if let Some(bypass_doc_validation) = options.bypass_document_validation { - body.append("bypassDocumentValidation", bypass_doc_validation); + body.append_err("bypassDocumentValidation", bypass_doc_validation)?; } if let Some(ref write_concern) = options.write_concern { if !write_concern.is_empty() { - body.append( + body.append_err( "writeConcern", - crate::bson::to_raw_document_buf(write_concern)?, - ); + crate::bson_compat::serialize_to_raw_document_buf(write_concern)?, + )?; } } if let Some(ref let_vars) = options.let_vars { - body.append("let", crate::bson::to_raw_document_buf(&let_vars)?); + body.append_err( + "let", + crate::bson_compat::serialize_to_raw_document_buf(&let_vars)?, + )?; } if let Some(ref comment) = options.comment { - body.append("comment", RawBson::try_from(comment.clone())?); + body.append_err("comment", RawBson::try_from(comment.clone())?)?; } if let Some(ref sort) = options.sort { - update.append("sort", RawDocumentBuf::from_document(sort)?); + update.append_err("sort", RawDocumentBuf::from_document(sort)?)?; } }; if let Some(multi) = self.multi { - update.append("multi", multi); + update.append_err("multi", multi)?; } let mut updates = RawArrayBuf::new(); - updates.push(update); - body.append("updates", updates); - body.append("ordered", true); // command monitoring tests expect this (SPEC-1130) + updates.push_err(update)?; + body.append_err("updates", updates)?; + body.append_err("ordered", true)?; // command monitoring tests expect this (SPEC-1130) Ok(Command::new( Self::NAME.to_string(), diff --git a/src/sdam/description/topology/test/sdam.rs b/src/sdam/description/topology/test/sdam.rs index 8c0986d1b..5154e24e2 100644 --- a/src/sdam/description/topology/test/sdam.rs +++ b/src/sdam/description/topology/test/sdam.rs @@ -754,16 +754,17 @@ async fn pool_cleared_error_does_not_mark_unknown() { // get the one server in the topology let server = topology.servers().into_values().next().unwrap(); - let heartbeat_response: HelloCommandResponse = crate::bson::from_document(doc! { - "ok": 1, - "isWritablePrimary": true, - "minWireVersion": 0, - "maxWireVersion": 6, - "maxBsonObjectSize": 16_000, - "maxWriteBatchSize": 10_000, - "maxMessageSizeBytes": 48_000_000, - }) - .unwrap(); + let heartbeat_response: HelloCommandResponse = + crate::bson_compat::deserialize_from_document(doc! { + "ok": 1, + "isWritablePrimary": true, + "minWireVersion": 0, + "maxWireVersion": 6, + "maxBsonObjectSize": 16_000, + "maxWriteBatchSize": 10_000, + "maxMessageSizeBytes": 48_000_000, + }) + .unwrap(); // discover the node topology diff --git a/src/selection_criteria.rs b/src/selection_criteria.rs index 805f54d78..edbdb5350 100644 --- a/src/selection_criteria.rs +++ b/src/selection_criteria.rs @@ -370,7 +370,7 @@ mod test { ); let read_pref = ReadPreference::Secondary { options }; - let doc = crate::bson::to_document(&read_pref).unwrap(); + let doc = crate::bson_compat::serialize_to_document(&read_pref).unwrap(); assert_eq!( doc, diff --git a/src/test/auth.rs b/src/test/auth.rs index 93ba7ef1c..c6f4ca430 100644 --- a/src/test/auth.rs +++ b/src/test/auth.rs @@ -36,7 +36,7 @@ async fn plain_auth() { authenticated: String, } - let doc: TestDocument = crate::bson::from_document(doc).unwrap(); + let doc: TestDocument = crate::bson_compat::deserialize_from_document(doc).unwrap(); assert_eq!( doc, diff --git a/src/test/client.rs b/src/test/client.rs index e2c5664eb..95033b768 100644 --- a/src/test/client.rs +++ b/src/test/client.rs @@ -80,7 +80,8 @@ async fn metadata_sent_in_handshake() { .get_document("clientMetadata") .unwrap() .clone(); - let metadata: ClientMetadata = crate::bson::from_document(metadata_document).unwrap(); + let metadata: ClientMetadata = + crate::bson_compat::deserialize_from_document(metadata_document).unwrap(); assert_eq!(metadata.driver.name, "mongo-rust-driver"); assert_eq!(metadata.driver.version, env!("CARGO_PKG_VERSION")); diff --git a/src/test/coll.rs b/src/test/coll.rs index 86982a49e..b2477cb07 100644 --- a/src/test/coll.rs +++ b/src/test/coll.rs @@ -5,15 +5,8 @@ use once_cell::sync::Lazy; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::{ - bson::{ - doc, - rawdoc, - serde_helpers::HumanReadable, - to_document, - Bson, - Document, - RawDocumentBuf, - }, + bson::{doc, rawdoc, serde_helpers::HumanReadable, Bson, Document, RawDocumentBuf}, + bson_compat::serialize_to_document, error::{ErrorKind, Result, WriteFailure}, options::{ Acknowledgment, @@ -578,7 +571,7 @@ async fn delete_hint_test(options: Option, name: &str) { .unwrap() .get("hint") .cloned() - .map(|bson| crate::bson::from_bson(bson).unwrap()); + .map(|bson| crate::bson_compat::deserialize_from_bson(bson).unwrap()); let expected_hint = options.and_then(|options| options.hint); assert_eq!(event_hint, expected_hint); } @@ -626,7 +619,7 @@ async fn find_one_and_delete_hint_test(options: Option, .command .get("hint") .cloned() - .map(|bson| crate::bson::from_bson(bson).unwrap()); + .map(|bson| crate::bson_compat::deserialize_from_bson(bson).unwrap()); let expected_hint = options.and_then(|options| options.hint); assert_eq!(event_hint, expected_hint); } @@ -746,7 +739,7 @@ where { coll.insert_one(insert_data.clone()).await.unwrap(); let result = coll - .find_one(to_document(&insert_data).unwrap()) + .find_one(serialize_to_document(&insert_data).unwrap()) .await .unwrap(); match result { diff --git a/src/test/db.rs b/src/test/db.rs index 4a744b468..73babc0a4 100644 --- a/src/test/db.rs +++ b/src/test/db.rs @@ -1,6 +1,6 @@ use std::cmp::Ord; -use crate::bson::RawDocumentBuf; +use crate::{bson::RawDocumentBuf, bson_compat::RawDocumentBufExt as _}; use futures::{stream::TryStreamExt, StreamExt}; use serde::Deserialize; @@ -187,7 +187,8 @@ async fn collection_management() { assert_eq!(colls[0].name, format!("{}1", function_name!())); assert_eq!(colls[0].collection_type, CollectionType::Collection); assert_eq!( - crate::bson::to_document(&colls[0].options).expect("serialization should succeed"), + crate::bson_compat::serialize_to_document(&colls[0].options) + .expect("serialization should succeed"), doc! {} ); assert!(!colls[0].info.read_only); @@ -331,7 +332,8 @@ async fn index_option_defaults_test(defaults: Option, name: #[test] fn deserialize_clustered_index_option_from_bool() { let options_doc = doc! { "clusteredIndex": true }; - let options: CreateCollectionOptions = crate::bson::from_document(options_doc).unwrap(); + let options: CreateCollectionOptions = + crate::bson_compat::deserialize_from_document(options_doc).unwrap(); let clustered_index = options .clustered_index .expect("deserialized options should include clustered_index"); @@ -429,7 +431,7 @@ async fn test_run_command() { // Test run_raw_command { let mut cmd = RawDocumentBuf::new(); - cmd.append("ping", 1); + cmd.append_err("ping", 1).unwrap(); let got = database.run_raw_command(cmd).await.unwrap(); assert_eq!(crate::bson_util::get_int(got.get("ok").unwrap()), Some(1)); } @@ -457,8 +459,8 @@ async fn test_run_command() { // Test run_raw_cursor_command { let mut cmd = RawDocumentBuf::new(); - cmd.append("find", "coll"); - cmd.append("filter", RawDocumentBuf::new()); + cmd.append_err("find", "coll").unwrap(); + cmd.append_err("filter", RawDocumentBuf::new()).unwrap(); let cursor = database.run_raw_cursor_command(cmd).await.unwrap(); let v: Vec> = cursor.collect().await; diff --git a/src/test/spec/read_write_concern/connection_string.rs b/src/test/spec/read_write_concern/connection_string.rs index 8fd8ebe1b..83e3d00ff 100644 --- a/src/test/spec/read_write_concern/connection_string.rs +++ b/src/test/spec/read_write_concern/connection_string.rs @@ -54,7 +54,8 @@ async fn run_connection_string_test(test_file: TestFile) { &normalize_write_concern_doc( options .write_concern - .map(|w| crate::bson::to_document(&w).expect(&test_case.description)) + .map(|w| crate::bson_compat::serialize_to_document(&w) + .expect(&test_case.description)) .unwrap_or_default() ), write_concern, diff --git a/src/test/spec/read_write_concern/document.rs b/src/test/spec/read_write_concern/document.rs index 8ad1fdda5..7b53c5144 100644 --- a/src/test/spec/read_write_concern/document.rs +++ b/src/test/spec/read_write_concern/document.rs @@ -30,29 +30,29 @@ async fn run_document_test(test_file: TestFile) { let description = test_case.description.as_str(); if let Some(specified_write_concern_document) = test_case.write_concern { - let specified_write_concern = - match crate::bson::from_document::(specified_write_concern_document) - .map_err(Error::from) - .and_then(|wc| wc.validate().map(|_| wc)) - { - Ok(write_concern) => { - assert!( - test_case.valid, - "Write concern deserialization/validation should fail: {}", - description - ); - write_concern - } - Err(err) => { - assert!( - !test_case.valid, - "Write concern deserialization/validation should succeed but got \ - {:?}: {}", - err, description, - ); - continue; - } - }; + let specified_write_concern = match crate::bson_compat::deserialize_from_document::< + WriteConcern, + >(specified_write_concern_document) + .map_err(Error::from) + .and_then(|wc| wc.validate().map(|_| wc)) + { + Ok(write_concern) => { + assert!( + test_case.valid, + "Write concern deserialization/validation should fail: {}", + description + ); + write_concern + } + Err(err) => { + assert!( + !test_case.valid, + "Write concern deserialization/validation should succeed but got {:?}: {}", + err, description, + ); + continue; + } + }; if let Some(is_server_default) = test_case.is_server_default { assert_eq!( @@ -76,13 +76,15 @@ async fn run_document_test(test_file: TestFile) { ); } - let actual_write_concern_document = crate::bson::to_document(&specified_write_concern) - .unwrap_or_else(|err| { - panic!( - "Write concern serialization should succeed but got {:?}: {}", - err, description - ) - }); + let actual_write_concern_document = crate::bson_compat::serialize_to_document( + &specified_write_concern, + ) + .unwrap_or_else(|err| { + panic!( + "Write concern serialization should succeed but got {:?}: {}", + err, description + ) + }); if let Some(expected_write_concern_document) = test_case.write_concern_document { assert_eq!( @@ -101,20 +103,23 @@ async fn run_document_test(test_file: TestFile) { } let specified_read_concern: ReadConcern = - crate::bson::from_document(specified_read_concern_document).unwrap_or_else(|err| { - panic!( - "Read concern deserialization should succeed but got {:?}: {}", - err, description, - ) - }); + crate::bson_compat::deserialize_from_document(specified_read_concern_document) + .unwrap_or_else(|err| { + panic!( + "Read concern deserialization should succeed but got {:?}: {}", + err, description, + ) + }); - let actual_read_concern_document = crate::bson::to_document(&specified_read_concern) - .unwrap_or_else(|err| { - panic!( - "Read concern serialization should succeed but got: {:?}: {}", - err, description - ) - }); + let actual_read_concern_document = crate::bson_compat::serialize_to_document( + &specified_read_concern, + ) + .unwrap_or_else(|err| { + panic!( + "Read concern serialization should succeed but got: {:?}: {}", + err, description + ) + }); if let Some(expected_read_concern_document) = test_case.read_concern_document { assert_eq!( diff --git a/src/test/spec/unified_runner/entity.rs b/src/test/spec/unified_runner/entity.rs index cdaacb677..d23e44fc8 100644 --- a/src/test/spec/unified_runner/entity.rs +++ b/src/test/spec/unified_runner/entity.rs @@ -6,7 +6,7 @@ use std::{ time::Duration, }; -use crate::bson::to_document; +use crate::bson_compat::serialize_to_document; use time::OffsetDateTime; use tokio::sync::{mpsc, oneshot, Mutex, RwLock}; @@ -287,7 +287,7 @@ impl ClientEntity { Event::Cmap(ev) => ev.planned_maintenance_testing_name(), }; if names.contains(&name) { - let ev_doc = to_document(&event).unwrap(); + let ev_doc = serialize_to_document(&event).unwrap(); write_json(ev_doc, name, &time); } } diff --git a/src/test/spec/unified_runner/matcher.rs b/src/test/spec/unified_runner/matcher.rs index 72fe943cd..c5f670780 100644 --- a/src/test/spec/unified_runner/matcher.rs +++ b/src/test/spec/unified_runner/matcher.rs @@ -193,7 +193,7 @@ pub(crate) fn tracing_events_match( }; } - let serialized_fields = crate::bson::to_document(&actual.fields) + let serialized_fields = crate::bson_compat::serialize_to_document(&actual.fields) .map_err(|e| format!("Failed to serialize tracing fields to document: {}", e))?; results_match( diff --git a/src/test/spec/unified_runner/operation.rs b/src/test/spec/unified_runner/operation.rs index eee1016c7..d45957162 100644 --- a/src/test/spec/unified_runner/operation.rs +++ b/src/test/spec/unified_runner/operation.rs @@ -318,7 +318,8 @@ pub(crate) enum Expectation { fn deserialize_op<'de, 'a, T: 'a + DeserializeOwned + TestOperation>( value: Document, ) -> std::result::Result, crate::bson::de::Error> { - crate::bson::from_document::(value).map(|op| Box::new(op) as Box) + crate::bson_compat::deserialize_from_document::(value) + .map(|op| Box::new(op) as Box) } impl<'de> Deserialize<'de> for Operation { diff --git a/src/test/spec/unified_runner/operation/bulk_write.rs b/src/test/spec/unified_runner/operation/bulk_write.rs index 83d8b5750..7b5219d10 100644 --- a/src/test/spec/unified_runner/operation/bulk_write.rs +++ b/src/test/spec/unified_runner/operation/bulk_write.rs @@ -3,7 +3,7 @@ use futures_util::FutureExt; use serde::Deserialize; use crate::{ - bson::to_bson, + bson_compat::serialize_to_bson, error::Result, options::{ BulkWriteOptions, @@ -71,11 +71,11 @@ impl TestOperation for BulkWrite { let result = if let Some(true) = self.verbose_results { with_opt_session!(test_runner, &self.session, action.verbose_results()) .await - .and_then(|result| Ok(to_bson(&result)?)) + .and_then(|result| Ok(serialize_to_bson(&result)?)) } else { with_opt_session!(test_runner, &self.session, action) .await - .and_then(|result| Ok(to_bson(&result)?)) + .and_then(|result| Ok(serialize_to_bson(&result)?)) }?; Ok(Some(result.into())) } diff --git a/src/test/spec/unified_runner/operation/command.rs b/src/test/spec/unified_runner/operation/command.rs index ba7a08960..1ce5734c1 100644 --- a/src/test/spec/unified_runner/operation/command.rs +++ b/src/test/spec/unified_runner/operation/command.rs @@ -1,6 +1,7 @@ use crate::{ action::Action, - bson::{to_bson, Document}, + bson::Document, + bson_compat::serialize_to_bson, error::Result, options::{RunCursorCommandOptions, SelectionCriteria}, test::spec::unified_runner::{ @@ -46,7 +47,7 @@ impl TestOperation for RunCommand { }), ) .await?; - let result = to_bson(&result)?; + let result = serialize_to_bson(&result)?; Ok(Some(result.into())) } .boxed() @@ -93,7 +94,7 @@ impl TestOperation for RunCursorCommand { } }; - Ok(Some(crate::bson::to_bson(&result)?.into())) + Ok(Some(crate::bson_compat::serialize_to_bson(&result)?.into())) } .boxed() } diff --git a/src/test/spec/unified_runner/operation/csfle.rs b/src/test/spec/unified_runner/operation/csfle.rs index 766786767..04c01cf45 100644 --- a/src/test/spec/unified_runner/operation/csfle.rs +++ b/src/test/spec/unified_runner/operation/csfle.rs @@ -54,7 +54,7 @@ impl TestOperation for DeleteKey { let ce = test_runner.get_client_encryption(id).await; let result = ce.delete_key(&self.id).await?; Ok(Some(Entity::Bson(Bson::Document( - crate::bson::to_document(&result)?, + crate::bson_compat::serialize_to_document(&result)?, )))) } .boxed() diff --git a/src/test/spec/unified_runner/operation/delete.rs b/src/test/spec/unified_runner/operation/delete.rs index fa2ec2f44..3f2f4ce4d 100644 --- a/src/test/spec/unified_runner/operation/delete.rs +++ b/src/test/spec/unified_runner/operation/delete.rs @@ -1,5 +1,6 @@ use crate::{ - bson::{to_bson, Document}, + bson::Document, + bson_compat::serialize_to_bson, error::Result, options::DeleteOptions, test::spec::unified_runner::{ @@ -37,7 +38,7 @@ impl TestOperation for DeleteMany { .with_options(self.options.clone()) ) .await?; - let result = to_bson(&result)?; + let result = serialize_to_bson(&result)?; Ok(Some(result.into())) } .boxed() @@ -69,7 +70,7 @@ impl TestOperation for DeleteOne { .with_options(self.options.clone()), ) .await?; - let result = to_bson(&result)?; + let result = serialize_to_bson(&result)?; Ok(Some(result.into())) } .boxed() diff --git a/src/test/spec/unified_runner/operation/find.rs b/src/test/spec/unified_runner/operation/find.rs index a2279fd72..a638a191e 100644 --- a/src/test/spec/unified_runner/operation/find.rs +++ b/src/test/spec/unified_runner/operation/find.rs @@ -1,7 +1,8 @@ use std::time::Duration; use crate::{ - bson::{to_bson, Bson, Document}, + bson::{Bson, Document}, + bson_compat::serialize_to_bson, error::Result, options::{ Collation, @@ -292,7 +293,7 @@ impl TestOperation for FindOneAndUpdate { .with_options(self.options.clone()), ) .await?; - let result = to_bson(&result)?; + let result = serialize_to_bson(&result)?; Ok(Some(result.into())) } .boxed() @@ -325,7 +326,7 @@ impl TestOperation for FindOneAndReplace { .with_options(self.options.clone()) ) .await?; - let result = to_bson(&result)?; + let result = serialize_to_bson(&result)?; Ok(Some(result.into())) } @@ -358,7 +359,7 @@ impl TestOperation for FindOneAndDelete { .with_options(self.options.clone()) ) .await?; - let result = to_bson(&result)?; + let result = serialize_to_bson(&result)?; Ok(Some(result.into())) } .boxed() diff --git a/src/test/spec/unified_runner/operation/index.rs b/src/test/spec/unified_runner/operation/index.rs index 2c96c0ff1..d5ad6cba2 100644 --- a/src/test/spec/unified_runner/operation/index.rs +++ b/src/test/spec/unified_runner/operation/index.rs @@ -78,7 +78,7 @@ impl TestOperation for ListIndexes { }; let indexes: Vec = indexes .iter() - .map(|index| crate::bson::to_document(index).unwrap()) + .map(|index| crate::bson_compat::serialize_to_document(index).unwrap()) .collect(); Ok(Some(Bson::from(indexes).into())) } diff --git a/src/test/spec/unified_runner/operation/insert.rs b/src/test/spec/unified_runner/operation/insert.rs index 016324445..da9cbafc5 100644 --- a/src/test/spec/unified_runner/operation/insert.rs +++ b/src/test/spec/unified_runner/operation/insert.rs @@ -1,6 +1,9 @@ use std::collections::HashMap; -use crate::bson::{doc, to_bson, Bson, Document}; +use crate::{ + bson::{doc, Bson, Document}, + bson_compat::serialize_to_bson, +}; use serde::Deserialize; use crate::{ @@ -39,7 +42,7 @@ impl TestOperation for InsertOne { .with_options(self.options.clone()), ) .await?; - let result = to_bson(&result)?; + let result = serialize_to_bson(&result)?; Ok(Some(result.into())) } .boxed() @@ -76,7 +79,7 @@ impl TestOperation for InsertMany { .into_iter() .map(|(k, v)| (k.to_string(), v)) .collect(); - let ids = to_bson(&ids)?; + let ids = serialize_to_bson(&ids)?; Ok(Some(Bson::from(doc! { "insertedIds": ids }).into())) } .boxed() diff --git a/src/test/spec/unified_runner/operation/iteration.rs b/src/test/spec/unified_runner/operation/iteration.rs index 53fde5c13..9404dac74 100644 --- a/src/test/spec/unified_runner/operation/iteration.rs +++ b/src/test/spec/unified_runner/operation/iteration.rs @@ -84,7 +84,7 @@ impl TestOperation for IterateUntilDocumentOrError { TestCursor::ChangeStream(stream) => { let mut stream = stream.lock().await; stream.next().await.map(|res| { - res.map(|ev| match crate::bson::to_bson(&ev) { + res.map(|ev| match crate::bson_compat::serialize_to_bson(&ev) { Ok(Bson::Document(doc)) => doc, _ => panic!("invalid serialization result"), }) diff --git a/src/test/spec/unified_runner/operation/list.rs b/src/test/spec/unified_runner/operation/list.rs index 3dd8f9eba..49eaf918b 100644 --- a/src/test/spec/unified_runner/operation/list.rs +++ b/src/test/spec/unified_runner/operation/list.rs @@ -35,7 +35,7 @@ impl TestOperation for ListDatabases { client.list_databases().with_options(self.options.clone()), ) .await?; - Ok(Some(crate::bson::to_bson(&result)?.into())) + Ok(Some(crate::bson_compat::serialize_to_bson(&result)?.into())) } .boxed() } @@ -103,7 +103,7 @@ impl TestOperation for ListCollections { cursor.try_collect::>().await? } }; - Ok(Some(crate::bson::to_bson(&result)?.into())) + Ok(Some(crate::bson_compat::serialize_to_bson(&result)?.into())) } .boxed() } diff --git a/src/test/spec/unified_runner/operation/rename.rs b/src/test/spec/unified_runner/operation/rename.rs index 0d4ca9a84..c69971874 100644 --- a/src/test/spec/unified_runner/operation/rename.rs +++ b/src/test/spec/unified_runner/operation/rename.rs @@ -26,11 +26,12 @@ impl TestOperation for Rename { match test_runner.entities.read().await.get(id).unwrap() { Entity::Collection(c) => { let args: RenameCollection = - crate::bson::from_document(self.0.clone()).unwrap(); + crate::bson_compat::deserialize_from_document(self.0.clone()).unwrap(); args.run(c.clone(), test_runner).await } Entity::Bucket(b) => { - let args: RenameBucket = crate::bson::from_document(self.0.clone()).unwrap(); + let args: RenameBucket = + crate::bson_compat::deserialize_from_document(self.0.clone()).unwrap(); args.run(b.clone()).await } other => panic!("cannot execute rename on {:?}", other), @@ -56,8 +57,8 @@ impl RenameCollection { let mut to_ns = ns.clone(); to_ns.coll.clone_from(&self.to); let cmd = doc! { - "renameCollection": crate::bson::to_bson(&ns)?, - "to": crate::bson::to_bson(&to_ns)?, + "renameCollection": crate::bson_compat::serialize_to_bson(&ns)?, + "to": crate::bson_compat::serialize_to_bson(&to_ns)?, }; let admin = test_runner.internal_client.database("admin"); admin.run_command(cmd).await?; diff --git a/src/test/spec/unified_runner/operation/search_index.rs b/src/test/spec/unified_runner/operation/search_index.rs index 3e33a80a2..a4ca4caf8 100644 --- a/src/test/spec/unified_runner/operation/search_index.rs +++ b/src/test/spec/unified_runner/operation/search_index.rs @@ -1,4 +1,7 @@ -use crate::bson::{to_bson, Bson, Document}; +use crate::{ + bson::{Bson, Document}, + bson_compat::serialize_to_bson, +}; use futures_core::future::BoxFuture; use futures_util::{FutureExt, TryStreamExt}; use serde::Deserialize; @@ -65,7 +68,7 @@ impl TestOperation for CreateSearchIndexes { .create_search_indexes(self.models.clone()) .with_options(self.options.clone()) .await?; - Ok(Some(to_bson(&names)?.into())) + Ok(Some(serialize_to_bson(&names)?.into())) } .boxed() } @@ -123,7 +126,7 @@ impl TestOperation for ListSearchIndexes { .with_options(self.options.clone()) .await?; let values: Vec<_> = cursor.try_collect().await?; - Ok(Some(to_bson(&values)?.into())) + Ok(Some(serialize_to_bson(&values)?.into())) } .boxed() } diff --git a/src/test/spec/unified_runner/operation/update.rs b/src/test/spec/unified_runner/operation/update.rs index 7a66c7294..ec6d25d1a 100644 --- a/src/test/spec/unified_runner/operation/update.rs +++ b/src/test/spec/unified_runner/operation/update.rs @@ -1,5 +1,6 @@ use crate::{ - bson::{to_bson, Document}, + bson::Document, + bson_compat::serialize_to_bson, error::Result, options::{ReplaceOptions, UpdateModifications, UpdateOptions}, test::spec::unified_runner::{ @@ -38,7 +39,7 @@ impl TestOperation for UpdateMany { .with_options(self.options.clone()), ) .await?; - let result = to_bson(&result)?; + let result = serialize_to_bson(&result)?; Ok(Some(result.into())) } .boxed() @@ -71,7 +72,7 @@ impl TestOperation for UpdateOne { .with_options(self.options.clone()), ) .await?; - let result = to_bson(&result)?; + let result = serialize_to_bson(&result)?; Ok(Some(result.into())) } .boxed() @@ -104,7 +105,7 @@ impl TestOperation for ReplaceOne { .with_options(self.options.clone()) ) .await?; - let result = to_bson(&result)?; + let result = serialize_to_bson(&result)?; Ok(Some(result.into())) } .boxed() diff --git a/src/test/spec/unified_runner/test_file.rs b/src/test/spec/unified_runner/test_file.rs index 0754db530..9d858e4ab 100644 --- a/src/test/spec/unified_runner/test_file.rs +++ b/src/test/spec/unified_runner/test_file.rs @@ -562,9 +562,9 @@ impl ExpectError { ErrorKind::BulkWrite(BulkWriteError { ref partial_result, .. }) => { - let actual_result = partial_result - .as_ref() - .map(|result| crate::bson::to_bson(result).expect(&context)); + let actual_result = partial_result.as_ref().map(|result| { + crate::bson_compat::serialize_to_bson(result).expect(&context) + }); results_match(actual_result.as_ref(), expected_result, false, None) .expect(&context); } @@ -586,7 +586,7 @@ impl ExpectError { for (expected_index, expected_error) in write_errors { let actual_error = actual_write_errors.get(expected_index).expect(&context); - let actual_error = crate::bson::to_bson(&actual_error) + let actual_error = crate::bson_compat::serialize_to_bson(&actual_error) .map_err(|e| e.to_string()) .expect(&context); results_match(Some(&actual_error), expected_error, true, None).expect(&context); @@ -609,7 +609,7 @@ impl ExpectError { ); for (actual, expected) in actual_write_concern_errors.iter().zip(write_concern_errors) { - let actual = crate::bson::to_bson(&actual) + let actual = crate::bson_compat::serialize_to_bson(&actual) .map_err(|e| e.to_string()) .expect(&context); results_match(Some(&actual), expected, true, None).expect(&context); diff --git a/src/test/spec/v2_runner.rs b/src/test/spec/v2_runner.rs index d9115a7ea..55a0047d3 100644 --- a/src/test/spec/v2_runner.rs +++ b/src/test/spec/v2_runner.rs @@ -9,7 +9,8 @@ use std::{future::IntoFuture, sync::Arc, time::Duration}; use futures::{future::BoxFuture, FutureExt}; use crate::{ - bson::{doc, from_bson}, + bson::doc, + bson_compat::deserialize_from_bson, coll::options::DropCollectionOptions, concern::WriteConcern, options::{ClientOptions, CreateCollectionOptions}, @@ -444,7 +445,7 @@ impl OpRunner<'_> { .unwrap(); } "targetedFailPoint" => { - let fail_point: FailPoint = from_bson( + let fail_point: FailPoint = deserialize_from_bson( operation .execute_on_client(&self.internal_client) .await diff --git a/src/test/spec/v2_runner/operation.rs b/src/test/spec/v2_runner/operation.rs index 7da7c1a57..38c53329e 100644 --- a/src/test/spec/v2_runner/operation.rs +++ b/src/test/spec/v2_runner/operation.rs @@ -344,7 +344,7 @@ impl TestOperation for DeleteMany { .with_options(self.options.clone()) .optional(session, |a, s| a.session(s)) .await?; - let result = crate::bson::to_bson(&result)?; + let result = crate::bson_compat::serialize_to_bson(&result)?; Ok(Some(result)) } .boxed() @@ -370,7 +370,7 @@ impl TestOperation for DeleteOne { .with_options(self.options.clone()) .optional(session, |a, s| a.session(s)) .await?; - let result = crate::bson::to_bson(&result)?; + let result = crate::bson_compat::serialize_to_bson(&result)?; Ok(Some(result)) } .boxed() @@ -440,7 +440,7 @@ impl TestOperation for InsertMany { .into_iter() .map(|(k, v)| (k.to_string(), v)) .collect(); - let ids = crate::bson::to_bson(&ids)?; + let ids = crate::bson_compat::serialize_to_bson(&ids)?; Ok(Some(Bson::from(doc! { "insertedIds": ids }))) } .boxed() @@ -468,7 +468,7 @@ impl TestOperation for InsertOne { .with_options(options) .optional(session, |a, s| a.session(s)) .await?; - let result = crate::bson::to_bson(&result)?; + let result = crate::bson_compat::serialize_to_bson(&result)?; Ok(Some(result)) } .boxed() @@ -495,7 +495,7 @@ impl TestOperation for UpdateMany { .with_options(self.options.clone()) .optional(session, |a, s| a.session(s)) .await?; - let result = crate::bson::to_bson(&result)?; + let result = crate::bson_compat::serialize_to_bson(&result)?; Ok(Some(result)) } .boxed() @@ -522,7 +522,7 @@ impl TestOperation for UpdateOne { .with_options(self.options.clone()) .optional(session, |a, s| a.session(s)) .await?; - let result = crate::bson::to_bson(&result)?; + let result = crate::bson_compat::serialize_to_bson(&result)?; Ok(Some(result)) } .boxed() @@ -729,7 +729,7 @@ impl TestOperation for ListCollections { cursor.try_collect::>().await? } }; - Ok(Some(crate::bson::to_bson(&result)?)) + Ok(Some(crate::bson_compat::serialize_to_bson(&result)?)) } .boxed() } @@ -781,7 +781,7 @@ impl TestOperation for ReplaceOne { .with_options(self.options.clone()) .optional(session, |a, s| a.session(s)) .await?; - let result = crate::bson::to_bson(&result)?; + let result = crate::bson_compat::serialize_to_bson(&result)?; Ok(Some(result)) } .boxed() @@ -808,7 +808,7 @@ impl TestOperation for FindOneAndUpdate { .with_options(self.options.clone()) .optional(session, |a, s| a.session(s)) .await?; - let result = crate::bson::to_bson(&result)?; + let result = crate::bson_compat::serialize_to_bson(&result)?; Ok(Some(result)) } .boxed() @@ -835,7 +835,7 @@ impl TestOperation for FindOneAndReplace { .with_options(self.options.clone()) .optional(session, |a, s| a.session(s)) .await?; - let result = crate::bson::to_bson(&result)?; + let result = crate::bson_compat::serialize_to_bson(&result)?; Ok(Some(result)) } .boxed() @@ -861,7 +861,7 @@ impl TestOperation for FindOneAndDelete { .with_options(self.options.clone()) .optional(session, |a, s| a.session(s)) .await?; - let result = crate::bson::to_bson(&result)?; + let result = crate::bson_compat::serialize_to_bson(&result)?; Ok(Some(result)) } .boxed() @@ -880,7 +880,8 @@ impl TestOperation for TargetedFailPoint { _client: &'a TestClient, ) -> BoxFuture<'a, Result>> { async move { - let command_document = crate::bson::to_document(&self.fail_point).unwrap(); + let command_document = + crate::bson_compat::serialize_to_document(&self.fail_point).unwrap(); Ok(Some(command_document.into())) } .boxed() @@ -935,7 +936,7 @@ impl TestOperation for ListDatabases { .list_databases() .with_options(self.options.clone()) .await?; - Ok(Some(crate::bson::to_bson(&result)?)) + Ok(Some(crate::bson_compat::serialize_to_bson(&result)?)) } .boxed() } @@ -1267,7 +1268,7 @@ impl TestOperation for ListIndexes { }; let indexes: Vec = indexes .iter() - .map(|index| crate::bson::to_document(index).unwrap()) + .map(|index| crate::bson_compat::serialize_to_document(index).unwrap()) .collect(); Ok(Some(indexes.into())) } diff --git a/src/test/spec/v2_runner/test_file.rs b/src/test/spec/v2_runner/test_file.rs index 9b3d48b1a..40ccccee3 100644 --- a/src/test/spec/v2_runner/test_file.rs +++ b/src/test/spec/v2_runner/test_file.rs @@ -1,6 +1,9 @@ use std::collections::HashMap; -use crate::bson::{doc, from_document, Bson}; +use crate::{ + bson::{doc, Bson}, + bson_compat::deserialize_from_document, +}; use futures::TryStreamExt; use serde::{Deserialize, Deserializer}; @@ -134,7 +137,7 @@ impl<'de> Deserialize<'de> for ClientOptions { #[cfg(feature = "in-use-encryption")] let auto_encrypt_opts = uri_options .remove("autoEncryptOpts") - .map(crate::bson::from_bson) + .map(crate::bson_compat::deserialize_from_bson) .transpose() .map_err(D::Error::custom)?; let uri = merge_uri_options(&DEFAULT_URI, Some(&uri_options), true); @@ -245,7 +248,7 @@ where docs.iter() .map(|doc| { let event = doc.get_document("command_started_event").unwrap(); - from_document(event.clone()).unwrap() + deserialize_from_document(event.clone()).unwrap() }) .collect(), )) diff --git a/src/test/util.rs b/src/test/util.rs index cedd6b55f..4bfe151da 100644 --- a/src/test/util.rs +++ b/src/test/util.rs @@ -240,7 +240,9 @@ impl TestClient { .database("admin") .run_command(hello.body.try_into()?) .await?; - Ok(crate::bson::from_document(hello_response_doc)?) + Ok(crate::bson_compat::deserialize_from_document( + hello_response_doc, + )?) } } diff --git a/src/test/util/fail_point.rs b/src/test/util/fail_point.rs index a2bccb01e..dc9df3a63 100644 --- a/src/test/util/fail_point.rs +++ b/src/test/util/fail_point.rs @@ -16,7 +16,7 @@ impl Client { /// method should remain in scope while the fail point is intended for use. Upon drop, the /// guard will disable the fail point on the server. pub(crate) async fn enable_fail_point(&self, fail_point: FailPoint) -> Result { - let command = crate::bson::to_document(&fail_point)?; + let command = crate::bson_compat::serialize_to_document(&fail_point)?; self.database("admin") .run_command(command) .selection_criteria(fail_point.selection_criteria.clone())