Skip to content

chore: move lazy_static to once_cell #1022

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 5, 2024
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ futures-util = { version = "0.3.14", features = ["io"] }
futures-executor = "0.3.14"
hex = "0.4.0"
hmac = "0.12.1"
lazy_static = "1.4.0"
once_cell = "1.19.0"
log = { version = "0.4.17", optional = true }
md-5 = "0.10.1"
mongocrypt = { git = "https://github.com/mongodb/libmongocrypt-rust.git", branch = "main", optional = true }
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ async-std-runtime = ["async-std", "mongodb/async-std-runtime"]
[dependencies]
mongodb = { path = "..", default-features = false }
serde_json = "1.0.59"
lazy_static = "1.4.0"
once_cell = "1.19.0"
clap = "2.33.3"
indicatif = "0.15.0"
async-trait = "0.1.41"
Expand Down
35 changes: 21 additions & 14 deletions benchmarks/src/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,34 +21,41 @@ use std::{
use anyhow::{bail, Result};
use futures::stream::TryStreamExt;
use indicatif::{ProgressBar, ProgressStyle};
use lazy_static::lazy_static;
use mongodb::{
bson::{doc, Bson, Document},
options::{Acknowledgment, ClientOptions, SelectionCriteria, WriteConcern},
Client,
};
use once_cell::sync::Lazy;
use serde_json::Value;

use crate::fs::{BufReader, File};

lazy_static! {
static ref DATABASE_NAME: String = option_env!("DATABASE_NAME")
static DATABASE_NAME: Lazy<String> = Lazy::new(|| {
option_env!("DATABASE_NAME")
.unwrap_or("perftest")
.to_string();
static ref COLL_NAME: String = option_env!("COLL_NAME").unwrap_or("corpus").to_string();
static ref MAX_EXECUTION_TIME: u64 = option_env!("MAX_EXECUTION_TIME")
.to_string()
});
static COLL_NAME: Lazy<String> =
Lazy::new(|| option_env!("COLL_NAME").unwrap_or("corpus").to_string());
static MAX_EXECUTION_TIME: Lazy<u64> = Lazy::new(|| {
option_env!("MAX_EXECUTION_TIME")
.unwrap_or("300")
.parse::<u64>()
.expect("invalid MAX_EXECUTION_TIME");
static ref MIN_EXECUTION_TIME: u64 = option_env!("MIN_EXECUTION_TIME")
.expect("invalid MAX_EXECUTION_TIME")
});
static MIN_EXECUTION_TIME: Lazy<u64> = Lazy::new(|| {
option_env!("MIN_EXECUTION_TIME")
.unwrap_or("60")
.parse::<u64>()
.expect("invalid MIN_EXECUTION_TIME");
pub static ref TARGET_ITERATION_COUNT: usize = option_env!("TARGET_ITERATION_COUNT")
.expect("invalid MIN_EXECUTION_TIME")
});
pub static TARGET_ITERATION_COUNT: Lazy<usize> = Lazy::new(|| {
option_env!("TARGET_ITERATION_COUNT")
.unwrap_or("100")
.parse::<usize>()
.expect("invalid TARGET_ITERATION_COUNT");
}
.expect("invalid TARGET_ITERATION_COUNT")
});

#[async_trait::async_trait]
pub trait Benchmark: Sized {
Expand Down Expand Up @@ -145,13 +152,13 @@ pub async fn drop_database(uri: &str, database: &str) -> Result<()> {
.run_command(doc! { "hello": true }, None)
.await?;

client.database(&database).drop(None).await?;
client.database(&database).drop().await?;

// in sharded clusters, take additional steps to ensure database is dropped completely.
// see: https://www.mongodb.com/docs/manual/reference/method/db.dropDatabase/#replica-set-and-sharded-clusters
let is_sharded = hello.get_str("msg").ok() == Some("isdbgrid");
if is_sharded {
client.database(&database).drop(None).await?;
client.database(&database).drop().await?;
for host in options.hosts {
client
.database("admin")
Expand Down
8 changes: 3 additions & 5 deletions benchmarks/src/bench/gridfs_multi_download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,16 @@ use std::{

use anyhow::{Context, Result};
use futures::AsyncWriteExt;
use lazy_static::lazy_static;
use mongodb::{bson::oid::ObjectId, gridfs::GridFsBucket, Client};
use once_cell::sync::Lazy;

use crate::{
bench::{drop_database, Benchmark, DATABASE_NAME},
fs::{open_async_read_compat, open_async_write_compat},
};

lazy_static! {
static ref DOWNLOAD_PATH: PathBuf =
Path::new(env!("CARGO_MANIFEST_DIR")).join("gridfs_multi_download");
}
static DOWNLOAD_PATH: Lazy<PathBuf> =
Lazy::new(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("gridfs_multi_download"));

pub struct GridFsMultiDownloadBenchmark {
uri: String,
Expand Down
6 changes: 2 additions & 4 deletions benchmarks/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ use clap::{App, Arg, ArgMatches};
use futures::Future;
#[cfg(feature = "tokio-runtime")]
use futures::FutureExt;
use lazy_static::lazy_static;
use mongodb::options::ClientOptions;
use once_cell::sync::Lazy;

use crate::{
bench::{
Expand All @@ -69,9 +69,7 @@ use crate::{
score::{score_test, BenchmarkResult, CompositeScore},
};

lazy_static! {
static ref DATA_PATH: PathBuf = Path::new(env!("CARGO_MANIFEST_DIR")).join("data");
}
static DATA_PATH: Lazy<PathBuf> = Lazy::new(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("data"));

// benchmark names
const FLAT_BSON_ENCODING: &'static str = "Flat BSON Encoding";
Expand Down
6 changes: 2 additions & 4 deletions src/client/auth/aws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::{fs::File, io::Read, time::Duration};

use chrono::{offset::Utc, DateTime};
use hmac::Hmac;
use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use rand::distributions::{Alphanumeric, DistString};
use serde::Deserialize;
use sha2::{Digest, Sha256};
Expand Down Expand Up @@ -30,9 +30,7 @@ const AWS_EC2_IP: &str = "169.254.169.254";
const AWS_LONG_DATE_FMT: &str = "%Y%m%dT%H%M%SZ";
const MECH_NAME: &str = "MONGODB-AWS";

lazy_static! {
static ref CACHED_CREDENTIAL: Mutex<Option<AwsCredential>> = Mutex::new(None);
}
static CACHED_CREDENTIAL: Lazy<Mutex<Option<AwsCredential>>> = Lazy::new(|| Mutex::new(None));

/// Performs MONGODB-AWS authentication for a given stream.
pub(super) async fn authenticate_stream(
Expand Down
13 changes: 5 additions & 8 deletions src/client/auth/scram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ use hmac::{
Hmac,
Mac,
};
use lazy_static::lazy_static;
use md5::Md5;
use once_cell::sync::Lazy;
use sha1::Sha1;
use sha2::Sha256;
use tokio::sync::RwLock;

use crate::{
bson::{doc, Bson, Document},
bson::{Bson, Document},
client::{
auth::{
self,
Expand Down Expand Up @@ -48,12 +48,9 @@ const NO_CHANNEL_BINDING: char = 'n';
/// The minimum number of iterations of the hash function that we will accept from the server.
const MIN_ITERATION_COUNT: u32 = 4096;

lazy_static! {
/// Cache of pre-computed salted passwords.
static ref CREDENTIAL_CACHE: RwLock<HashMap<CacheEntry, Vec<u8>>> = {
RwLock::new(HashMap::new())
};
}
/// Cache of pre-computed salted passwords.
static CREDENTIAL_CACHE: Lazy<RwLock<HashMap<CacheEntry, Vec<u8>>>> =
Lazy::new(|| RwLock::new(HashMap::new()));

#[derive(Hash, Eq, PartialEq)]
struct CacheEntry {
Expand Down
12 changes: 6 additions & 6 deletions src/client/auth/test.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use lazy_static::lazy_static;
use once_cell::sync::Lazy;

use crate::{cmap::StreamDescription, options::AuthMechanism};

use super::sasl::SaslStart;

lazy_static! {
static ref MECHS: [String; 2] = [
static MECHS: Lazy<[String; 2]> = Lazy::new(|| {
[
AuthMechanism::ScramSha1.as_str().to_string(),
AuthMechanism::ScramSha256.as_str().to_string()
];
}
AuthMechanism::ScramSha256.as_str().to_string(),
]
});

#[test]
fn negotiate_both_scram() {
Expand Down
42 changes: 20 additions & 22 deletions src/client/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use bson::RawDocumentBuf;
use bson::{doc, RawBsonRef, RawDocument, Timestamp};
#[cfg(feature = "in-use-encryption-unstable")]
use futures_core::future::BoxFuture;
use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use serde::de::DeserializeOwned;

use std::{
Expand Down Expand Up @@ -63,27 +63,25 @@ use crate::{
ClusterTime,
};

lazy_static! {
pub(crate) static ref REDACTED_COMMANDS: HashSet<&'static str> = {
let mut hash_set = HashSet::new();
hash_set.insert("authenticate");
hash_set.insert("saslstart");
hash_set.insert("saslcontinue");
hash_set.insert("getnonce");
hash_set.insert("createuser");
hash_set.insert("updateuser");
hash_set.insert("copydbgetnonce");
hash_set.insert("copydbsaslstart");
hash_set.insert("copydb");
hash_set
};
pub(crate) static ref HELLO_COMMAND_NAMES: HashSet<&'static str> = {
let mut hash_set = HashSet::new();
hash_set.insert("hello");
hash_set.insert(LEGACY_HELLO_COMMAND_NAME_LOWERCASE);
hash_set
};
}
pub(crate) static REDACTED_COMMANDS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
let mut hash_set = HashSet::new();
hash_set.insert("authenticate");
hash_set.insert("saslstart");
hash_set.insert("saslcontinue");
hash_set.insert("getnonce");
hash_set.insert("createuser");
hash_set.insert("updateuser");
hash_set.insert("copydbgetnonce");
hash_set.insert("copydbsaslstart");
hash_set.insert("copydb");
hash_set
});
pub(crate) static HELLO_COMMAND_NAMES: Lazy<HashSet<&'static str>> = Lazy::new(|| {
let mut hash_set = HashSet::new();
hash_set.insert("hello");
hash_set.insert(LEGACY_HELLO_COMMAND_NAME_LOWERCASE);
hash_set
});

impl Client {
/// Execute the given operation.
Expand Down
20 changes: 8 additions & 12 deletions src/client/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use std::{

use bson::UuidRepresentation;
use derivative::Derivative;
use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use serde::{de::Unexpected, Deserialize, Deserializer, Serialize};
use serde_with::skip_serializing_none;
use strsim::jaro_winkler;
Expand Down Expand Up @@ -83,18 +83,14 @@ const URI_OPTIONS: &[&str] = &[
"zlibcompressionlevel",
];

lazy_static! {
/// Reserved characters as defined by [Section 2.2 of RFC-3986](https://tools.ietf.org/html/rfc3986#section-2.2).
/// Usernames / passwords that contain these characters must instead include the URL encoded version of them when included
/// as part of the connection string.
static ref USERINFO_RESERVED_CHARACTERS: HashSet<&'static char> = {
[':', '/', '?', '#', '[', ']', '@'].iter().collect()
};
/// Reserved characters as defined by [Section 2.2 of RFC-3986](https://tools.ietf.org/html/rfc3986#section-2.2).
/// Usernames / passwords that contain these characters must instead include the URL encoded version
/// of them when included as part of the connection string.
static USERINFO_RESERVED_CHARACTERS: Lazy<HashSet<&'static char>> =
Lazy::new(|| [':', '/', '?', '#', '[', ']', '@'].iter().collect());

static ref ILLEGAL_DATABASE_CHARACTERS: HashSet<&'static char> = {
['/', '\\', ' ', '"', '$'].iter().collect()
};
}
static ILLEGAL_DATABASE_CHARACTERS: Lazy<HashSet<&'static char>> =
Lazy::new(|| ['/', '\\', ' ', '"', '$'].iter().collect());

/// An enum representing the address of a MongoDB server.
#[derive(Clone, Debug, Eq, Serialize)]
Expand Down
16 changes: 7 additions & 9 deletions src/client/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{
time::{Duration, Instant},
};

use lazy_static::lazy_static;
use once_cell::sync::Lazy;
use uuid::Uuid;

use crate::{
Expand All @@ -28,14 +28,12 @@ pub(super) use pool::ServerSessionPool;

use super::{options::ServerAddress, AsyncDropToken};

lazy_static! {
pub(crate) static ref SESSIONS_UNSUPPORTED_COMMANDS: HashSet<&'static str> = {
let mut hash_set = HashSet::new();
hash_set.insert("killcursors");
hash_set.insert("parallelcollectionscan");
hash_set
};
}
pub(crate) static SESSIONS_UNSUPPORTED_COMMANDS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
let mut hash_set = HashSet::new();
hash_set.insert("killcursors");
hash_set.insert("parallelcollectionscan");
hash_set
});

/// A MongoDB client session. This struct represents a logical session used for ordering sequential
/// operations. To create a `ClientSession`, call `start_session` on a `Client`.
Expand Down
6 changes: 1 addition & 5 deletions src/cmap/conn/wire/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,9 @@ use std::{
sync::atomic::{AtomicI32, Ordering},
};

use lazy_static::lazy_static;

/// Closure to obtain a new, unique request ID.
pub(crate) fn next_request_id() -> i32 {
lazy_static! {
static ref REQUEST_ID: AtomicI32 = AtomicI32::new(0);
}
static REQUEST_ID: AtomicI32 = AtomicI32::new(0);

REQUEST_ID.fetch_add(1, Ordering::SeqCst)
}
Expand Down
Loading