Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion mongocrypt/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ compile_fail = []
mongocrypt-sys = { path = "../mongocrypt-sys" }
bson = { git = "https://github.com/mongodb/bson-rust", branch = "main" }
serde = "1.0.125"
once_cell = "1.17.0"

[dev-dependencies]
serde_json = "1.0.81"
serde_json = "1.0.81"
15 changes: 13 additions & 2 deletions mongocrypt/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{borrow::Borrow, ffi::CStr, path::Path, ptr};
use std::{borrow::Borrow, ffi::CStr, path::Path, ptr, sync::Mutex};

use bson::Document;
#[cfg(test)]
Expand All @@ -19,6 +19,7 @@ mod test;
use error::{HasStatus, Result};
pub use hooks::*;
use native::OwnedPtr;
use once_cell::sync::Lazy;

/// Returns the version string for libmongocrypt.
pub fn version() -> &'static str {
Expand All @@ -38,11 +39,19 @@ impl HasStatus for CryptBuilder {
}
}

// This works around a possible race condition in mongocrypt [de]initialization; see RUST-1578 for details.
static CRYPT_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add a comment indicating why the lock is needed, possibly referencing the libmongocrpyt bug filed for this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.


unsafe extern "C" fn mongocrypt_destroy_locked(crypt: *mut sys::mongocrypt_t) {
let _guard = CRYPT_LOCK.lock().unwrap();
sys::mongocrypt_destroy(crypt);
}

impl CryptBuilder {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
inner: OwnedPtr::steal(unsafe { sys::mongocrypt_new() }, sys::mongocrypt_destroy),
inner: OwnedPtr::steal(unsafe { sys::mongocrypt_new() }, mongocrypt_destroy_locked),
cleanup: vec![],
}
}
Expand Down Expand Up @@ -216,6 +225,8 @@ impl CryptBuilder {
}

pub fn build(mut self) -> Result<Crypt> {
let _guard = CRYPT_LOCK.lock().unwrap();

let ok = unsafe { sys::mongocrypt_init(*self.inner.borrow()) };
if !ok {
return Err(self.status().as_error());
Expand Down