Skip to content

Commit 0f6a690

Browse files
authored
RUST-1992 Driver changes to track bson serde-optional API changes (#1401)
1 parent bc4ae96 commit 0f6a690

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

77 files changed

+546
-369
lines changed

Cargo.lock

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,11 +134,12 @@ branch = "main"
134134
package = "bson"
135135
version = "3.0.0"
136136
optional = true
137+
features = ["serde"]
137138

138139
[dependencies.mongocrypt]
139140
git = "https://github.com/mongodb/libmongocrypt-rust.git"
140141
branch = "main"
141-
version = "0.3.0"
142+
version = "0.3.1"
142143
default-features = false
143144
optional = true
144145

src/action/find_and_modify.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,8 @@ impl<T: Serialize + DeserializeOwned + Send + Sync> Collection<T> {
107107
FindOneAndReplace {
108108
coll: self,
109109
filter,
110-
replacement: crate::bson::to_raw_document_buf(replacement.borrow()).map_err(Into::into),
110+
replacement: crate::bson_compat::serialize_to_raw_document_buf(replacement.borrow())
111+
.map_err(Into::into),
111112
options: None,
112113
session: None,
113114
}

src/action/insert_many.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,10 @@ impl<T: Serialize + Send + Sync> Collection<T> {
3434
coll: CollRef::new(self),
3535
docs: docs
3636
.into_iter()
37-
.map(|v| crate::bson::to_raw_document_buf(v.borrow()).map_err(Into::into))
37+
.map(|v| {
38+
crate::bson_compat::serialize_to_raw_document_buf(v.borrow())
39+
.map_err(Into::into)
40+
})
3841
.collect(),
3942
options: None,
4043
session: None,

src/action/insert_one.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ impl<T: Serialize + Send + Sync> Collection<T> {
3232
pub fn insert_one(&self, doc: impl Borrow<T>) -> InsertOne {
3333
InsertOne {
3434
coll: CollRef::new(self),
35-
doc: crate::bson::to_raw_document_buf(doc.borrow()).map_err(Into::into),
35+
doc: crate::bson_compat::serialize_to_raw_document_buf(doc.borrow())
36+
.map_err(Into::into),
3637
options: None,
3738
session: None,
3839
}

src/action/list_databases.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ impl<'a> Action for ListDatabases<'a, ListSpecifications> {
106106
.and_then(|dbs| {
107107
dbs.into_iter()
108108
.map(|db_spec| {
109-
crate::bson::from_slice(db_spec.as_bytes())
109+
crate::bson_compat::deserialize_from_slice(db_spec.as_bytes())
110110
.map_err(crate::error::Error::from)
111111
})
112112
.collect()

src/action/replace_one.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ impl<T: Serialize + Send + Sync> Collection<T> {
3131
ReplaceOne {
3232
coll: CollRef::new(self),
3333
query,
34-
replacement: crate::bson::to_raw_document_buf(replacement.borrow()).map_err(Into::into),
34+
replacement: crate::bson_compat::serialize_to_raw_document_buf(replacement.borrow())
35+
.map_err(Into::into),
3536
options: None,
3637
session: None,
3738
}

src/bson_compat.rs

Lines changed: 112 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,132 @@
1-
#[cfg(feature = "bson-3")]
2-
pub(crate) trait RawDocumentBufExt {
3-
fn append_ref<'a>(
1+
use crate::bson::RawBson;
2+
3+
pub(crate) trait RawDocumentBufExt: Sized {
4+
fn append_err(&mut self, key: impl AsRef<str>, value: impl Into<RawBson>) -> RawResult<()>;
5+
6+
fn append_ref_err<'a>(
47
&mut self,
58
key: impl AsRef<str>,
69
value: impl Into<crate::bson::raw::RawBsonRef<'a>>,
7-
);
10+
) -> RawResult<()>;
11+
12+
#[cfg(not(feature = "bson-3"))]
13+
fn decode_from_bytes(data: Vec<u8>) -> RawResult<Self>;
814
}
915

1016
#[cfg(feature = "bson-3")]
1117
impl RawDocumentBufExt for crate::bson::RawDocumentBuf {
12-
fn append_ref<'a>(
18+
fn append_err(&mut self, key: impl AsRef<str>, value: impl Into<RawBson>) -> RawResult<()> {
19+
self.append(key, value.into())
20+
}
21+
22+
fn append_ref_err<'a>(
1323
&mut self,
1424
key: impl AsRef<str>,
1525
value: impl Into<crate::bson::raw::RawBsonRef<'a>>,
16-
) {
26+
) -> RawResult<()> {
1727
self.append(key, value)
1828
}
1929
}
2030

31+
#[cfg(not(feature = "bson-3"))]
32+
impl RawDocumentBufExt for crate::bson::RawDocumentBuf {
33+
fn append_err(&mut self, key: impl AsRef<str>, value: impl Into<RawBson>) -> RawResult<()> {
34+
self.append(key, value);
35+
Ok(())
36+
}
37+
38+
fn append_ref_err<'a>(
39+
&mut self,
40+
key: impl AsRef<str>,
41+
value: impl Into<crate::bson::raw::RawBsonRef<'a>>,
42+
) -> RawResult<()> {
43+
self.append_ref(key, value);
44+
Ok(())
45+
}
46+
47+
fn decode_from_bytes(data: Vec<u8>) -> RawResult<Self> {
48+
Self::from_bytes(data)
49+
}
50+
}
51+
52+
pub(crate) trait RawArrayBufExt: Sized {
53+
#[allow(dead_code)]
54+
fn from_iter_err<V: Into<RawBson>, I: IntoIterator<Item = V>>(iter: I) -> RawResult<Self>;
55+
56+
fn push_err(&mut self, value: impl Into<RawBson>) -> RawResult<()>;
57+
}
58+
2159
#[cfg(feature = "bson-3")]
22-
pub(crate) use crate::bson::error::Result as RawResult;
60+
impl RawArrayBufExt for crate::bson::RawArrayBuf {
61+
fn from_iter_err<V: Into<RawBson>, I: IntoIterator<Item = V>>(iter: I) -> RawResult<Self> {
62+
Self::from_iter(iter.into_iter().map(|v| v.into()))
63+
}
64+
65+
fn push_err(&mut self, value: impl Into<RawBson>) -> RawResult<()> {
66+
self.push(value.into())
67+
}
68+
}
2369

2470
#[cfg(not(feature = "bson-3"))]
25-
pub(crate) use crate::bson::raw::Result as RawResult;
71+
impl RawArrayBufExt for crate::bson::RawArrayBuf {
72+
fn from_iter_err<V: Into<RawBson>, I: IntoIterator<Item = V>>(iter: I) -> RawResult<Self> {
73+
Ok(Self::from_iter(iter))
74+
}
2675

27-
#[cfg(feature = "bson-3")]
28-
pub(crate) use crate::bson::error::Error as RawError;
76+
fn push_err(&mut self, value: impl Into<RawBson>) -> RawResult<()> {
77+
self.push(value);
78+
Ok(())
79+
}
80+
}
2981

3082
#[cfg(not(feature = "bson-3"))]
31-
pub(crate) use crate::bson::raw::Error as RawError;
83+
pub(crate) trait RawDocumentExt {
84+
fn decode_from_bytes<D: AsRef<[u8]> + ?Sized>(data: &D) -> RawResult<&Self>;
85+
}
86+
87+
#[cfg(not(feature = "bson-3"))]
88+
impl RawDocumentExt for crate::bson::RawDocument {
89+
fn decode_from_bytes<D: AsRef<[u8]> + ?Sized>(data: &D) -> RawResult<&Self> {
90+
Self::from_bytes(data)
91+
}
92+
}
93+
94+
#[cfg(not(feature = "bson-3"))]
95+
#[allow(dead_code)]
96+
pub(crate) trait DocumentExt {
97+
fn encode_to_vec(&self) -> crate::bson::ser::Result<Vec<u8>>;
98+
}
99+
100+
#[cfg(not(feature = "bson-3"))]
101+
impl DocumentExt for crate::bson::Document {
102+
fn encode_to_vec(&self) -> crate::bson::ser::Result<Vec<u8>> {
103+
let mut out = vec![];
104+
self.to_writer(&mut out)?;
105+
Ok(out)
106+
}
107+
}
108+
109+
macro_rules! use_either {
110+
($($name:ident => $path3:path | $path2:path);+;) => {
111+
$(
112+
#[cfg(feature = "bson-3")]
113+
pub(crate) use crate::bson::{$path3 as $name};
114+
115+
#[cfg(not(feature = "bson-3"))]
116+
#[allow(unused_imports)]
117+
pub(crate) use crate::bson::{$path2 as $name};
118+
)+
119+
};
120+
}
121+
122+
// Exported name => bson3 import | bson2 import
123+
use_either! {
124+
RawResult => error::Result | raw::Result;
125+
RawError => error::Error | raw::Error;
126+
serialize_to_raw_document_buf => serialize_to_raw_document_buf | to_raw_document_buf;
127+
serialize_to_document => serialize_to_document | to_document;
128+
serialize_to_bson => serialize_to_bson | to_bson;
129+
deserialize_from_slice => deserialize_from_slice | from_slice;
130+
deserialize_from_document => deserialize_from_document | from_document;
131+
deserialize_from_bson => deserialize_from_bson | from_bson;
132+
}

src/bson_util.rs

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,12 @@ use crate::{
1717
RawBsonRef,
1818
RawDocumentBuf,
1919
},
20+
bson_compat::{RawArrayBufExt, RawDocumentBufExt as _},
2021
checked::Checked,
2122
error::{Error, ErrorKind, Result},
2223
runtime::SyncLittleEndianRead,
2324
};
2425

25-
#[cfg(feature = "bson-3")]
26-
use crate::bson_compat::RawDocumentBufExt as _;
27-
2826
/// Coerce numeric types into an `i64` if it would be lossless to do so. If this Bson is not numeric
2927
/// or the conversion would be lossy (e.g. 1.5 -> 1), this returns `None`.
3028
#[allow(clippy::cast_possible_truncation)]
@@ -80,14 +78,14 @@ pub(crate) fn to_bson_array(docs: &[Document]) -> Bson {
8078
pub(crate) fn to_raw_bson_array(docs: &[Document]) -> Result<RawBson> {
8179
let mut array = RawArrayBuf::new();
8280
for doc in docs {
83-
array.push(RawDocumentBuf::from_document(doc)?);
81+
array.push_err(RawDocumentBuf::from_document(doc)?)?;
8482
}
8583
Ok(RawBson::Array(array))
8684
}
8785
pub(crate) fn to_raw_bson_array_ser<T: Serialize>(values: &[T]) -> Result<RawBson> {
8886
let mut array = RawArrayBuf::new();
8987
for value in values {
90-
array.push(crate::bson::to_raw_document_buf(value)?);
88+
array.push_err(crate::bson_compat::serialize_to_raw_document_buf(value)?)?;
9189
}
9290
Ok(RawBson::Array(array))
9391
}
@@ -149,12 +147,12 @@ pub(crate) fn array_entry_size_bytes(index: usize, doc_len: usize) -> Result<usi
149147
(Checked::new(1) + num_decimal_digits(index) + 1 + doc_len).get()
150148
}
151149

152-
pub(crate) fn vec_to_raw_array_buf(docs: Vec<RawDocumentBuf>) -> RawArrayBuf {
150+
pub(crate) fn vec_to_raw_array_buf(docs: Vec<RawDocumentBuf>) -> Result<RawArrayBuf> {
153151
let mut array = RawArrayBuf::new();
154152
for doc in docs {
155-
array.push(doc);
153+
array.push_err(doc)?;
156154
}
157-
array
155+
Ok(array)
158156
}
159157

160158
/// The number of digits in `n` in base 10.
@@ -202,7 +200,7 @@ pub(crate) fn extend_raw_document_buf(
202200
k
203201
)));
204202
}
205-
this.append(k, v.to_raw_bson());
203+
this.append_err(k, v.to_raw_bson())?;
206204
}
207205
Ok(())
208206
}
@@ -216,13 +214,13 @@ pub(crate) fn append_ser(
216214
struct Helper<T> {
217215
value: T,
218216
}
219-
let raw_doc = crate::bson::to_raw_document_buf(&Helper { value })?;
220-
this.append_ref(
217+
let raw_doc = crate::bson_compat::serialize_to_raw_document_buf(&Helper { value })?;
218+
this.append_ref_err(
221219
key,
222220
raw_doc
223221
.get("value")?
224222
.ok_or_else(|| Error::internal("no value"))?,
225-
);
223+
)?;
226224
Ok(())
227225
}
228226

@@ -243,7 +241,7 @@ pub(crate) fn get_or_prepend_id_field(doc: &mut RawDocumentBuf) -> Result<Bson>
243241
let new_length: i32 = Checked::new(new_bytes.len()).try_into()?;
244242
new_bytes[0..4].copy_from_slice(&new_length.to_le_bytes());
245243

246-
*doc = RawDocumentBuf::from_bytes(new_bytes)?;
244+
*doc = RawDocumentBuf::decode_from_bytes(new_bytes)?;
247245

248246
Ok(id.into())
249247
}

