Skip to content

Commit a38c035

Browse files
authored
RUST-1992 Update the driver for bson cstr API changes (#1412)
1 parent d7a6b0c commit a38c035

Some content is hidden

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

44 files changed

+299
-363
lines changed

Cargo.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/bson_compat.rs

Lines changed: 43 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,84 +1,71 @@
1-
use crate::bson::RawBson;
1+
#[cfg(feature = "bson-3")]
2+
pub(crate) type CStr = crate::bson::raw::CStr;
3+
#[cfg(feature = "bson-3")]
4+
pub(crate) type CString = crate::bson::raw::CString;
5+
#[cfg(feature = "bson-3")]
6+
pub(crate) use crate::bson::raw::cstr;
27

3-
pub(crate) trait RawDocumentBufExt: Sized {
4-
fn append_err(&mut self, key: impl AsRef<str>, value: impl Into<RawBson>) -> RawResult<()>;
8+
#[cfg(not(feature = "bson-3"))]
9+
pub(crate) type CStr = str;
10+
#[cfg(not(feature = "bson-3"))]
11+
pub(crate) type CString = String;
12+
#[cfg(not(feature = "bson-3"))]
13+
macro_rules! cstr {
14+
($text:literal) => {
15+
$text
16+
};
17+
}
18+
#[cfg(not(feature = "bson-3"))]
19+
pub(crate) use cstr;
520

6-
fn append_ref_err<'a>(
21+
pub(crate) fn cstr_to_str(cs: &CStr) -> &str {
22+
#[cfg(feature = "bson-3")]
23+
{
24+
cs.as_str()
25+
}
26+
#[cfg(not(feature = "bson-3"))]
27+
{
28+
cs
29+
}
30+
}
31+
32+
pub(crate) trait RawDocumentBufExt: Sized {
33+
fn append_ref_compat<'a>(
734
&mut self,
8-
key: impl AsRef<str>,
9-
value: impl Into<crate::bson::raw::RawBsonRef<'a>>,
10-
) -> RawResult<()>;
35+
key: impl AsRef<CStr>,
36+
value: impl Into<crate::bson::raw::RawBsonRef<'a>> + 'a,
37+
);
1138

1239
#[cfg(not(feature = "bson-3"))]
1340
fn decode_from_bytes(data: Vec<u8>) -> RawResult<Self>;
1441
}
1542

1643
#[cfg(feature = "bson-3")]
1744
impl RawDocumentBufExt for crate::bson::RawDocumentBuf {
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>(
45+
fn append_ref_compat<'a>(
2346
&mut self,
24-
key: impl AsRef<str>,
25-
value: impl Into<crate::bson::raw::RawBsonRef<'a>>,
26-
) -> RawResult<()> {
27-
self.append(key, value)
47+
key: impl AsRef<CStr>,
48+
value: impl Into<crate::bson::raw::RawBsonRef<'a>> + 'a,
49+
) {
50+
self.append(key, value);
2851
}
2952
}
3053

3154
#[cfg(not(feature = "bson-3"))]
3255
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>(
56+
fn append_ref_compat<'a>(
3957
&mut self,
40-
key: impl AsRef<str>,
58+
key: impl AsRef<CStr>,
4159
value: impl Into<crate::bson::raw::RawBsonRef<'a>>,
42-
) -> RawResult<()> {
43-
self.append_ref(key, value);
44-
Ok(())
60+
) {
61+
self.append_ref(key, value)
4562
}
4663

