Refactor migrating away from once cell (#4614)

Co-authored-by: Tobie Morgan Hitchcock <tobie@surrealdb.com>
This commit is contained in:
Luca Giannini 2024-09-05 10:04:12 +02:00 committed by GitHub
parent 441048082f
commit 0294bde560
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
41 changed files with 164 additions and 182 deletions

4
Cargo.lock generated
View file

@ -34,7 +34,6 @@ name = "actix-example"
version = "0.1.0"
dependencies = [
"actix-web",
"once_cell",
"serde",
"surrealdb",
"thiserror",
@ -5948,7 +5947,6 @@ dependencies = [
"jsonwebtoken",
"mimalloc",
"nix 0.27.1",
"once_cell",
"opentelemetry",
"opentelemetry-otlp",
"opentelemetry-proto",
@ -6043,7 +6041,6 @@ dependencies = [
"hashbrown 0.14.5",
"indexmap 2.2.6",
"native-tls",
"once_cell",
"path-clean",
"pharos",
"pprof",
@ -6131,7 +6128,6 @@ dependencies = [
"num-traits",
"num_cpus",
"object_store",
"once_cell",
"pbkdf2",
"pharos",
"phf",

View file

@ -83,7 +83,6 @@ http = "1.1.0"
http-body = "1.0.0"
http-body-util = "0.1.1"
hyper = "1.4.1"
once_cell = "1.18.0"
opentelemetry = { version = "0.24" }
opentelemetry_sdk = { version = "0.24", features = ["rt-tokio"] }
opentelemetry-otlp = { version = "0.17.0", features = ["metrics"] }

View file

@ -3,7 +3,7 @@ name = "surrealdb-core"
publish = true
edition = "2021"
version = "2.0.0"
rust-version = "1.80.0"
rust-version = "1.80.1"
readme = "../sdk/CARGO.md"
authors = ["Tobie Morgan Hitchcock <tobie@surrealdb.com>"]
description = "A scalable, distributed, collaborative, document-graph database, for the realtime web"
@ -108,7 +108,6 @@ ndarray-stats = "=0.5.1"
num_cpus = "1.16.0"
num-traits = "0.2.18"
object_store = { version = "0.10.2", optional = false }
once_cell = "1.18.0"
pbkdf2 = { version = "0.12.2", features = ["simple"] }
phf = { version = "0.11.2", features = ["macros", "unicase"] }
pin-project-lite = "0.2.13"

View file

@ -1,4 +1,4 @@
use once_cell::sync::Lazy;
use std::sync::LazyLock;
/// The characters which are supported in server record IDs.
pub const ID_CHARS: [char; 36] = [
@ -14,41 +14,42 @@ pub const PROTECTED_PARAM_NAMES: &[&str] = &["access", "auth", "token", "session
/// Specifies how many concurrent jobs can be buffered in the worker channel.
#[cfg(not(target_arch = "wasm32"))]
pub static MAX_CONCURRENT_TASKS: Lazy<usize> =
pub static MAX_CONCURRENT_TASKS: LazyLock<usize> =
lazy_env_parse!("SURREAL_MAX_CONCURRENT_TASKS", usize, 64);
/// Specifies how deep computation recursive call will go before en error is returned.
pub static MAX_COMPUTATION_DEPTH: Lazy<u32> =
pub static MAX_COMPUTATION_DEPTH: LazyLock<u32> =
lazy_env_parse!("SURREAL_MAX_COMPUTATION_DEPTH", u32, 120);
/// Specifies the number of items which can be cached within a single transaction.
pub static TRANSACTION_CACHE_SIZE: Lazy<usize> =
pub static TRANSACTION_CACHE_SIZE: LazyLock<usize> =
lazy_env_parse!("SURREAL_TRANSACTION_CACHE_SIZE", usize, 10_000);
/// The maximum number of keys that should be scanned at once in general queries.
pub static NORMAL_FETCH_SIZE: Lazy<u32> = lazy_env_parse!("SURREAL_NORMAL_FETCH_SIZE", u32, 50);
pub static NORMAL_FETCH_SIZE: LazyLock<u32> = lazy_env_parse!("SURREAL_NORMAL_FETCH_SIZE", u32, 50);
/// The maximum number of keys that should be scanned at once for export queries.
pub static EXPORT_BATCH_SIZE: Lazy<u32> = lazy_env_parse!("SURREAL_EXPORT_BATCH_SIZE", u32, 1000);
pub static EXPORT_BATCH_SIZE: LazyLock<u32> =
lazy_env_parse!("SURREAL_EXPORT_BATCH_SIZE", u32, 1000);
/// The maximum number of keys that should be fetched when streaming range scans in a Scanner.
pub static MAX_STREAM_BATCH_SIZE: Lazy<u32> =
pub static MAX_STREAM_BATCH_SIZE: LazyLock<u32> =
lazy_env_parse!("SURREAL_MAX_STREAM_BATCH_SIZE", u32, 1000);
/// The maximum number of keys that should be scanned at once per concurrent indexing batch.
pub static INDEXING_BATCH_SIZE: Lazy<u32> =
pub static INDEXING_BATCH_SIZE: LazyLock<u32> =
lazy_env_parse!("SURREAL_INDEXING_BATCH_SIZE", u32, 250);
/// The maximum stack size of the JavaScript function runtime (defaults to 256 KiB)
pub static SCRIPTING_MAX_STACK_SIZE: Lazy<usize> =
pub static SCRIPTING_MAX_STACK_SIZE: LazyLock<usize> =
lazy_env_parse!("SURREAL_SCRIPTING_MAX_STACK_SIZE", usize, 256 * 1024);
/// The maximum memory limit of the JavaScript function runtime (defaults to 2 MiB).
pub static SCRIPTING_MAX_MEMORY_LIMIT: Lazy<usize> =
pub static SCRIPTING_MAX_MEMORY_LIMIT: LazyLock<usize> =
lazy_env_parse!("SURREAL_SCRIPTING_MAX_MEMORY_LIMIT", usize, 2 << 20);
/// Forward all signup/signin/authenticate query errors to a client performing authentication. Do not use in production.
pub static INSECURE_FORWARD_ACCESS_ERRORS: Lazy<bool> =
pub static INSECURE_FORWARD_ACCESS_ERRORS: LazyLock<bool> =
lazy_env_parse!("SURREAL_INSECURE_FORWARD_ACCESS_ERRORS", bool, false);
#[cfg(any(
@ -60,25 +61,25 @@ pub static INSECURE_FORWARD_ACCESS_ERRORS: Lazy<bool> =
feature = "kv-surrealcs",
))]
/// Specifies the buffer limit for external sorting.
pub static EXTERNAL_SORTING_BUFFER_LIMIT: Lazy<usize> =
pub static EXTERNAL_SORTING_BUFFER_LIMIT: LazyLock<usize> =
lazy_env_parse!("SURREAL_EXTERNAL_SORTING_BUFFER_LIMIT", usize, 50_000);
/// Specifies whether GraphQL querying and schema definition is enabled.
pub static GRAPHQL_ENABLE: Lazy<bool> =
pub static GRAPHQL_ENABLE: LazyLock<bool> =
lazy_env_parse!("SURREAL_EXPERIMENTAL_GRAPHQL", bool, false);
/// Enable experimental bearer access and stateful access grant management. Still under active development.
/// Using this experimental feature may introduce risks related to breaking changes and security issues.
#[cfg(not(test))]
pub static EXPERIMENTAL_BEARER_ACCESS: Lazy<bool> =
pub static EXPERIMENTAL_BEARER_ACCESS: LazyLock<bool> =
lazy_env_parse!("SURREAL_EXPERIMENTAL_BEARER_ACCESS", bool, false);
/// Run tests with bearer access enabled as it introduces new functionality that needs to be tested.
#[cfg(test)]
pub static EXPERIMENTAL_BEARER_ACCESS: Lazy<bool> = Lazy::new(|| true);
pub static EXPERIMENTAL_BEARER_ACCESS: LazyLock<bool> = LazyLock::new(|| true);
/// Used to limit allocation for builtin functions
pub static GENERATION_ALLOCATION_LIMIT: Lazy<usize> = once_cell::sync::Lazy::new(|| {
pub static GENERATION_ALLOCATION_LIMIT: LazyLock<usize> = LazyLock::new(|| {
let n = std::env::var("SURREAL_GENERATION_ALLOCATION_LIMIT")
.map(|s| s.parse::<u32>().unwrap_or(20))
.unwrap_or(20);

View file

@ -1,12 +1,12 @@
#![cfg(not(target_arch = "wasm32"))]
use executor::{Executor, Task};
use once_cell::sync::Lazy;
use std::future::Future;
use std::panic::catch_unwind;
use std::sync::LazyLock;
pub fn spawn<T: Send + 'static>(future: impl Future<Output = T> + Send + 'static) -> Task<T> {
static GLOBAL: Lazy<Executor<'_>> = Lazy::new(|| {
static GLOBAL: LazyLock<Executor<'_>> = LazyLock::new(|| {
std::thread::spawn(|| {
catch_unwind(|| {
futures::executor::block_on(GLOBAL.run(futures::future::pending::<()>()))

View file

@ -186,16 +186,16 @@ pub mod is {
use crate::sql::value::Value;
use crate::sql::{Datetime, Thing};
use chrono::NaiveDateTime;
use once_cell::sync::Lazy;
use regex::Regex;
use semver::Version;
use std::char;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::LazyLock;
use url::Url;
use uuid::Uuid;
#[rustfmt::skip] static LATITUDE_RE: Lazy<Regex> = Lazy::new(|| Regex::new("^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$").unwrap());
#[rustfmt::skip] static LONGITUDE_RE: Lazy<Regex> = Lazy::new(|| Regex::new("^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$").unwrap());
#[rustfmt::skip] static LATITUDE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new("^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$").unwrap());
#[rustfmt::skip] static LONGITUDE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new("^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$").unwrap());
pub fn alphanum((arg,): (String,)) -> Result<Value, Error> {
Ok(arg.chars().all(char::is_alphanumeric).into())

View file

@ -1,8 +1,8 @@
use fuzzy_matcher::skim::SkimMatcherV2;
use fuzzy_matcher::FuzzyMatcher;
use once_cell::sync::Lazy;
use std::sync::LazyLock;
static MATCHER: Lazy<SkimMatcherV2> = Lazy::new(|| SkimMatcherV2::default().ignore_case());
static MATCHER: LazyLock<SkimMatcherV2> = LazyLock::new(|| SkimMatcherV2::default().ignore_case());
pub trait Fuzzy {
/// Retrieve the fuzzy similarity score of this &str compared to another &str

View file

@ -1,9 +1,9 @@
use ascii::any_ascii as ascii;
use once_cell::sync::Lazy;
use regex::Regex;
use std::sync::LazyLock;
static SIMPLES: Lazy<Regex> = Lazy::new(|| Regex::new("[^a-z0-9-_]").unwrap());
static HYPHENS: Lazy<Regex> = Lazy::new(|| Regex::new("-+").unwrap());
static SIMPLES: LazyLock<Regex> = LazyLock::new(|| Regex::new("[^a-z0-9-_]").unwrap());
static HYPHENS: LazyLock<Regex> = LazyLock::new(|| Regex::new("-+").unwrap());
pub fn slug<S: AsRef<str>>(s: S) -> String {
// Get a reference

View file

@ -1,7 +1,7 @@
use cedar_policy::Schema;
use once_cell::sync::Lazy;
use std::sync::LazyLock;
pub static DEFAULT_CEDAR_SCHEMA: Lazy<serde_json::Value> = Lazy::new(|| {
pub static DEFAULT_CEDAR_SCHEMA: LazyLock<serde_json::Value> = LazyLock::new(|| {
serde_json::json!(
{
"": {

View file

@ -6,13 +6,13 @@ use jsonwebtoken::jwk::{
AlgorithmParameters::*, Jwk, JwkSet, KeyAlgorithm, KeyOperations, PublicKeyUse,
};
use jsonwebtoken::{Algorithm::*, DecodingKey, Validation};
use once_cell::sync::Lazy;
use reqwest::{Client, Url};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc;
use std::sync::LazyLock;
use tokio::sync::RwLock;
pub(crate) type JwksCache = HashMap<String, JwksCacheEntry>;
@ -23,10 +23,10 @@ pub(crate) struct JwksCacheEntry {
}
#[cfg(test)]
static CACHE_EXPIRATION: Lazy<chrono::Duration> = Lazy::new(|| Duration::seconds(1));
static CACHE_EXPIRATION: LazyLock<chrono::Duration> = LazyLock::new(|| Duration::seconds(1));
#[cfg(not(test))]
static CACHE_EXPIRATION: Lazy<chrono::Duration> =
Lazy::new(|| match std::env::var("SURREAL_JWKS_CACHE_EXPIRATION_SECONDS") {
static CACHE_EXPIRATION: LazyLock<chrono::Duration> =
LazyLock::new(|| match std::env::var("SURREAL_JWKS_CACHE_EXPIRATION_SECONDS") {
Ok(seconds_str) => {
let seconds = seconds_str.parse::<u64>().expect(
"Expected a valid number of seconds for SURREAL_JWKS_CACHE_EXPIRATION_SECONDS",
@ -39,10 +39,10 @@ static CACHE_EXPIRATION: Lazy<chrono::Duration> =
});
#[cfg(test)]
static CACHE_COOLDOWN: Lazy<chrono::Duration> = Lazy::new(|| Duration::seconds(300));
static CACHE_COOLDOWN: LazyLock<chrono::Duration> = LazyLock::new(|| Duration::seconds(300));
#[cfg(not(test))]
static CACHE_COOLDOWN: Lazy<chrono::Duration> =
Lazy::new(|| match std::env::var("SURREAL_JWKS_CACHE_COOLDOWN_SECONDS") {
static CACHE_COOLDOWN: LazyLock<chrono::Duration> =
LazyLock::new(|| match std::env::var("SURREAL_JWKS_CACHE_COOLDOWN_SECONDS") {
Ok(seconds_str) => {
let seconds = seconds_str.parse::<u64>().expect(
"Expected a valid number of seconds for SURREAL_JWKS_CACHE_COOLDOWN_SECONDS",
@ -55,8 +55,8 @@ static CACHE_COOLDOWN: Lazy<chrono::Duration> =
});
#[cfg(not(target_arch = "wasm32"))]
static REMOTE_TIMEOUT: Lazy<chrono::Duration> =
Lazy::new(|| match std::env::var("SURREAL_JWKS_REMOTE_TIMEOUT_MILLISECONDS") {
static REMOTE_TIMEOUT: LazyLock<chrono::Duration> =
LazyLock::new(|| match std::env::var("SURREAL_JWKS_REMOTE_TIMEOUT_MILLISECONDS") {
Ok(milliseconds_str) => {
let milliseconds = milliseconds_str
.parse::<u64>()
@ -365,7 +365,7 @@ mod tests {
rng.sample_iter(&Alphanumeric).take(8).map(char::from).collect()
}
static DEFAULT_JWKS: Lazy<JwkSet> = Lazy::new(|| {
static DEFAULT_JWKS: LazyLock<JwkSet> = LazyLock::new(|| {
JwkSet{
keys: vec![Jwk{
common: jsonwebtoken::jwk::CommonParameters {

View file

@ -1,9 +1,9 @@
use std::str::FromStr;
use cedar_policy::PolicySet;
use once_cell::sync::Lazy;
use std::sync::LazyLock;
pub static POLICY_SET: Lazy<PolicySet> = Lazy::new(|| {
pub static POLICY_SET: LazyLock<PolicySet> = LazyLock::new(|| {
PolicySet::from_str(
r#"
// All roles can view all resources on the same level hierarchy or below

View file

@ -2,11 +2,11 @@ use crate::sql::json;
use crate::sql::Object;
use crate::sql::Value;
use jsonwebtoken::{Algorithm, Header};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::LazyLock;
pub static HEADER: Lazy<Header> = Lazy::new(|| Header::new(Algorithm::HS512));
pub static HEADER: LazyLock<Header> = LazyLock::new(|| Header::new(Algorithm::HS512));
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]

View file

@ -11,9 +11,9 @@ use crate::syn;
use argon2::{Argon2, PasswordHash, PasswordVerifier};
use chrono::Utc;
use jsonwebtoken::{decode, DecodingKey, Validation};
use once_cell::sync::Lazy;
use std::str::{self, FromStr};
use std::sync::Arc;
use std::sync::LazyLock;
fn config(alg: Algorithm, key: &[u8]) -> Result<(DecodingKey, Validation), Error> {
let (dec, mut val) = match alg {
@ -67,9 +67,9 @@ fn config(alg: Algorithm, key: &[u8]) -> Result<(DecodingKey, Validation), Error
Ok((dec, val))
}
static KEY: Lazy<DecodingKey> = Lazy::new(|| DecodingKey::from_secret(&[]));
static KEY: LazyLock<DecodingKey> = LazyLock::new(|| DecodingKey::from_secret(&[]));
static DUD: Lazy<Validation> = Lazy::new(|| {
static DUD: LazyLock<Validation> = LazyLock::new(|| {
let mut validation = Validation::new(jsonwebtoken::Algorithm::HS256);
validation.insecure_disable_signature_validation();
validation.validate_nbf = false;

View file

@ -1,10 +1,10 @@
use once_cell::sync::Lazy;
use std::sync::LazyLock;
pub static FOUNDATIONDB_TRANSACTION_TIMEOUT: Lazy<i32> =
pub static FOUNDATIONDB_TRANSACTION_TIMEOUT: LazyLock<i32> =
lazy_env_parse_or_else!("SURREAL_FOUNDATIONDB_TRANSACTION_TIMEOUT", i32, |_| { 5000 });
pub static FOUNDATIONDB_TRANSACTION_RETRY_LIMIT: Lazy<i32> =
pub static FOUNDATIONDB_TRANSACTION_RETRY_LIMIT: LazyLock<i32> =
lazy_env_parse_or_else!("SURREAL_FOUNDATIONDB_TRANSACTION_RETRY_LIMIT", i32, |_| { 5 });
pub static FOUNDATIONDB_TRANSACTION_MAX_RETRY_DELAY: Lazy<i32> =
pub static FOUNDATIONDB_TRANSACTION_MAX_RETRY_DELAY: LazyLock<i32> =
lazy_env_parse_or_else!("SURREAL_FOUNDATIONDB_TRANSACTION_MAX_RETRY_DELAY", i32, |_| { 500 });

View file

@ -14,10 +14,10 @@ use foundationdb::Database;
use foundationdb::RangeOption;
use foundationdb::Transaction as Tx;
use futures::StreamExt;
use once_cell::sync::Lazy;
use std::fmt::Debug;
use std::ops::Range;
use std::sync::Arc;
use std::sync::LazyLock;
const TIMESTAMP: [u8; 10] = [0x00; 10];
@ -91,8 +91,8 @@ impl Datastore {
/// for more information on cluster connection files.
pub(crate) async fn new(path: &str) -> Result<Datastore, Error> {
// Initialize the FoundationDB Client API
static FDBNET: Lazy<Arc<foundationdb::api::NetworkAutoStop>> =
Lazy::new(|| Arc::new(unsafe { foundationdb::boot() }));
static FDBNET: LazyLock<Arc<foundationdb::api::NetworkAutoStop>> =
LazyLock::new(|| Arc::new(unsafe { foundationdb::boot() }));
// Store the network cancellation handle
let _fdbnet = (*FDBNET).clone();
// Configure and setup the database

View file

@ -1,28 +1,28 @@
use once_cell::sync::Lazy;
use std::sync::LazyLock;
pub static ROCKSDB_THREAD_COUNT: Lazy<i32> =
pub static ROCKSDB_THREAD_COUNT: LazyLock<i32> =
lazy_env_parse_or_else!("SURREAL_ROCKSDB_THREAD_COUNT", i32, |_| num_cpus::get() as i32);
pub static ROCKSDB_WRITE_BUFFER_SIZE: Lazy<usize> =
pub static ROCKSDB_WRITE_BUFFER_SIZE: LazyLock<usize> =
lazy_env_parse!("SURREAL_ROCKSDB_WRITE_BUFFER_SIZE", usize, 256 * 1024 * 1024);
pub static ROCKSDB_TARGET_FILE_SIZE_BASE: Lazy<u64> =
pub static ROCKSDB_TARGET_FILE_SIZE_BASE: LazyLock<u64> =
lazy_env_parse!("SURREAL_ROCKSDB_TARGET_FILE_SIZE_BASE", u64, 512 * 1024 * 1024);
pub static ROCKSDB_MAX_WRITE_BUFFER_NUMBER: Lazy<i32> =
pub static ROCKSDB_MAX_WRITE_BUFFER_NUMBER: LazyLock<i32> =
lazy_env_parse!("SURREAL_ROCKSDB_MAX_WRITE_BUFFER_NUMBER", i32, 32);
pub static ROCKSDB_MIN_WRITE_BUFFER_NUMBER_TO_MERGE: Lazy<i32> =
pub static ROCKSDB_MIN_WRITE_BUFFER_NUMBER_TO_MERGE: LazyLock<i32> =
lazy_env_parse!("SURREAL_ROCKSDB_MIN_WRITE_BUFFER_NUMBER_TO_MERGE", i32, 4);
pub static ROCKSDB_ENABLE_PIPELINED_WRITES: Lazy<bool> =
pub static ROCKSDB_ENABLE_PIPELINED_WRITES: LazyLock<bool> =
lazy_env_parse!("SURREAL_ROCKSDB_ENABLE_PIPELINED_WRITES", bool, true);
pub static ROCKSDB_ENABLE_BLOB_FILES: Lazy<bool> =
pub static ROCKSDB_ENABLE_BLOB_FILES: LazyLock<bool> =
lazy_env_parse!("SURREAL_ROCKSDB_ENABLE_BLOB_FILES", bool, true);
pub static ROCKSDB_MIN_BLOB_SIZE: Lazy<u64> =
pub static ROCKSDB_MIN_BLOB_SIZE: LazyLock<u64> =
lazy_env_parse!("SURREAL_ROCKSDB_MIN_BLOB_SIZE", u64, 4 * 1024);
pub static ROCKSDB_KEEP_LOG_FILE_NUM: Lazy<usize> =
pub static ROCKSDB_KEEP_LOG_FILE_NUM: LazyLock<usize> =
lazy_env_parse!("SURREAL_ROCKSDB_KEEP_LOG_FILE_NUM", usize, 20);

View file

@ -83,12 +83,12 @@ macro_rules! run {
///
/// # Return Value
///
/// A lazy static variable of type `once_cell::sync::Lazy`, which holds the parsed value
/// A lazy static variable of type `std::sync::LazyLock`, which holds the parsed value
/// from the environment variable or the default value.
#[macro_export]
macro_rules! lazy_env_parse {
($key:expr, $t:ty, $default:expr) => {
once_cell::sync::Lazy::new(|| {
std::sync::LazyLock::new(|| {
std::env::var($key)
.and_then(|s| Ok(s.parse::<$t>().unwrap_or($default)))
.unwrap_or($default)
@ -111,7 +111,7 @@ macro_rules! lazy_env_parse {
#[macro_export]
macro_rules! lazy_env_parse_or_else {
($key:expr, $t:ty, $default:expr) => {
once_cell::sync::Lazy::new(|| {
std::sync::LazyLock::new(|| {
std::env::var($key)
.and_then(|s| Ok(s.parse::<$t>().unwrap_or_else($default)))
.unwrap_or_else($default)

View file

@ -10,11 +10,11 @@ use object_store::memory::InMemory;
use object_store::parse_url;
use object_store::path::Path;
use object_store::ObjectStore;
use once_cell::sync::Lazy;
use sha1::{Digest, Sha1};
use std::env;
use std::fs;
use std::sync::Arc;
use std::sync::LazyLock;
use url::Url;
fn initialize_store(env_var: &str, default_dir: &str) -> Arc<dyn ObjectStore> {
@ -46,11 +46,11 @@ fn initialize_store(env_var: &str, default_dir: &str) -> Arc<dyn ObjectStore> {
}
}
static STORE: Lazy<Arc<dyn ObjectStore>> =
Lazy::new(|| initialize_store("SURREAL_OBJECT_STORE", "store"));
static STORE: LazyLock<Arc<dyn ObjectStore>> =
LazyLock::new(|| initialize_store("SURREAL_OBJECT_STORE", "store"));
static CACHE: Lazy<Arc<dyn ObjectStore>> =
Lazy::new(|| initialize_store("SURREAL_CACHE_STORE", "cache"));
static CACHE: LazyLock<Arc<dyn ObjectStore>> =
LazyLock::new(|| initialize_store("SURREAL_CACHE_STORE", "cache"));
/// Streams the file from the local system or memory object storage.
pub async fn stream(

View file

@ -3,11 +3,11 @@ use crate::rpc::format::msgpack::Pack;
use crate::rpc::RpcError;
use crate::sql::Part;
use crate::sql::{Array, Value};
use once_cell::sync::Lazy;
use std::sync::LazyLock;
pub static ID: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("id")]);
pub static METHOD: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("method")]);
pub static PARAMS: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("params")]);
pub static ID: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from("id")]);
pub static METHOD: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from("method")]);
pub static PARAMS: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from("params")]);
#[derive(Debug)]
pub struct Request {

View file

@ -1,30 +1,30 @@
use crate::sql::part::Part;
use once_cell::sync::Lazy;
use std::sync::LazyLock;
pub const OBJ_PATH_ACCESS: &str = "ac";
pub const OBJ_PATH_AUTH: &str = "rd";
pub const OBJ_PATH_TOKEN: &str = "tk";
pub static ID: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("id")]);
pub static ID: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from("id")]);
pub static IP: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("ip")]);
pub static IP: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from("ip")]);
pub static NS: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("ns")]);
pub static NS: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from("ns")]);
pub static DB: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("db")]);
pub static DB: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from("db")]);
pub static AC: Lazy<[Part; 1]> = Lazy::new(|| [Part::from(OBJ_PATH_ACCESS)]);
pub static AC: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from(OBJ_PATH_ACCESS)]);
pub static RD: Lazy<[Part; 1]> = Lazy::new(|| [Part::from(OBJ_PATH_AUTH)]);
pub static RD: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from(OBJ_PATH_AUTH)]);
pub static OR: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("or")]);
pub static OR: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from("or")]);
pub static TK: Lazy<[Part; 1]> = Lazy::new(|| [Part::from(OBJ_PATH_TOKEN)]);
pub static TK: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from(OBJ_PATH_TOKEN)]);
pub static IN: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("in")]);
pub static IN: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from("in")]);
pub static OUT: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("out")]);
pub static OUT: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from("out")]);
pub static META: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("__")]);
pub static META: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from("__")]);
pub static EDGE: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("__")]);
pub static EDGE: LazyLock<[Part; 1]> = LazyLock::new(|| [Part::from("__")]);

View file

@ -1,4 +1,3 @@
use once_cell::sync::Lazy;
use quick_cache::sync::{Cache, GuardResult};
use revision::revisioned;
use serde::{
@ -10,6 +9,7 @@ use std::fmt::Debug;
use std::fmt::{self, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::str::FromStr;
use std::sync::LazyLock;
use std::{env, str};
pub(crate) const TOKEN: &str = "$surrealdb::private::sql::Regex";
@ -27,7 +27,7 @@ impl Regex {
}
fn regex_new(str: &str) -> Result<regex::Regex, regex::Error> {
static REGEX_CACHE: Lazy<Cache<String, regex::Regex>> = Lazy::new(|| {
static REGEX_CACHE: LazyLock<Cache<String, regex::Regex>> = LazyLock::new(|| {
let cache_size: usize = env::var("SURREAL_REGEX_CACHE_SIZE")
.map_or(1000, |v| v.parse().unwrap_or(1000))
.max(10); // The minimum cache size is 10

View file

@ -9,7 +9,7 @@ FROM docker.io/rockylinux:8 as builder
RUN yum install -y gcc-toolset-13 git cmake llvm-toolset patch zlib-devel python3.11
# Install rust
ARG RUST_VERSION=1.80.0
ARG RUST_VERSION=1.80.1
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > /tmp/rustup.sh
RUN bash /tmp/rustup.sh -y --default-toolchain ${RUST_VERSION}
ENV PATH="/root/.cargo/bin:${PATH}"

View file

@ -3,7 +3,7 @@ name = "surrealdb"
publish = true
edition = "2021"
version = "2.0.0"
rust-version = "1.80.0"
rust-version = "1.80.1"
readme = "CARGO.md"
authors = ["Tobie Morgan Hitchcock <tobie@surrealdb.com>"]
description = "A scalable, distributed, collaborative, document-graph database, for the realtime web"
@ -75,7 +75,6 @@ futures = "0.3.30"
geo = { version = "0.28.0", features = ["use-serde"] }
indexmap = { version = "2.1.0", features = ["serde"] }
native-tls = { version = "0.2.11", optional = true }
once_cell = "1.18.0"
path-clean = "1.0.1"
reqwest = { version = "0.12.7", default-features = false, features = [
"json",

View file

@ -1,19 +1,21 @@
use criterion::Criterion;
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use std::sync::OnceLock;
use tokio::runtime::Runtime;
mod lib;
mod sdk;
static NUM_OPS: Lazy<usize> =
Lazy::new(|| std::env::var("BENCH_NUM_OPS").unwrap_or("1000".to_string()).parse().unwrap());
static DURATION_SECS: Lazy<u64> =
Lazy::new(|| std::env::var("BENCH_DURATION").unwrap_or("30".to_string()).parse().unwrap());
static SAMPLE_SIZE: Lazy<usize> =
Lazy::new(|| std::env::var("BENCH_SAMPLE_SIZE").unwrap_or("30".to_string()).parse().unwrap());
static WORKER_THREADS: Lazy<usize> =
Lazy::new(|| std::env::var("BENCH_WORKER_THREADS").unwrap_or("1".to_string()).parse().unwrap());
static NUM_OPS: LazyLock<usize> =
LazyLock::new(|| std::env::var("BENCH_NUM_OPS").unwrap_or("1000".to_string()).parse().unwrap());
static DURATION_SECS: LazyLock<u64> =
LazyLock::new(|| std::env::var("BENCH_DURATION").unwrap_or("30".to_string()).parse().unwrap());
static SAMPLE_SIZE: LazyLock<usize> = LazyLock::new(|| {
std::env::var("BENCH_SAMPLE_SIZE").unwrap_or("30".to_string()).parse().unwrap()
});
static WORKER_THREADS: LazyLock<usize> = LazyLock::new(|| {
std::env::var("BENCH_WORKER_THREADS").unwrap_or("1".to_string()).parse().unwrap()
});
static RUNTIME: OnceLock<Runtime> = OnceLock::new();
fn rt() -> &'static Runtime {

View file

@ -1,12 +1,12 @@
use criterion::{Criterion, Throughput};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use std::sync::LazyLock;
use std::time::Duration;
use surrealdb::{engine::any::Any, sql::Id, Surreal};
mod routines;
static DB: Lazy<Surreal<Any>> = Lazy::new(Surreal::init);
static DB: LazyLock<Surreal<Any>> = LazyLock::new(Surreal::init);
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Record {

View file

@ -6,7 +6,6 @@ publish = false
[dependencies]
actix-web = { version = "4.4.0", features = ["macros"] }
once_cell = "1.18.0"
serde = { version = "1.0.209", features = ["derive"] }
surrealdb = { path = "../.." }
thiserror = "1.0.63"

View file

@ -2,13 +2,13 @@ mod error;
mod person;
use actix_web::{App, HttpServer};
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use surrealdb::engine::remote::ws::Client;
use surrealdb::engine::remote::ws::Ws;
use surrealdb::opt::auth::Root;
use surrealdb::Surreal;
static DB: Lazy<Surreal<Client>> = Lazy::new(Surreal::init);
static DB: LazyLock<Surreal<Client>> = LazyLock::new(Surreal::init);
#[actix_web::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

View file

@ -1,10 +1,10 @@
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use surrealdb::engine::remote::ws::Client;
use surrealdb::engine::remote::ws::Ws;
use surrealdb::Surreal;
use tokio::sync::mpsc;
static DB: Lazy<Surreal<Client>> = Lazy::new(Surreal::init);
static DB: LazyLock<Surreal<Client>> = LazyLock::new(Surreal::init);
const NUM: usize = 100_000;

14
sdk/fuzz/Cargo.lock generated
View file

@ -282,17 +282,6 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "async-recursion"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30c5ef0ede93efbf733c1a727f3b6b5a1060bbedd5600183e66f6e4be4af0ec5"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.58",
]
[[package]]
name = "async-stream"
version = "0.3.5"
@ -3011,7 +3000,6 @@ dependencies = [
"futures",
"geo 0.27.0",
"indexmap 2.2.6",
"once_cell",
"path-clean",
"pharos",
"reblessive",
@ -3047,7 +3035,6 @@ dependencies = [
"async-channel",
"async-executor",
"async-graphql",
"async-recursion",
"base64 0.21.7",
"bcrypt",
"bincode",
@ -3079,7 +3066,6 @@ dependencies = [
"num-traits",
"num_cpus",
"object_store",
"once_cell",
"pbkdf2",
"pharos",
"phf",

View file

@ -218,11 +218,11 @@ impl Surreal<Any> {
/// # Examples
///
/// ```no_run
/// use once_cell::sync::Lazy;
/// use std::sync::LazyLock;
/// use surrealdb::Surreal;
/// use surrealdb::engine::any::Any;
///
/// static DB: Lazy<Surreal<Any>> = Lazy::new(Surreal::init);
/// static DB: LazyLock<Surreal<Any>> = LazyLock::new(Surreal::init);
///
/// # #[tokio::main]
/// # async fn main() -> surrealdb::Result<()> {

View file

@ -92,12 +92,12 @@ const DEFAULT_TICK_INTERVAL: Duration = Duration::from_secs(10);
/// Instantiating a global instance
///
/// ```
/// use once_cell::sync::Lazy;
/// use std::sync::LazyLock;
/// use surrealdb::{Result, Surreal};
/// use surrealdb::engine::local::Db;
/// use surrealdb::engine::local::Mem;
///
/// static DB: Lazy<Surreal<Db>> = Lazy::new(Surreal::init);
/// static DB: LazyLock<Surreal<Db>> = LazyLock::new(Surreal::init);
///
/// #[tokio::main]
/// async fn main() -> Result<()> {

View file

@ -68,12 +68,12 @@ impl Surreal<Client> {
/// # Examples
///
/// ```no_run
/// use once_cell::sync::Lazy;
/// use std::sync::LazyLock;
/// use surrealdb::Surreal;
/// use surrealdb::engine::remote::http::Client;
/// use surrealdb::engine::remote::http::Http;
///
/// static DB: Lazy<Surreal<Client>> = Lazy::new(Surreal::init);
/// static DB: LazyLock<Surreal<Client>> = LazyLock::new(Surreal::init);
///
/// # #[tokio::main]
/// # async fn main() -> surrealdb::Result<()> {

View file

@ -113,12 +113,12 @@ impl Surreal<Client> {
/// # Examples
///
/// ```no_run
/// use once_cell::sync::Lazy;
/// use std::sync::LazyLock;
/// use surrealdb::Surreal;
/// use surrealdb::engine::remote::ws::Client;
/// use surrealdb::engine::remote::ws::Ws;
///
/// static DB: Lazy<Surreal<Client>> = Lazy::new(Surreal::init);
/// static DB: LazyLock<Surreal<Client>> = LazyLock::new(Surreal::init);
///
/// # #[tokio::main]
/// # async fn main() -> surrealdb::Result<()> {

View file

@ -132,7 +132,7 @@ where
/// Using a static, compile-time scheme
///
/// ```no_run
/// use once_cell::sync::Lazy;
/// use std::sync::LazyLock;
/// use serde::{Serialize, Deserialize};
/// use surrealdb::Surreal;
/// use surrealdb::opt::auth::Root;
@ -140,7 +140,7 @@ where
/// use surrealdb::engine::remote::ws::Client;
///
/// // Creates a new static instance of the client
/// static DB: Lazy<Surreal<Client>> = Lazy::new(Surreal::init);
/// static DB: LazyLock<Surreal<Client>> = LazyLock::new(Surreal::init);
///
/// #[derive(Serialize, Deserialize)]
/// struct Person {
@ -174,14 +174,14 @@ where
/// Using a dynamic, run-time scheme
///
/// ```no_run
/// use once_cell::sync::Lazy;
/// use std::sync::LazyLock;
/// use serde::{Serialize, Deserialize};
/// use surrealdb::Surreal;
/// use surrealdb::engine::any::Any;
/// use surrealdb::opt::auth::Root;
///
/// // Creates a new static instance of the client
/// static DB: Lazy<Surreal<Any>> = Lazy::new(Surreal::init);
/// static DB: LazyLock<Surreal<Any>> = LazyLock::new(Surreal::init);
///
/// #[derive(Serialize, Deserialize)]
/// struct Person {

View file

@ -14,16 +14,16 @@ use crate::api::opt::auth::Root;
use crate::api::opt::PatchOp;
use crate::api::Response as QueryResponse;
use crate::api::Surreal;
use once_cell::sync::Lazy;
use protocol::Client;
use protocol::Test;
use semver::Version;
use std::ops::Bound;
use std::sync::LazyLock;
use surrealdb_core::sql::statements::{BeginStatement, CommitStatement};
use types::User;
use types::USER;
static DB: Lazy<Surreal<Client>> = Lazy::new(Surreal::init);
static DB: LazyLock<Surreal<Client>> = LazyLock::new(Surreal::init);
#[tokio::test]
async fn api() {

View file

@ -1,7 +1,6 @@
#[allow(unused_imports, dead_code)]
mod api_integration {
use chrono::DateTime;
use once_cell::sync::Lazy;
use semver::Version;
use serde::Deserialize;
use serde::Serialize;
@ -10,6 +9,7 @@ mod api_integration {
use std::borrow::Cow;
use std::ops::Bound;
use std::sync::Arc;
use std::sync::LazyLock;
use std::sync::Mutex;
use std::time::Duration;
use surrealdb::error::Api as ApiError;

View file

@ -1,4 +1,4 @@
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use std::time::Duration;
use surrealdb::{lazy_env_parse, lazy_env_parse_or_else};
@ -29,50 +29,50 @@ pub const PKG_NAME: &str = "surrealdb";
pub const APP_ENDPOINT: &str = "https://surrealdb.com/app";
/// The maximum HTTP body size of the HTTP /ml endpoints (defaults to 4 GiB)
pub static HTTP_MAX_ML_BODY_SIZE: Lazy<usize> =
pub static HTTP_MAX_ML_BODY_SIZE: LazyLock<usize> =
lazy_env_parse!("SURREAL_HTTP_MAX_ML_BODY_SIZE", usize, 4 << 30);
/// The maximum HTTP body size of the HTTP /sql endpoint (defaults to 1 MiB)
pub static HTTP_MAX_SQL_BODY_SIZE: Lazy<usize> =
pub static HTTP_MAX_SQL_BODY_SIZE: LazyLock<usize> =
lazy_env_parse!("SURREAL_HTTP_MAX_SQL_BODY_SIZE", usize, 1 << 20);
/// The maximum HTTP body size of the HTTP /rpc endpoint (defaults to 4 MiB)
pub static HTTP_MAX_RPC_BODY_SIZE: Lazy<usize> =
pub static HTTP_MAX_RPC_BODY_SIZE: LazyLock<usize> =
lazy_env_parse!("SURREAL_HTTP_MAX_RPC_BODY_SIZE", usize, 4 << 20);
/// The maximum HTTP body size of the HTTP /key endpoints (defaults to 16 KiB)
pub static HTTP_MAX_KEY_BODY_SIZE: Lazy<usize> =
pub static HTTP_MAX_KEY_BODY_SIZE: LazyLock<usize> =
lazy_env_parse!("SURREAL_HTTP_MAX_KEY_BODY_SIZE", usize, 16 << 10);
/// The maximum HTTP body size of the HTTP /signup endpoint (defaults to 1 KiB)
pub static HTTP_MAX_SIGNUP_BODY_SIZE: Lazy<usize> =
pub static HTTP_MAX_SIGNUP_BODY_SIZE: LazyLock<usize> =
lazy_env_parse!("SURREAL_HTTP_MAX_SIGNUP_BODY_SIZE", usize, 1 << 10);
/// The maximum HTTP body size of the HTTP /signin endpoint (defaults to 1 KiB)
pub static HTTP_MAX_SIGNIN_BODY_SIZE: Lazy<usize> =
pub static HTTP_MAX_SIGNIN_BODY_SIZE: LazyLock<usize> =
lazy_env_parse!("SURREAL_HTTP_MAX_SIGNIN_BODY_SIZE", usize, 1 << 10);
/// The maximum HTTP body size of the HTTP /import endpoint (defaults to 4 GiB)
pub static HTTP_MAX_IMPORT_BODY_SIZE: Lazy<usize> =
pub static HTTP_MAX_IMPORT_BODY_SIZE: LazyLock<usize> =
lazy_env_parse!("SURREAL_HTTP_MAX_IMPORT_BODY_SIZE", usize, 4 << 30);
/// Specifies the frequency with which ping messages should be sent to the client
pub const WEBSOCKET_PING_FREQUENCY: Duration = Duration::from_secs(5);
/// What is the maximum WebSocket frame size (defaults to 16 MiB)
pub static WEBSOCKET_MAX_FRAME_SIZE: Lazy<usize> =
pub static WEBSOCKET_MAX_FRAME_SIZE: LazyLock<usize> =
lazy_env_parse!("SURREAL_WEBSOCKET_MAX_FRAME_SIZE", usize, 16 << 20);
/// What is the maximum WebSocket message size (defaults to 128 MiB)
pub static WEBSOCKET_MAX_MESSAGE_SIZE: Lazy<usize> =
pub static WEBSOCKET_MAX_MESSAGE_SIZE: LazyLock<usize> =
lazy_env_parse!("SURREAL_WEBSOCKET_MAX_MESSAGE_SIZE", usize, 128 << 20);
/// How many concurrent tasks can be handled on each WebSocket (defaults to 24)
pub static WEBSOCKET_MAX_CONCURRENT_REQUESTS: Lazy<usize> =
pub static WEBSOCKET_MAX_CONCURRENT_REQUESTS: LazyLock<usize> =
lazy_env_parse!("SURREAL_WEBSOCKET_MAX_CONCURRENT_REQUESTS", usize, 24);
/// What is the runtime thread memory stack size (defaults to 10MiB)
pub static RUNTIME_STACK_SIZE: Lazy<usize> =
pub static RUNTIME_STACK_SIZE: LazyLock<usize> =
lazy_env_parse_or_else!("SURREAL_RUNTIME_STACK_SIZE", usize, |_| {
// Stack frames are generally larger in debug mode.
if cfg!(debug_assertions) {
@ -83,17 +83,18 @@ pub static RUNTIME_STACK_SIZE: Lazy<usize> =
});
/// How many threads which can be started for blocking operations (defaults to 512)
pub static RUNTIME_MAX_BLOCKING_THREADS: Lazy<usize> =
pub static RUNTIME_MAX_BLOCKING_THREADS: LazyLock<usize> =
lazy_env_parse!("SURREAL_RUNTIME_MAX_BLOCKING_THREADS", usize, 512);
/// The version identifier of this build
pub static PKG_VERSION: Lazy<String> = Lazy::new(|| match option_env!("SURREAL_BUILD_METADATA") {
Some(metadata) if !metadata.trim().is_empty() => {
let version = env!("CARGO_PKG_VERSION");
format!("{version}+{metadata}")
}
_ => env!("CARGO_PKG_VERSION").to_owned(),
});
pub static PKG_VERSION: LazyLock<String> =
LazyLock::new(|| match option_env!("SURREAL_BUILD_METADATA") {
Some(metadata) if !metadata.trim().is_empty() => {
let version = env!("CARGO_PKG_VERSION");
format!("{version}+{metadata}")
}
_ => env!("CARGO_PKG_VERSION").to_owned(),
});
pub static GRAPHQL_ENABLE: Lazy<bool> =
pub static GRAPHQL_ENABLE: LazyLock<bool> =
lazy_env_parse!("SURREAL_EXPERIMENTAL_GRAPHQL", bool, false);

6
src/env/mod.rs vendored
View file

@ -1,11 +1,11 @@
use crate::cnf::PKG_VERSION;
use crate::err::Error;
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use surrealdb::env::{arch, os};
/// Stores the current release identifier
pub static RELEASE: Lazy<String> =
Lazy::new(|| format!("{} for {} on {}", *PKG_VERSION, os(), arch()));
pub static RELEASE: LazyLock<String> =
LazyLock::new(|| format!("{} for {} on {}", *PKG_VERSION, os(), arch()));
pub async fn init() -> Result<(), Error> {
// Log version

View file

@ -1,14 +1,14 @@
pub(super) mod tower_layer;
use once_cell::sync::Lazy;
use opentelemetry::global;
use opentelemetry::metrics::{Histogram, Meter, MetricsError, UpDownCounter};
use std::sync::LazyLock;
use self::tower_layer::HttpCallMetricTracker;
static METER: Lazy<Meter> = Lazy::new(|| global::meter("surrealdb.http"));
static METER: LazyLock<Meter> = LazyLock::new(|| global::meter("surrealdb.http"));
pub static HTTP_SERVER_DURATION: Lazy<Histogram<u64>> = Lazy::new(|| {
pub static HTTP_SERVER_DURATION: LazyLock<Histogram<u64>> = LazyLock::new(|| {
METER
.u64_histogram("http.server.duration")
.with_description("The HTTP server duration in milliseconds.")
@ -16,14 +16,14 @@ pub static HTTP_SERVER_DURATION: Lazy<Histogram<u64>> = Lazy::new(|| {
.init()
});
pub static HTTP_SERVER_ACTIVE_REQUESTS: Lazy<UpDownCounter<i64>> = Lazy::new(|| {
pub static HTTP_SERVER_ACTIVE_REQUESTS: LazyLock<UpDownCounter<i64>> = LazyLock::new(|| {
METER
.i64_up_down_counter("http.server.active_requests")
.with_description("The number of active HTTP requests.")
.init()
});
pub static HTTP_SERVER_REQUEST_SIZE: Lazy<Histogram<u64>> = Lazy::new(|| {
pub static HTTP_SERVER_REQUEST_SIZE: LazyLock<Histogram<u64>> = LazyLock::new(|| {
METER
.u64_histogram("http.server.request.size")
.with_description("Measures the size of HTTP request messages.")
@ -31,7 +31,7 @@ pub static HTTP_SERVER_REQUEST_SIZE: Lazy<Histogram<u64>> = Lazy::new(|| {
.init()
});
pub static HTTP_SERVER_RESPONSE_SIZE: Lazy<Histogram<u64>> = Lazy::new(|| {
pub static HTTP_SERVER_RESPONSE_SIZE: LazyLock<Histogram<u64>> = LazyLock::new(|| {
METER
.u64_histogram("http.server.response.size")
.with_description("Measures the size of HTTP response messages.")

View file

@ -1,16 +1,16 @@
use std::time::Instant;
use once_cell::sync::Lazy;
use opentelemetry::metrics::Meter;
use opentelemetry::{global, KeyValue};
use opentelemetry::{
metrics::{Histogram, MetricsError, UpDownCounter},
Context as TelemetryContext,
};
use std::sync::LazyLock;
static METER: Lazy<Meter> = Lazy::new(|| global::meter("surrealdb.rpc"));
static METER: LazyLock<Meter> = LazyLock::new(|| global::meter("surrealdb.rpc"));
pub static RPC_SERVER_DURATION: Lazy<Histogram<u64>> = Lazy::new(|| {
pub static RPC_SERVER_DURATION: LazyLock<Histogram<u64>> = LazyLock::new(|| {
METER
.u64_histogram("rpc.server.duration")
.with_description("Measures duration of inbound RPC requests in milliseconds.")
@ -18,14 +18,14 @@ pub static RPC_SERVER_DURATION: Lazy<Histogram<u64>> = Lazy::new(|| {
.init()
});
pub static RPC_SERVER_ACTIVE_CONNECTIONS: Lazy<UpDownCounter<i64>> = Lazy::new(|| {
pub static RPC_SERVER_ACTIVE_CONNECTIONS: LazyLock<UpDownCounter<i64>> = LazyLock::new(|| {
METER
.i64_up_down_counter("rpc.server.active_connections")
.with_description("The number of active WebSocket connections.")
.init()
});
pub static RPC_SERVER_REQUEST_SIZE: Lazy<Histogram<u64>> = Lazy::new(|| {
pub static RPC_SERVER_REQUEST_SIZE: LazyLock<Histogram<u64>> = LazyLock::new(|| {
METER
.u64_histogram("rpc.server.request.size")
.with_description("Measures the size of HTTP request messages.")
@ -33,7 +33,7 @@ pub static RPC_SERVER_REQUEST_SIZE: Lazy<Histogram<u64>> = Lazy::new(|| {
.init()
});
pub static RPC_SERVER_RESPONSE_SIZE: Lazy<Histogram<u64>> = Lazy::new(|| {
pub static RPC_SERVER_RESPONSE_SIZE: LazyLock<Histogram<u64>> = LazyLock::new(|| {
METER
.u64_histogram("rpc.server.response.size")
.with_description("Measures the size of HTTP response messages.")

View file

@ -3,7 +3,6 @@ pub mod metrics;
pub mod traces;
use crate::cli::validator::parser::env_filter::CustomEnvFilter;
use once_cell::sync::Lazy;
use opentelemetry::metrics::MetricsError;
use opentelemetry::Context;
use opentelemetry::KeyValue;
@ -11,6 +10,7 @@ use opentelemetry_sdk::resource::{
EnvResourceDetector, SdkProvidedResourceDetector, TelemetryResourceDetector,
};
use opentelemetry_sdk::Resource;
use std::sync::LazyLock;
use std::time::Duration;
use tracing::{Level, Subscriber};
use tracing_subscriber::filter::ParseError;
@ -18,7 +18,7 @@ use tracing_subscriber::prelude::*;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::EnvFilter;
pub static OTEL_DEFAULT_RESOURCE: Lazy<Resource> = Lazy::new(|| {
pub static OTEL_DEFAULT_RESOURCE: LazyLock<Resource> = LazyLock::new(|| {
let res = Resource::from_detectors(
Duration::from_secs(5),
vec![