src/change_stream.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,9 @@ where
158158
/// ```
159159
pub async fn next_if_any(&mut self) -> Result<Option<T>> {
160160
Ok(match NextInBatchFuture::new(self).await? {
161-
BatchValue::Some { doc, .. } => Some(crate::bson::from_slice(doc.as_bytes())?),
161+
BatchValue::Some { doc, .. } => {
162+
Some(crate::bson_compat::deserialize_from_slice(doc.as_bytes())?)
163+
}
162164
BatchValue::Empty | BatchValue::Exhausted => None,
163165
})
164166
}

src/change_stream/session.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,9 @@ where
148148
match bv {
149149
BatchValue::Some { doc, .. } => {
150150
self.data.document_returned = true;
151-
return Ok(Some(crate::bson::from_slice(doc.as_bytes())?));
151+
return Ok(Some(crate::bson_compat::deserialize_from_slice(
152+
doc.as_bytes(),
153+
)?));
152154
}
153155
BatchValue::Empty | BatchValue::Exhausted => return Ok(None),
154156
}

src/client/auth.rs

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ mod x509;
1414

1515
use std::{borrow::Cow, fmt::Debug, str::FromStr};
1616

17-
use crate::bson::RawDocumentBuf;
17+
use crate::{bson::RawDocumentBuf, bson_compat::RawDocumentBufExt as _};
1818
use derive_where::derive_where;
1919
use hmac::{digest::KeyInit, Mac};
2020
use rand::Rng;
@@ -240,7 +240,7 @@ impl AuthMechanism {
240240
Ok(Some(ClientFirst::Scram(ScramVersion::Sha256, client_first)))
241241
}
242242
Self::MongoDbX509 => Ok(Some(ClientFirst::X509(Box::new(
243-
x509::build_speculative_client_first(credential),
243+
x509::build_speculative_client_first(credential)?,
244244
)))),
245245
Self::Plain => Ok(None),
246246
Self::MongoDbOidc => Ok(oidc::build_speculative_client_first(credential)
@@ -447,13 +447,17 @@ impl Credential {
447447

448448
/// If the mechanism is missing, append the appropriate mechanism negotiation key-value-pair to
449449
/// the provided hello or legacy hello command document.
450-
pub(crate) fn append_needed_mechanism_negotiation(&self, command: &mut RawDocumentBuf) {
450+
pub(crate) fn append_needed_mechanism_negotiation(
451+
&self,
452+
command: &mut RawDocumentBuf,
453+
) -> Result<()> {
451454
if let (Some(username), None) = (self.username.as_ref(), self.mechanism.as_ref()) {
452-
command.append(
455+
command.append_err(
453456
"saslSupportedMechs",
454457
format!("{}.{}", self.resolved_source(), username),
455-
);
458+
)?;
456459
}
460+
Ok(())
457461
}
458462

459463
/// Attempts to authenticate a stream according to this credential, returning an error
@@ -551,12 +555,12 @@ pub(crate) enum ClientFirst {
551555
}
552556

553557
impl ClientFirst {
554-
pub(crate) fn to_document(&self) -> RawDocumentBuf {
555-
match self {
556-
Self::Scram(version, client_first) => client_first.to_command(version).body,
558+
pub(crate) fn to_document(&self) -> Result<RawDocumentBuf> {
559+
Ok(match self {
560+
Self::Scram(version, client_first) => client_first.to_command(version)?.body,
557561
Self::X509(command) => command.body.clone(),
558562
Self::Oidc(command) => command.body.clone(),
559-
}
563+
})
560564
}
561565

562566
pub(crate) fn into_first_round(self, server_first: Document) -> FirstRound {

0 commit comments

Comments
 (0)