4764
fn decode_from_bytes(data: Vec<u8>) -> RawResult<Self> {
4865
Self::from_bytes(data)
4966
}
5067
}
5168

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-
59-
#[cfg(feature = "bson-3")]
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-
}
69-
70-
#[cfg(not(feature = "bson-3"))]
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-
}
75-
76-
fn push_err(&mut self, value: impl Into<RawBson>) -> RawResult<()> {
77-
self.push(value);
78-
Ok(())
79-
}
80-
}
81-
8269
#[cfg(not(feature = "bson-3"))]
8370
pub(crate) trait RawDocumentExt {
8471
fn decode_from_bytes<D: AsRef<[u8]> + ?Sized>(data: &D) -> RawResult<&Self>;

src/bson_util.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use crate::{
1717
RawBsonRef,
1818
RawDocumentBuf,
1919
},
20-
bson_compat::{RawArrayBufExt, RawDocumentBufExt as _},
20+
bson_compat::RawDocumentBufExt as _,
2121
checked::Checked,
2222
error::{Error, ErrorKind, Result},
2323
runtime::SyncLittleEndianRead,
@@ -78,14 +78,14 @@ pub(crate) fn to_bson_array(docs: &[Document]) -> Bson {
7878
pub(crate) fn to_raw_bson_array(docs: &[Document]) -> Result<RawBson> {
7979
let mut array = RawArrayBuf::new();
8080
for doc in docs {
81-
array.push_err(RawDocumentBuf::from_document(doc)?)?;
81+
array.push(RawDocumentBuf::from_document(doc)?);
8282
}
8383
Ok(RawBson::Array(array))
8484
}
8585
pub(crate) fn to_raw_bson_array_ser<T: Serialize>(values: &[T]) -> Result<RawBson> {
8686
let mut array = RawArrayBuf::new();
8787
for value in values {
88-
array.push_err(crate::bson_compat::serialize_to_raw_document_buf(value)?)?;
88+
array.push(crate::bson_compat::serialize_to_raw_document_buf(value)?);
8989
}
9090
Ok(RawBson::Array(array))
9191
}
@@ -127,7 +127,7 @@ pub(crate) fn replacement_document_check(replacement: &Document) -> Result<()> {
127127

128128
pub(crate) fn replacement_raw_document_check(replacement: &RawDocumentBuf) -> Result<()> {
129129
if let Some((key, _)) = replacement.iter().next().transpose()? {
130-
if key.starts_with('$') {
130+
if crate::bson_compat::cstr_to_str(key).starts_with('$') {
131131
return Err(ErrorKind::InvalidArgument {
132132
message: "replacement document must not contain update modifiers".to_string(),
133133
}
@@ -147,12 +147,12 @@ pub(crate) fn array_entry_size_bytes(index: usize, doc_len: usize) -> Result<usi
147147
(Checked::new(1) + num_decimal_digits(index) + 1 + doc_len).get()
148148
}
149149

150-
pub(crate) fn vec_to_raw_array_buf(docs: Vec<RawDocumentBuf>) -> Result<RawArrayBuf> {
150+
pub(crate) fn vec_to_raw_array_buf(docs: Vec<RawDocumentBuf>) -> RawArrayBuf {
151151
let mut array = RawArrayBuf::new();
152152
for doc in docs {
153-
array.push_err(doc)?;
153+
array.push(doc);
154154
}
155-
Ok(array)
155+
array
156156
}
157157

158158
/// The number of digits in `n` in base 10.
@@ -188,7 +188,7 @@ pub(crate) fn extend_raw_document_buf(
188188
this: &mut RawDocumentBuf,
189189
other: RawDocumentBuf,
190190
) -> Result<()> {
191-
let mut keys: HashSet<String> = HashSet::new();
191+
let mut keys: HashSet<crate::bson_compat::CString> = HashSet::new();
192192
for elem in this.iter_elements() {
193193
keys.insert(elem?.key().to_owned());
194194
}
@@ -200,27 +200,27 @@ pub(crate) fn extend_raw_document_buf(
200200
k
201201
)));
202202
}
203-
this.append_err(k, v.to_raw_bson())?;
203+
this.append(k, v.to_raw_bson());
204204
}
205205
Ok(())
206206
}
207207

208208
pub(crate) fn append_ser(
209209
this: &mut RawDocumentBuf,
210-
key: impl AsRef<str>,
210+
key: impl AsRef<crate::bson_compat::CStr>,
211211
value: impl Serialize,
212212
) -> Result<()> {
213213
#[derive(Serialize)]
214214
struct Helper<T> {
215215
value: T,
216216
}
217217
let raw_doc = crate::bson_compat::serialize_to_raw_document_buf(&Helper { value })?;
218-
this.append_ref_err(
218+
this.append_ref_compat(
219219
key,
220220
raw_doc
221221
.get("value")?
222222
.ok_or_else(|| Error::internal("no value"))?,
223-
)?;
223+
);
224224
Ok(())
225225
}
226226

src/client/auth.rs

Lines changed: 5 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, bson_compat::RawDocumentBufExt as _};
17+
use crate::{bson::RawDocumentBuf, bson_compat::cstr};
1818
use derive_where::derive_where;
1919
use hmac::{digest::KeyInit, Mac};
2020
use rand::Rng;
@@ -447,17 +447,13 @@ 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(
451-
&self,
452-
command: &mut RawDocumentBuf,
453-
) -> Result<()> {
450+
pub(crate) fn append_needed_mechanism_negotiation(&self, command: &mut RawDocumentBuf) {
454451
if let (Some(username), None) = (self.username.as_ref(), self.mechanism.as_ref()) {
455-
command.append_err(
456-
"saslSupportedMechs",
452+
command.append(
453+
cstr!("saslSupportedMechs"),
457454
format!("{}.{}", self.resolved_source(), username),
458-
)?;
455+
);
459456
}
460-
Ok(())
461457
}
462458

463459
/// Attempts to authenticate a stream according to this credential, returning an error

src/client/auth/oidc.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use typed_builder::TypedBuilder;
99

1010
use crate::{
1111
bson::{doc, rawdoc, spec::BinarySubtype, Binary, Document},
12-
bson_compat::RawDocumentBufExt as _,
12+
bson_compat::cstr,
1313
client::options::{ServerAddress, ServerApi},
1414
cmap::{Command, Connection},
1515
error::{Error, Result},
@@ -620,9 +620,9 @@ async fn send_sasl_start_command(
620620
) -> Result<SaslResponse> {
621621
let mut start_doc = rawdoc! {};
622622
if let Some(access_token) = access_token {
623-
start_doc.append_err("jwt", access_token)?;
623+
start_doc.append(cstr!("jwt"), access_token);
624624
} else if let Some(username) = credential.username.as_deref() {
625-
start_doc.append_err("n", username)?;
625+
start_doc.append(cstr!("n"), username);
626626
}
627627
let sasl_start = SaslStart::new(
628628
source.to_string(),

src/client/auth/sasl.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use crate::bson::{rawdoc, RawBson};
22

33
use crate::{
44
bson::{spec::BinarySubtype, Binary, Bson, Document},
5-
bson_compat::RawDocumentBufExt as _,
5+
bson_compat::cstr,
66
bson_util,
77
client::{auth::AuthMechanism, options::ServerApi},
88
cmap::Command,
@@ -42,7 +42,7 @@ impl SaslStart {
4242
if self.mechanism == AuthMechanism::ScramSha1
4343
|| self.mechanism == AuthMechanism::ScramSha256
4444
{
45-
body.append_err("options", rawdoc! { "skipEmptyExchange": true })?;
45+
body.append(cstr!("options"), rawdoc! { "skipEmptyExchange": true });
4646
}
4747

4848
let mut command = Command::new("saslStart", self.source, body);

src/client/auth/scram.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use tokio::sync::RwLock;
1919

2020
use crate::{
2121
bson::{Bson, Document},
22-
bson_compat::RawDocumentBufExt as _,
22+
bson_compat::cstr,
2323
client::{
2424
auth::{
2525
self,
@@ -461,7 +461,7 @@ impl ClientFirst {
461461
let mut cmd = sasl_start.into_command()?;
462462

463463
if self.include_db {
464-
cmd.body.append_err("db", self.source.clone())?;
464+
cmd.body.append(cstr!("db"), self.source.clone());
465465
}
466466

467467
Ok(cmd)

src/client/auth/x509.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use crate::bson::rawdoc;
22

33
use crate::{
44
bson::Document,
5-
bson_compat::RawDocumentBufExt as _,
5+
bson_compat::cstr,
66
client::options::ServerApi,
77
cmap::{Command, Connection, RawCommandResponse},
88
error::{Error, Result},
@@ -25,7 +25,7 @@ pub(crate) fn build_client_first(
2525
};
2626

2727
if let Some(ref username) = credential.username {
28-
auth_command_doc.append_err("username", username.as_str())?;
28+
auth_command_doc.append(cstr!("username"), username.as_str());
2929
}
3030

3131
let mut command = Command::new("authenticate", "$external", auth_command_doc);

src/client/csfle/state_machine.rs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use std::{
77

88
use crate::{
99
bson::{rawdoc, Document, RawDocument, RawDocumentBuf},
10-
bson_compat::RawDocumentBufExt as _,
10+
bson_compat::{cstr, CString},
1111
};
1212
use futures_util::{stream, TryStreamExt};
1313
use mongocrypt::ctx::{Ctx, KmsCtx, KmsProviderType, State};
@@ -245,6 +245,7 @@ impl CryptExecutor {
245245
continue;
246246
}
247247

248+
let prov_name: CString = provider.as_string().try_into()?;
248249
match provider.provider_type() {
249250
KmsProviderType::Aws => {
250251
#[cfg(feature = "aws-auth")]
@@ -264,9 +265,9 @@ impl CryptExecutor {
264265
"secretAccessKey": aws_creds.secret_key(),
265266
};
266267
if let Some(token) = aws_creds.session_token() {
267-
creds.append_err("sessionToken", token)?;
268+
creds.append(cstr!("sessionToken"), token);
268269
}
269-
kms_providers.append_err(provider.as_string(), creds)?;
270+
kms_providers.append(prov_name, creds);
270271
}
271272
#[cfg(not(feature = "aws-auth"))]
272273
{
@@ -279,10 +280,7 @@ impl CryptExecutor {
279280
KmsProviderType::Azure => {
280281
#[cfg(feature = "azure-kms")]
281282
{
282-
kms_providers.append_err(
283-
provider.as_string(),
284-
self.azure.get_token().await?,
285-
)?;
283+
kms_providers.append(prov_name, self.azure.get_token().await?);
286284
}
287285
#[cfg(not(feature = "azure-kms"))]
288286
{
@@ -330,10 +328,10 @@ impl CryptExecutor {
330328
.send()
331329
.await
332330
.map_err(|e| kms_error(e.to_string()))?;
333-
kms_providers.append_err(
334-
"gcp",
331+
kms_providers.append(
332+
cstr!("gcp"),
335333
rawdoc! { "accessToken": response.access_token },
336-
)?;
334+
);
337335
}
338336
#[cfg(not(feature = "gcp-kms"))]
339337
{

src/client/executor.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ impl Client {
323323
let (server, effective_criteria) = match self
324324
.select_server(
325325
selection_criteria,
326-
op.name(),
326+
crate::bson_compat::cstr_to_str(op.name()),
327327
retry.as_ref().map(|r| &r.first_server),
328328
op.override_criteria(),
329329
)

0 commit comments

Comments
 (0)