Use once_cell instead of lazy_static

This commit is contained in:
Felix Ableitner 2021-11-22 19:58:31 +01:00
parent 76c4378011
commit e88106cef4
19 changed files with 60 additions and 74 deletions

12
Cargo.lock generated
View file

@ -1760,7 +1760,6 @@ dependencies = [
"http", "http",
"http-signature-normalization-actix", "http-signature-normalization-actix",
"itertools", "itertools",
"lazy_static",
"lemmy_api_common", "lemmy_api_common",
"lemmy_apub", "lemmy_apub",
"lemmy_apub_lib", "lemmy_apub_lib",
@ -1822,7 +1821,6 @@ dependencies = [
"http", "http",
"http-signature-normalization-actix", "http-signature-normalization-actix",
"itertools", "itertools",
"lazy_static",
"lemmy_api_common", "lemmy_api_common",
"lemmy_apub", "lemmy_apub",
"lemmy_apub_lib", "lemmy_apub_lib",
@ -1869,7 +1867,6 @@ dependencies = [
"http", "http",
"http-signature-normalization-actix", "http-signature-normalization-actix",
"itertools", "itertools",
"lazy_static",
"lemmy_api_common", "lemmy_api_common",
"lemmy_apub_lib", "lemmy_apub_lib",
"lemmy_db_schema", "lemmy_db_schema",
@ -1878,6 +1875,7 @@ dependencies = [
"lemmy_utils", "lemmy_utils",
"lemmy_websocket", "lemmy_websocket",
"log", "log",
"once_cell",
"percent-encoding", "percent-encoding",
"rand 0.8.4", "rand 0.8.4",
"reqwest", "reqwest",
@ -1908,10 +1906,10 @@ dependencies = [
"http", "http",
"http-signature-normalization-actix", "http-signature-normalization-actix",
"http-signature-normalization-reqwest", "http-signature-normalization-reqwest",
"lazy_static",
"lemmy_apub_lib_derive", "lemmy_apub_lib_derive",
"lemmy_utils", "lemmy_utils",
"log", "log",
"once_cell",
"openssl", "openssl",
"reqwest", "reqwest",
"serde", "serde",
@ -1939,10 +1937,10 @@ dependencies = [
"diesel", "diesel",
"diesel-derive-newtype", "diesel-derive-newtype",
"diesel_migrations", "diesel_migrations",
"lazy_static",
"lemmy_apub_lib", "lemmy_apub_lib",
"lemmy_utils", "lemmy_utils",
"log", "log",
"once_cell",
"regex", "regex",
"serde", "serde",
"serde_json", "serde_json",
@ -1995,7 +1993,6 @@ dependencies = [
"awc", "awc",
"chrono", "chrono",
"diesel", "diesel",
"lazy_static",
"lemmy_api_common", "lemmy_api_common",
"lemmy_apub", "lemmy_apub",
"lemmy_db_schema", "lemmy_db_schema",
@ -2004,6 +2001,7 @@ dependencies = [
"lemmy_utils", "lemmy_utils",
"lemmy_websocket", "lemmy_websocket",
"log", "log",
"once_cell",
"rss", "rss",
"serde", "serde",
"sha2", "sha2",
@ -2066,9 +2064,9 @@ dependencies = [
"http", "http",
"itertools", "itertools",
"jsonwebtoken", "jsonwebtoken",
"lazy_static",
"lettre", "lettre",
"log", "log",
"once_cell",
"openssl", "openssl",
"percent-encoding", "percent-encoding",
"rand 0.8.4", "rand 0.8.4",

View file

@ -35,7 +35,6 @@ log = "0.4.14"
rand = "0.8.4" rand = "0.8.4"
strum = "0.21.0" strum = "0.21.0"
strum_macros = "0.21.1" strum_macros = "0.21.1"
lazy_static = "1.4.0"
url = { version = "2.2.2", features = ["serde"] } url = { version = "2.2.2", features = ["serde"] }
openssl = "0.10.36" openssl = "0.10.36"
http = "0.2.5" http = "0.2.5"

View file

@ -30,7 +30,6 @@ log = "0.4.14"
rand = "0.8.4" rand = "0.8.4"
strum = "0.21.0" strum = "0.21.0"
strum_macros = "0.21.1" strum_macros = "0.21.1"
lazy_static = "1.4.0"
url = { version = "2.2.2", features = ["serde"] } url = { version = "2.2.2", features = ["serde"] }
openssl = "0.10.36" openssl = "0.10.36"
http = "0.2.5" http = "0.2.5"

View file

@ -50,7 +50,7 @@ thiserror = "1.0.29"
background-jobs = "0.9.1" background-jobs = "0.9.1"
reqwest = { version = "0.11.4", features = ["json"] } reqwest = { version = "0.11.4", features = ["json"] }
html2md = "0.2.13" html2md = "0.2.13"
lazy_static = "1.4.0" once_cell = "1.8.0"
[dev-dependencies] [dev-dependencies]
serial_test = "0.5.1" serial_test = "0.5.1"

View file

@ -1,9 +1,9 @@
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
lazy_static! { static CONTEXT: Lazy<Vec<serde_json::Value>> = Lazy::new(|| {
static ref CONTEXT: Vec<serde_json::Value> = serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context")
serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context"); });
}
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub(crate) struct WithContext<T> { pub(crate) struct WithContext<T> {
@ -16,7 +16,7 @@ pub(crate) struct WithContext<T> {
impl<T> WithContext<T> { impl<T> WithContext<T> {
pub(crate) fn new(inner: T) -> WithContext<T> { pub(crate) fn new(inner: T) -> WithContext<T> {
WithContext { WithContext {
context: CONTEXT.clone(), context: (*CONTEXT).clone(),
inner, inner,
} }
} }

View file

@ -17,9 +17,6 @@ pub mod migrations;
pub mod objects; pub mod objects;
pub mod protocol; pub mod protocol;
#[macro_use]
extern crate lazy_static;
/// Checks if the ID is allowed for sending or receiving. /// Checks if the ID is allowed for sending or receiving.
/// ///
/// In particular, it checks for: /// In particular, it checks for:

View file

@ -20,7 +20,7 @@ reqwest = { version = "0.11.4", features = ["json"] }
log = "0.4.14" log = "0.4.14"
base64 = "0.13.0" base64 = "0.13.0"
openssl = "0.10.36" openssl = "0.10.36"
lazy_static = "1.4.0" once_cell = "1.8.0"
http = "0.2.5" http = "0.2.5"
sha2 = "0.9.8" sha2 = "0.9.8"
actix-web = { version = "4.0.0-beta.9", default-features = false } actix-web = { version = "4.0.0-beta.9", default-features = false }

View file

@ -1,6 +1,3 @@
#[macro_use]
extern crate lazy_static;
pub mod activity_queue; pub mod activity_queue;
pub mod data; pub mod data;
pub mod object_id; pub mod object_id;

View file

@ -8,6 +8,7 @@ use lemmy_utils::{
LemmyError, LemmyError,
}; };
use log::info; use log::info;
use once_cell::sync::Lazy;
use reqwest::{Client, StatusCode}; use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ use std::{
@ -21,12 +22,12 @@ use url::Url;
/// fetch through the search). This should be configurable. /// fetch through the search). This should be configurable.
static REQUEST_LIMIT: i32 = 25; static REQUEST_LIMIT: i32 = 25;
lazy_static! { static CLIENT: Lazy<Client> = Lazy::new(|| {
static ref CLIENT: Client = Client::builder() Client::builder()
.user_agent(build_user_agent(&Settings::get())) .user_agent(build_user_agent(&Settings::get()))
.build() .build()
.expect("Couldn't build client"); .expect("Couldn't build client")
} });
/// We store Url on the heap because it is quite large (88 bytes). /// We store Url on the heap because it is quite large (88 bytes).
#[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)]

View file

@ -6,6 +6,7 @@ use http_signature_normalization_actix::Config as ConfigActix;
use http_signature_normalization_reqwest::prelude::{Config, SignExt}; use http_signature_normalization_reqwest::prelude::{Config, SignExt};
use lemmy_utils::LemmyError; use lemmy_utils::LemmyError;
use log::debug; use log::debug;
use once_cell::sync::Lazy;
use openssl::{ use openssl::{
hash::MessageDigest, hash::MessageDigest,
pkey::PKey, pkey::PKey,
@ -17,10 +18,8 @@ use sha2::{Digest, Sha256};
use std::str::FromStr; use std::str::FromStr;
use url::Url; use url::Url;
lazy_static! { static CONFIG2: Lazy<ConfigActix> = Lazy::new(ConfigActix::new);
static ref CONFIG2: ConfigActix = ConfigActix::new(); static HTTP_SIG_CONFIG: Lazy<Config> = Lazy::new(Config::new);
static ref HTTP_SIG_CONFIG: Config = Config::new();
}
/// Creates an HTTP post request to `inbox_url`, with the given `client` and `headers`, and /// Creates an HTTP post request to `inbox_url`, with the given `client` and `headers`, and
/// `activity` as request body. The request is signed with `private_key` and then sent. /// `activity` as request body. The request is signed with `private_key` and then sent.

View file

@ -22,7 +22,7 @@ log = "0.4.14"
url = { version = "2.2.2", features = ["serde"] } url = { version = "2.2.2", features = ["serde"] }
diesel-derive-newtype = "0.1.2" diesel-derive-newtype = "0.1.2"
regex = "1.5.4" regex = "1.5.4"
lazy_static = "1.4.0" once_cell = "1.8.0"
strum = "0.21.0" strum = "0.21.0"
strum_macros = "0.21.1" strum_macros = "0.21.1"
sha2 = "0.9.8" sha2 = "0.9.8"

View file

@ -2,8 +2,6 @@
extern crate diesel; extern crate diesel;
#[macro_use] #[macro_use]
extern crate diesel_derive_newtype; extern crate diesel_derive_newtype;
#[macro_use]
extern crate lazy_static;
// this is used in tests // this is used in tests
#[allow(unused_imports)] #[allow(unused_imports)]
#[macro_use] #[macro_use]
@ -24,6 +22,7 @@ use crate::newtypes::DbUrl;
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use diesel::{Connection, PgConnection}; use diesel::{Connection, PgConnection};
use lemmy_utils::ApiError; use lemmy_utils::ApiError;
use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{env, env::VarError}; use std::{env, env::VarError};
@ -133,11 +132,10 @@ pub fn naive_now() -> NaiveDateTime {
chrono::prelude::Utc::now().naive_utc() chrono::prelude::Utc::now().naive_utc()
} }
lazy_static! { static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
static ref EMAIL_REGEX: Regex =
Regex::new(r"^[a-zA-Z0-9.!#$%&*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$") Regex::new(r"^[a-zA-Z0-9.!#$%&*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
.expect("compile email regex"); .expect("compile email regex")
} });
pub mod functions { pub mod functions {
use diesel::sql_types::*; use diesel::sql_types::*;

View file

@ -32,4 +32,4 @@ serde = { version = "1.0.130", features = ["derive"] }
awc = { version = "3.0.0-beta.8", default-features = false } awc = { version = "3.0.0-beta.8", default-features = false }
url = { version = "2.2.2", features = ["serde"] } url = { version = "2.2.2", features = ["serde"] }
strum = "0.21.0" strum = "0.21.0"
lazy_static = "1.4.0" once_cell = "1.8.0"

View file

@ -18,6 +18,7 @@ use lemmy_db_views::{
use lemmy_db_views_actor::person_mention_view::{PersonMentionQueryBuilder, PersonMentionView}; use lemmy_db_views_actor::person_mention_view::{PersonMentionQueryBuilder, PersonMentionView};
use lemmy_utils::{claims::Claims, utils::markdown_to_html, LemmyError}; use lemmy_utils::{claims::Claims, utils::markdown_to_html, LemmyError};
use lemmy_websocket::LemmyContext; use lemmy_websocket::LemmyContext;
use once_cell::sync::Lazy;
use rss::{ use rss::{
extension::dublincore::DublinCoreExtensionBuilder, extension::dublincore::DublinCoreExtensionBuilder,
ChannelBuilder, ChannelBuilder,
@ -48,16 +49,14 @@ pub fn config(cfg: &mut web::ServiceConfig) {
.route("/feeds/local.xml", web::get().to(get_local_feed)); .route("/feeds/local.xml", web::get().to(get_local_feed));
} }
lazy_static! { static RSS_NAMESPACE: Lazy<HashMap<String, String>> = Lazy::new(|| {
static ref RSS_NAMESPACE: HashMap<String, String> = {
let mut h = HashMap::new(); let mut h = HashMap::new();
h.insert( h.insert(
"dc".to_string(), "dc".to_string(),
rss::extension::dublincore::NAMESPACE.to_string(), rss::extension::dublincore::NAMESPACE.to_string(),
); );
h h
}; });
}
async fn get_all_feed( async fn get_all_feed(
info: web::Query<Params>, info: web::Query<Params>,

View file

@ -1,6 +1,3 @@
#[macro_use]
extern crate lazy_static;
pub mod feeds; pub mod feeds;
pub mod images; pub mod images;
pub mod nodeinfo; pub mod nodeinfo;

View file

@ -24,7 +24,7 @@ serde = { version = "1.0.130", features = ["derive"] }
serde_json = { version = "1.0.68", features = ["preserve_order"] } serde_json = { version = "1.0.68", features = ["preserve_order"] }
thiserror = "1.0.29" thiserror = "1.0.29"
comrak = { version = "0.12.1", default-features = false } comrak = { version = "0.12.1", default-features = false }
lazy_static = "1.4.0" once_cell = "1.8.0"
openssl = "0.10.36" openssl = "0.10.36"
url = { version = "2.2.2", features = ["serde"] } url = { version = "2.2.2", features = ["serde"] }
actix-web = { version = "4.0.0-beta.9", default-features = false, features = ["rustls"] } actix-web = { version = "4.0.0-beta.9", default-features = false, features = ["rustls"] }

View file

@ -1,6 +1,4 @@
#[macro_use] #[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate strum_macros; extern crate strum_macros;
#[macro_use] #[macro_use]
extern crate smart_default; extern crate smart_default;

View file

@ -1,6 +1,7 @@
use crate::{location_info, settings::structs::Settings, LemmyError}; use crate::{location_info, settings::structs::Settings, LemmyError};
use anyhow::{anyhow, Context}; use anyhow::{anyhow, Context};
use deser_hjson::from_str; use deser_hjson::from_str;
use once_cell::sync::Lazy;
use regex::{Regex, RegexBuilder}; use regex::{Regex, RegexBuilder};
use std::{env, fs, io::Error, sync::RwLock}; use std::{env, fs, io::Error, sync::RwLock};
@ -8,15 +9,15 @@ pub mod structs;
static DEFAULT_CONFIG_FILE: &str = "config/config.hjson"; static DEFAULT_CONFIG_FILE: &str = "config/config.hjson";
lazy_static! { static SETTINGS: Lazy<RwLock<Settings>> =
static ref SETTINGS: RwLock<Settings> = Lazy::new(|| RwLock::new(Settings::init().expect("Failed to load settings file")));
RwLock::new(Settings::init().expect("Failed to load settings file")); static WEBFINGER_REGEX: Lazy<Regex> = Lazy::new(|| {
static ref WEBFINGER_REGEX: Regex = Regex::new(&format!( Regex::new(&format!(
"^acct:([a-z0-9_]{{3,}})@{}$", "^acct:([a-z0-9_]{{3,}})@{}$",
Settings::get().hostname Settings::get().hostname
)) ))
.expect("compile webfinger regex"); .expect("compile webfinger regex")
} });
impl Settings { impl Settings {
/// Reads config from configuration file. /// Reads config from configuration file.

View file

@ -2,23 +2,26 @@ use crate::{ApiError, IpAddr};
use actix_web::dev::ConnectionInfo; use actix_web::dev::ConnectionInfo;
use chrono::{DateTime, FixedOffset, NaiveDateTime}; use chrono::{DateTime, FixedOffset, NaiveDateTime};
use itertools::Itertools; use itertools::Itertools;
use once_cell::sync::Lazy;
use rand::{distributions::Alphanumeric, thread_rng, Rng}; use rand::{distributions::Alphanumeric, thread_rng, Rng};
use regex::Regex; use regex::Regex;
use url::Url; use url::Url;
lazy_static! { static MENTIONS_REGEX: Lazy<Regex> = Lazy::new(|| {
static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").expect("compile regex"); Regex::new(r"@(?P<name>[\w.]+)@(?P<domain>[a-zA-Z0-9._:-]+)").expect("compile regex")
});
static ref USERNAME_MATCHES_REGEX: Regex = Regex::new(r"/u/[a-zA-Z][0-9a-zA-Z_]*").expect("compile regex"); static VALID_ACTOR_NAME_REGEX: Lazy<Regex> =
// TODO keep this old one, it didn't work with port well tho Lazy::new(|| Regex::new(r"^[a-zA-Z0-9_]{3,}$").expect("compile regex"));
// static ref MENTIONS_REGEX: Regex = Regex::new(r"@(?P<name>[\w.]+)@(?P<domain>[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)").expect("compile regex"); static VALID_POST_TITLE_REGEX: Lazy<Regex> =
static ref MENTIONS_REGEX: Regex = Regex::new(r"@(?P<name>[\w.]+)@(?P<domain>[a-zA-Z0-9._:-]+)").expect("compile regex"); Lazy::new(|| Regex::new(r".*\S.*").expect("compile regex"));
static ref VALID_ACTOR_NAME_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9_]{3,}$").expect("compile regex"); static VALID_MATRIX_ID_REGEX: Lazy<Regex> = Lazy::new(|| {
static ref VALID_POST_TITLE_REGEX: Regex = Regex::new(r".*\S.*").expect("compile regex"); Regex::new(r"^@[A-Za-z0-9._=-]+:[A-Za-z0-9.-]+\.[A-Za-z]{2,}$").expect("compile regex")
static ref VALID_MATRIX_ID_REGEX: Regex = Regex::new(r"^@[A-Za-z0-9._=-]+:[A-Za-z0-9.-]+\.[A-Za-z]{2,}$").expect("compile regex"); });
// taken from https://en.wikipedia.org/wiki/UTM_parameters // taken from https://en.wikipedia.org/wiki/UTM_parameters
static ref CLEAN_URL_PARAMS_REGEX: Regex = Regex::new(r"^utm_source|utm_medium|utm_campaign|utm_term|utm_content|gclid|gclsrc|dclid|fbclid$").expect("compile regex"); static CLEAN_URL_PARAMS_REGEX: Lazy<Regex> = Lazy::new(|| {
} Regex::new(r"^utm_source|utm_medium|utm_campaign|utm_term|utm_content|gclid|gclsrc|dclid|fbclid$")
.expect("compile regex")
});
pub fn naive_from_unix(time: i64) -> NaiveDateTime { pub fn naive_from_unix(time: i64) -> NaiveDateTime {
NaiveDateTime::from_timestamp(time, 0) NaiveDateTime::from_timestamp(time, 0)