chore: move to once_cell from lazy_static

This commit is contained in:
Zomatree
2023-03-12 23:30:01 +00:00
committed by Paul Makles
parent 4c8ea31d98
commit 0321eff62b
21 changed files with 110 additions and 161 deletions

6
Cargo.lock generated
View File

@@ -2106,9 +2106,9 @@ dependencies = [
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.13.0" version = "1.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18a6dbe30758c9f83eb00cbea4ac95966305f5a7772f3f42ebfc7fc7eddbd8e1" checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3"
[[package]] [[package]]
name = "opaque-debug" name = "opaque-debug"
@@ -2819,7 +2819,6 @@ dependencies = [
"env_logger", "env_logger",
"futures", "futures",
"impl_ops", "impl_ops",
"lazy_static",
"lettre", "lettre",
"linkify 0.6.0", "linkify 0.6.0",
"log", "log",
@@ -2866,7 +2865,6 @@ dependencies = [
"impl_ops", "impl_ops",
"indexmap", "indexmap",
"iso8601-timestamp", "iso8601-timestamp",
"lazy_static",
"linkify 0.8.1", "linkify 0.8.1",
"log", "log",
"lru", "lru",

View File

@@ -15,9 +15,8 @@ log = "0.4.11"
dotenv = "0.15.0" dotenv = "0.15.0"
dashmap = "5.2.0" dashmap = "5.2.0"
linkify = "0.6.0" linkify = "0.6.0"
once_cell = "1.4.1" once_cell = "1.17.1"
env_logger = "0.7.1" env_logger = "0.7.1"
lazy_static = "1.4.0"
# Lang. Utilities # Lang. Utilities
regex = "1" regex = "1"

View File

@@ -4,8 +4,6 @@ extern crate rocket;
extern crate revolt_rocket_okapi; extern crate revolt_rocket_okapi;
#[macro_use] #[macro_use]
extern crate serde_json; extern crate serde_json;
#[macro_use]
extern crate lazy_static;
pub mod routes; pub mod routes;
pub mod util; pub mod util;

View File

@@ -15,6 +15,7 @@ use rocket::serde::json::Json;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use ulid::Ulid; use ulid::Ulid;
use validator::Validate; use validator::Validate;
use once_cell::sync::Lazy;
#[derive(Validate, Serialize, Deserialize, JsonSchema)] #[derive(Validate, Serialize, Deserialize, JsonSchema)]
pub struct DataMessageSend { pub struct DataMessageSend {
@@ -44,10 +45,7 @@ pub struct DataMessageSend {
interactions: Option<Interactions>, interactions: Option<Interactions>,
} }
lazy_static! { static RE_MENTION: Lazy<Regex> = Lazy::new(|| Regex::new(r"<@([0-9A-HJKMNP-TV-Z]{26})>").unwrap());
// ignoring I L O and U is intentional
static ref RE_MENTION: Regex = Regex::new(r"<@([0-9A-HJKMNP-TV-Z]{26})>").unwrap();
}
/// # Send Message /// # Send Message
/// ///

View File

@@ -67,8 +67,7 @@ impl_ops = "0.1.1"
num_enum = "0.5.6" num_enum = "0.5.6"
reqwest = "0.11.10" reqwest = "0.11.10"
bitfield = "0.13.2" bitfield = "0.13.2"
once_cell = "1.13.0" once_cell = "1.17.1"
lazy_static = "1.4.0"
async-lock = "2.6.0" async-lock = "2.6.0"
lru = { version = "0.7.6", optional = true } lru = { version = "0.7.6", optional = true }

View File

@@ -5,13 +5,11 @@ use crate::{
Database, Error, Result, Database, Error, Result,
}; };
lazy_static! { static ALPHABET: [char; 54] = [
static ref ALPHABET: [char; 54] = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z' 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'
]; ];
}
impl Invite { impl Invite {
/// Get the invite code for this invite /// Get the invite code for this invite
@@ -30,7 +28,7 @@ impl Invite {
/// Create a new invite from given information /// Create a new invite from given information
pub async fn create(db: &Database, creator: &User, target: &Channel) -> Result<Invite> { pub async fn create(db: &Database, creator: &User, target: &Channel) -> Result<Invite> {
let code = nanoid!(8, &*ALPHABET); let code = nanoid!(8, &ALPHABET);
let invite = match &target { let invite = match &target {
Channel::Group { id, .. } => Ok(Invite::Group { Channel::Group { id, .. } => Ok(Invite::Group {
code, code,

View File

@@ -1,4 +1,5 @@
use std::{collections::HashSet, str::FromStr}; use std::{collections::HashSet, str::FromStr};
use once_cell::sync::Lazy;
use ulid::Ulid; use ulid::Ulid;
@@ -8,13 +9,10 @@ use crate::{
Database, Result, Database, Result,
}; };
lazy_static! { static PERMISSIBLE_EMOJIS: Lazy<HashSet<String>> = Lazy::new(|| include_str!(crate::asset!("emojis.txt"))
/// Permissible emojis
static ref PERMISSIBLE_EMOJIS: HashSet<String> = include_str!(crate::asset!("emojis.txt"))
.split('\n') .split('\n')
.map(|x| x.into()) .map(|x| x.into())
.collect(); .collect());
}
impl Emoji { impl Emoji {
/// Get parent id /// Get parent id

View File

@@ -1,4 +1,4 @@
use std::time::Duration; use std::{time::Duration, ops::BitXor};
use bson::{Bson, DateTime}; use bson::{Bson, DateTime};
use futures::StreamExt; use futures::StreamExt;
@@ -503,13 +503,8 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
update.insert( update.insert(
"default_permissions", "default_permissions",
(*DEFAULT_PERMISSION_SERVER
// Remove Send Message permission if it wasn't originally granted // Remove Send Message permission if it wasn't originally granted
^ (if has_send { DEFAULT_PERMISSION_SERVER.bitxor(if has_send { 0 } else { Permission::SendMessage as u64}) as i64,
0
} else {
Permission::SendMessage as u64
})) as i64,
); );
if let Some(Bson::Document(mut roles)) = document.remove("roles") { if let Some(Bson::Document(mut roles)) = document.remove("roles") {

View File

@@ -1,6 +1,7 @@
use bson::Document; use bson::Document;
use futures::StreamExt; use futures::StreamExt;
use mongodb::options::{Collation, CollationStrength, FindOneOptions, FindOptions}; use mongodb::options::{Collation, CollationStrength, FindOneOptions, FindOptions};
use once_cell::sync::Lazy;
use crate::models::user::{FieldsUser, PartialUser, RelationshipStatus, User}; use crate::models::user::{FieldsUser, PartialUser, RelationshipStatus, User};
use crate::r#impl::mongo::IntoDocumentPath; use crate::r#impl::mongo::IntoDocumentPath;
@@ -8,16 +9,14 @@ use crate::{AbstractUser, Error, Result};
use super::super::MongoDb; use super::super::MongoDb;
lazy_static! { static FIND_USERNAME_OPTIONS: Lazy<FindOneOptions> = Lazy::new(|| FindOneOptions::builder()
static ref FIND_USERNAME_OPTIONS: FindOneOptions = FindOneOptions::builder()
.collation( .collation(
Collation::builder() Collation::builder()
.locale("en") .locale("en")
.strength(CollationStrength::Secondary) .strength(CollationStrength::Secondary)
.build() .build()
) )
.build(); .build());
}
static COL: &str = "users"; static COL: &str = "users";

View File

@@ -11,8 +11,6 @@ extern crate impl_ops;
#[macro_use] #[macro_use]
extern crate optional_struct; extern crate optional_struct;
#[macro_use] #[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate bitfield; extern crate bitfield;
#[macro_use] #[macro_use]
extern crate bson; extern crate bson;

View File

@@ -1,6 +1,7 @@
use num_enum::TryFromPrimitive; use num_enum::TryFromPrimitive;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::ops; use once_cell::sync::Lazy;
use std::ops::{self, Add};
/// Permission value on Revolt /// Permission value on Revolt
/// ///
@@ -97,24 +98,18 @@ pub enum Permission {
impl_op_ex!(+ |a: &Permission, b: &Permission| -> u64 { *a as u64 | *b as u64 }); impl_op_ex!(+ |a: &Permission, b: &Permission| -> u64 { *a as u64 | *b as u64 });
impl_op_ex_commutative!(+ |a: &u64, b: &Permission| -> u64 { *a | *b as u64 }); impl_op_ex_commutative!(+ |a: &u64, b: &Permission| -> u64 { *a | *b as u64 });
lazy_static! { pub static ALLOW_IN_TIMEOUT: Lazy<u64> = Lazy::new(|| Permission::ViewChannel + Permission::ReadMessageHistory);
pub static ref ALLOW_IN_TIMEOUT: u64 = Permission::ViewChannel + Permission::ReadMessageHistory; pub static DEFAULT_PERMISSION_VIEW_ONLY: Lazy<u64> = Lazy::new(|| Permission::ViewChannel + Permission::ReadMessageHistory);
pub static ref DEFAULT_PERMISSION_VIEW_ONLY: u64 = pub static DEFAULT_PERMISSION: Lazy<u64> = Lazy::new(|| DEFAULT_PERMISSION_VIEW_ONLY.add(
Permission::ViewChannel + Permission::ReadMessageHistory; Permission::SendMessage
pub static ref DEFAULT_PERMISSION: u64 = *DEFAULT_PERMISSION_VIEW_ONLY
+ Permission::SendMessage
+ Permission::InviteOthers + Permission::InviteOthers
+ Permission::SendEmbeds + Permission::SendEmbeds
+ Permission::UploadFiles + Permission::UploadFiles
+ Permission::Connect + Permission::Connect
+ Permission::Speak; + Permission::Speak));
pub static ref DEFAULT_PERMISSION_SAVED_MESSAGES: u64 = Permission::GrantAllSafe as u64; pub static DEFAULT_PERMISSION_SAVED_MESSAGES: u64 = Permission::GrantAllSafe as u64;
pub static ref DEFAULT_PERMISSION_DIRECT_MESSAGE: u64 = *DEFAULT_PERMISSION pub static DEFAULT_PERMISSION_DIRECT_MESSAGE: Lazy<u64> = Lazy::new(|| DEFAULT_PERMISSION.add(Permission::ManageChannel + Permission::React));
+ Permission::ManageChannel pub static DEFAULT_PERMISSION_SERVER: Lazy<u64> = Lazy::new(|| DEFAULT_PERMISSION.add(Permission::React + Permission::ChangeNickname + Permission::ChangeAvatar));
+ Permission::React;
pub static ref DEFAULT_PERMISSION_SERVER: u64 =
*DEFAULT_PERMISSION + Permission::React + Permission::ChangeNickname + Permission::ChangeAvatar;
}
bitfield! { bitfield! {
#[derive(Default)] #[derive(Default)]

View File

@@ -113,7 +113,7 @@ async fn calculate_channel_permission(
let value: PermissionValue = match channel { let value: PermissionValue = match channel {
Channel::SavedMessages { user, .. } => { Channel::SavedMessages { user, .. } => {
if user == &data.perspective.id { if user == &data.perspective.id {
(*DEFAULT_PERMISSION_SAVED_MESSAGES).into() DEFAULT_PERMISSION_SAVED_MESSAGES.into()
} else { } else {
0_u64.into() 0_u64.into()
} }

View File

@@ -1,14 +1,14 @@
use std::env; use std::env;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use once_cell::sync::Lazy;
lazy_static! { pub static REGION_ID: Lazy<u16> = Lazy::new(|| env::var("REGION_ID")
pub static ref REGION_ID: u16 = env::var("REGION_ID")
.unwrap_or_else(|_| "0".to_string()) .unwrap_or_else(|_| "0".to_string())
.parse() .parse()
.unwrap(); .unwrap());
pub static ref REGION_KEY: String = format!("region{}", &*REGION_ID);
} pub static REGION_KEY: Lazy<String> = Lazy::new(|| format!("region{}", &*REGION_ID));
/// Compact presence information for a user /// Compact presence information for a user
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]

View File

@@ -4,6 +4,7 @@ use crate::Database;
use deadqueue::limited::Queue; use deadqueue::limited::Queue;
use mongodb::bson::doc; use mongodb::bson::doc;
use std::{collections::HashMap, time::Duration}; use std::{collections::HashMap, time::Duration};
use once_cell::sync::Lazy;
use super::DelayedTask; use super::DelayedTask;
@@ -38,9 +39,7 @@ struct Task {
event: AckEvent, event: AckEvent,
} }
lazy_static! { static Q: Lazy<Queue<Data>> = Lazy::new(|| Queue::new(10_000));
static ref Q: Queue<Data> = Queue::new(10_000);
}
/// Queue a new task for a worker /// Queue a new task for a worker
pub async fn queue(channel: String, user: String, event: AckEvent) { pub async fn queue(channel: String, user: String, event: AckEvent) {

View File

@@ -4,6 +4,7 @@ use crate::{models::channel::PartialChannel, Database};
use deadqueue::limited::Queue; use deadqueue::limited::Queue;
use mongodb::bson::doc; use mongodb::bson::doc;
use std::{collections::HashMap, time::Duration}; use std::{collections::HashMap, time::Duration};
use once_cell::sync::Lazy;
use super::DelayedTask; use super::DelayedTask;
@@ -26,9 +27,7 @@ struct Task {
is_dm: bool, is_dm: bool,
} }
lazy_static! { static Q: Lazy<Queue<Data>> = Lazy::new(|| Queue::new(10_000));
static ref Q: Queue<Data> = Queue::new(10_000);
}
/// Queue a new task for a worker /// Queue a new task for a worker
pub async fn queue(channel: String, id: String, is_dm: bool) { pub async fn queue(channel: String, id: String, is_dm: bool) {

View File

@@ -9,6 +9,7 @@ use async_lock::Semaphore;
use async_std::task::spawn; use async_std::task::spawn;
use deadqueue::limited::Queue; use deadqueue::limited::Queue;
use std::sync::Arc; use std::sync::Arc;
use once_cell::sync::Lazy;
/// Task information /// Task information
#[derive(Debug)] #[derive(Debug)]
@@ -21,9 +22,8 @@ struct EmbedTask {
content: String, content: String,
} }
lazy_static! { static Q: Lazy<Queue<EmbedTask>> = Lazy::new(|| Queue::new(10_000));
static ref Q: Queue<EmbedTask> = Queue::new(10_000);
}
/// Queue a new task for a worker /// Queue a new task for a worker
pub async fn queue(channel: String, id: String, content: String) { pub async fn queue(channel: String, id: String, content: String) {

View File

@@ -3,6 +3,7 @@ use crate::util::variables::delta::VAPID_PRIVATE_KEY;
use authifier::Database; use authifier::Database;
use deadqueue::limited::Queue; use deadqueue::limited::Queue;
use once_cell::sync::Lazy;
use web_push::{ use web_push::{
ContentEncoding, SubscriptionInfo, SubscriptionKeys, VapidSignatureBuilder, WebPushClient, ContentEncoding, SubscriptionInfo, SubscriptionKeys, VapidSignatureBuilder, WebPushClient,
WebPushMessageBuilder, WebPushMessageBuilder,
@@ -17,9 +18,8 @@ struct PushTask {
payload: String, payload: String,
} }
lazy_static! { static Q: Lazy<Queue<PushTask>> = Lazy::new(|| Queue::new(10_000));
static ref Q: Queue<PushTask> = Queue::new(10_000);
}
/// Queue a new task for a worker /// Queue a new task for a worker
pub async fn queue(recipients: Vec<String>, payload: String) { pub async fn queue(recipients: Vec<String>, payload: String) {

View File

@@ -5,6 +5,7 @@ use linkify::{LinkFinder, LinkKind};
use regex::Regex; use regex::Regex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{collections::HashSet, sync::Arc}; use std::{collections::HashSet, sync::Arc};
use once_cell::sync::Lazy;
use crate::{models::attachment::File, Error, Result}; use crate::{models::attachment::File, Error, Result};
@@ -175,6 +176,9 @@ pub enum Embed {
None, None,
} }
static RE_CODE: Lazy<Regex> = Lazy::new(|| Regex::new("```(?:.|\n)+?```|`(?:.|\n)+?`").unwrap());
static RE_IGNORED: Lazy<Regex> = Lazy::new(|| Regex::new("(<http.+>)").unwrap());
impl Embed { impl Embed {
/// Generate embeds from given content /// Generate embeds from given content
pub async fn generate( pub async fn generate(
@@ -183,10 +187,7 @@ impl Embed {
max_embeds: usize, max_embeds: usize,
semaphore: Arc<Semaphore>, semaphore: Arc<Semaphore>,
) -> Result<Vec<Embed>> { ) -> Result<Vec<Embed>> {
lazy_static! {
static ref RE_CODE: Regex = Regex::new("```(?:.|\n)+?```|`(?:.|\n)+?`").unwrap();
static ref RE_IGNORED: Regex = Regex::new("(<http.+>)").unwrap();
}
// Ignore code blocks. // Ignore code blocks.
let content = RE_CODE.replace_all(&content, ""); let content = RE_CODE.replace_all(&content, "");

View File

@@ -1,73 +1,50 @@
use std::env; use std::env;
use once_cell::sync::Lazy;
lazy_static! {
// Application Settings // Application Settings
pub static ref PUBLIC_URL: String = pub static PUBLIC_URL: Lazy<String> = Lazy::new(|| env::var("REVOLT_PUBLIC_URL").expect("Missing REVOLT_PUBLIC_URL environment variable."));
env::var("REVOLT_PUBLIC_URL").expect("Missing REVOLT_PUBLIC_URL environment variable."); pub static APP_URL: Lazy<String> = Lazy::new(|| env::var("REVOLT_APP_URL").expect("Missing REVOLT_APP_URL environment variable."));
pub static ref APP_URL: String = pub static EXTERNAL_WS_URL: Lazy<String> = Lazy::new(|| env::var("REVOLT_EXTERNAL_WS_URL").expect("Missing REVOLT_EXTERNAL_WS_URL environment variable."));
env::var("REVOLT_APP_URL").expect("Missing REVOLT_APP_URL environment variable.");
pub static ref EXTERNAL_WS_URL: String =
env::var("REVOLT_EXTERNAL_WS_URL").expect("Missing REVOLT_EXTERNAL_WS_URL environment variable.");
pub static ref AUTUMN_URL: String = pub static AUTUMN_URL: Lazy<String> = Lazy::new(|| env::var("AUTUMN_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string()));
env::var("AUTUMN_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string()); pub static JANUARY_URL: Lazy<String> = Lazy::new(|| env::var("JANUARY_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string()));
pub static ref JANUARY_URL: String = pub static JANUARY_CONCURRENT_CONNECTIONS: Lazy<usize> = Lazy::new(|| env::var("JANUARY_CONCURRENT_CONNECTIONS").map_or(50, |v| v.parse().unwrap()));
env::var("JANUARY_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string()); pub static VOSO_URL: Lazy<String> = Lazy::new(|| env::var("VOSO_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string()));
pub static ref JANUARY_CONCURRENT_CONNECTIONS: usize = pub static VOSO_WS_HOST: Lazy<String> = Lazy::new(|| env::var("VOSO_WS_HOST").unwrap_or_else(|_| "wss://example.com".to_string()));
env::var("JANUARY_CONCURRENT_CONNECTIONS").map_or(50, |v| v.parse().unwrap()); pub static VOSO_MANAGE_TOKEN: Lazy<String> = Lazy::new(|| env::var("VOSO_MANAGE_TOKEN").unwrap_or_else(|_| "0".to_string()));
pub static ref VOSO_URL: String =
env::var("VOSO_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string());
pub static ref VOSO_WS_HOST: String =
env::var("VOSO_WS_HOST").unwrap_or_else(|_| "wss://example.com".to_string());
pub static ref VOSO_MANAGE_TOKEN: String =
env::var("VOSO_MANAGE_TOKEN").unwrap_or_else(|_| "0".to_string());
pub static ref HCAPTCHA_KEY: String = pub static HCAPTCHA_KEY: Lazy<String> = Lazy::new(|| env::var("REVOLT_HCAPTCHA_KEY").unwrap_or_else(|_| "0x0000000000000000000000000000000000000000".to_string()));
env::var("REVOLT_HCAPTCHA_KEY").unwrap_or_else(|_| "0x0000000000000000000000000000000000000000".to_string()); pub static HCAPTCHA_SITEKEY: Lazy<String> = Lazy::new(|| env::var("REVOLT_HCAPTCHA_SITEKEY").unwrap_or_else(|_| "10000000-ffff-ffff-ffff-000000000001".to_string()));
pub static ref HCAPTCHA_SITEKEY: String = pub static VAPID_PRIVATE_KEY: Lazy<String> = Lazy::new(|| env::var("REVOLT_VAPID_PRIVATE_KEY").expect("Missing REVOLT_VAPID_PRIVATE_KEY environment variable."));
env::var("REVOLT_HCAPTCHA_SITEKEY").unwrap_or_else(|_| "10000000-ffff-ffff-ffff-000000000001".to_string()); pub static VAPID_PUBLIC_KEY: Lazy<String> = Lazy::new(|| env::var("REVOLT_VAPID_PUBLIC_KEY").expect("Missing REVOLT_VAPID_PUBLIC_KEY environment variable."));
pub static ref VAPID_PRIVATE_KEY: String = pub static AUTHIFIER_SHIELD_KEY: Lazy<Option<String>> = Lazy::new(|| env::var("REVOLT_AUTHIFIER_SHIELD_KEY").ok());
env::var("REVOLT_VAPID_PRIVATE_KEY").expect("Missing REVOLT_VAPID_PRIVATE_KEY environment variable.");
pub static ref VAPID_PUBLIC_KEY: String =
env::var("REVOLT_VAPID_PUBLIC_KEY").expect("Missing REVOLT_VAPID_PUBLIC_KEY environment variable.");
pub static ref AUTHIFIER_SHIELD_KEY: Option<String> =
env::var("REVOLT_AUTHIFIER_SHIELD_KEY").ok();
// Application Flags // Application Flags
pub static ref INVITE_ONLY: bool = env::var("REVOLT_INVITE_ONLY").map_or(false, |v| v == "1"); pub static INVITE_ONLY: Lazy<bool> = Lazy::new(|| env::var("REVOLT_INVITE_ONLY").map_or(false, |v| v == "1"));
pub static ref USE_EMAIL: bool = env::var("REVOLT_USE_EMAIL_VERIFICATION").map_or( pub static USE_EMAIL: Lazy<bool> = Lazy::new(|| env::var("REVOLT_USE_EMAIL_VERIFICATION").map_or(
env::var("REVOLT_SMTP_HOST").is_ok() env::var("REVOLT_SMTP_HOST").is_ok()
&& env::var("REVOLT_SMTP_USERNAME").is_ok() && env::var("REVOLT_SMTP_USERNAME").is_ok()
&& env::var("REVOLT_SMTP_PASSWORD").is_ok() && env::var("REVOLT_SMTP_PASSWORD").is_ok()
&& env::var("REVOLT_SMTP_FROM").is_ok(), && env::var("REVOLT_SMTP_FROM").is_ok(),
|v| v == *"1" |v| v == *"1"
); ));
pub static ref USE_HCAPTCHA: bool = env::var("REVOLT_HCAPTCHA_KEY").is_ok(); pub static USE_HCAPTCHA: Lazy<bool> = Lazy::new(|| env::var("REVOLT_HCAPTCHA_KEY").is_ok());
pub static ref USE_AUTUMN: bool = env::var("AUTUMN_PUBLIC_URL").is_ok(); pub static USE_AUTUMN: Lazy<bool> = Lazy::new(|| env::var("AUTUMN_PUBLIC_URL").is_ok());
pub static ref USE_JANUARY: bool = env::var("JANUARY_PUBLIC_URL").is_ok(); pub static USE_JANUARY: Lazy<bool> = Lazy::new(|| env::var("JANUARY_PUBLIC_URL").is_ok());
pub static ref USE_VOSO: bool = env::var("VOSO_PUBLIC_URL").is_ok() && env::var("VOSO_MANAGE_TOKEN").is_ok(); pub static USE_VOSO: Lazy<bool> = Lazy::new(|| env::var("VOSO_PUBLIC_URL").is_ok() && env::var("VOSO_MANAGE_TOKEN").is_ok());
// SMTP Settings // SMTP Settings
pub static ref SMTP_HOST: String = pub static SMTP_HOST: Lazy<String> = Lazy::new(|| env::var("REVOLT_SMTP_HOST").unwrap_or_else(|_| "".to_string()));
env::var("REVOLT_SMTP_HOST").unwrap_or_else(|_| "".to_string()); pub static SMTP_USERNAME: Lazy<String> = Lazy::new(|| env::var("REVOLT_SMTP_USERNAME").unwrap_or_else(|_| "".to_string()));
pub static ref SMTP_USERNAME: String = pub static SMTP_PASSWORD: Lazy<String> = Lazy::new(|| env::var("REVOLT_SMTP_PASSWORD").unwrap_or_else(|_| "".to_string()));
env::var("REVOLT_SMTP_USERNAME").unwrap_or_else(|_| "".to_string()); pub static SMTP_FROM: Lazy<String> = Lazy::new(|| env::var("REVOLT_SMTP_FROM").unwrap_or_else(|_| "".to_string()));
pub static ref SMTP_PASSWORD: String =
env::var("REVOLT_SMTP_PASSWORD").unwrap_or_else(|_| "".to_string());
pub static ref SMTP_FROM: String = env::var("REVOLT_SMTP_FROM").unwrap_or_else(|_| "".to_string());
// Application Logic Settings // Application Logic Settings
pub static ref MAX_GROUP_SIZE: usize = pub static MAX_GROUP_SIZE: Lazy<usize> = Lazy::new(|| env::var("REVOLT_MAX_GROUP_SIZE").unwrap_or_else(|_| "50".to_string()).parse().unwrap());
env::var("REVOLT_MAX_GROUP_SIZE").unwrap_or_else(|_| "50".to_string()).parse().unwrap(); pub static MAX_BOT_COUNT: Lazy<usize> = Lazy::new(|| env::var("REVOLT_MAX_BOT_COUNT").unwrap_or_else(|_| "5".to_string()).parse().unwrap());
pub static ref MAX_BOT_COUNT: usize = pub static MAX_EMBED_COUNT: Lazy<usize> = Lazy::new(|| env::var("REVOLT_MAX_EMBED_COUNT").unwrap_or_else(|_| "5".to_string()).parse().unwrap());
env::var("REVOLT_MAX_BOT_COUNT").unwrap_or_else(|_| "5".to_string()).parse().unwrap(); pub static MAX_SERVER_COUNT: Lazy<usize> = Lazy::new(|| env::var("REVOLT_MAX_SERVER_COUNT").unwrap_or_else(|_| "100".to_string()).parse().unwrap());
pub static ref MAX_EMBED_COUNT: usize = pub static EARLY_ADOPTER_BADGE: Lazy<i64> = Lazy::new(|| env::var("REVOLT_EARLY_ADOPTER_BADGE").unwrap_or_else(|_| "0".to_string()).parse().unwrap());
env::var("REVOLT_MAX_EMBED_COUNT").unwrap_or_else(|_| "5".to_string()).parse().unwrap();
pub static ref MAX_SERVER_COUNT: usize =
env::var("REVOLT_MAX_SERVER_COUNT").unwrap_or_else(|_| "100".to_string()).parse().unwrap();
pub static ref EARLY_ADOPTER_BADGE: i64 =
env::var("REVOLT_EARLY_ADOPTER_BADGE").unwrap_or_else(|_| "0".to_string()).parse().unwrap();
}
pub fn preflight_checks() { pub fn preflight_checks() {
format!("url = {}", *APP_URL); format!("url = {}", *APP_URL);

View File

@@ -9,6 +9,7 @@ use rocket::request::{FromRequest, Outcome};
use schemars::schema::{InstanceType, SchemaObject, SingleOrVec}; use schemars::schema::{InstanceType, SchemaObject, SingleOrVec};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use validator::Validate; use validator::Validate;
use once_cell::sync::Lazy;
#[derive(Validate, Serialize, Deserialize)] #[derive(Validate, Serialize, Deserialize)]
pub struct IdempotencyKey { pub struct IdempotencyKey {
@@ -16,9 +17,7 @@ pub struct IdempotencyKey {
key: String, key: String,
} }
lazy_static! { static TOKEN_CACHE: Lazy<Mutex<lru::LruCache<String, ()>>> = Lazy::new(|| Mutex::new(lru::LruCache::new(100)));
static ref TOKEN_CACHE: Mutex<lru::LruCache<String, ()>> = Mutex::new(lru::LruCache::new(100));
}
impl IdempotencyKey { impl IdempotencyKey {
// Backwards compatibility. // Backwards compatibility.

View File

@@ -22,6 +22,7 @@ use revolt_rocket_okapi::request::{OpenApiFromRequest, RequestHeaderInput};
use serde::Serialize; use serde::Serialize;
use dashmap::DashMap; use dashmap::DashMap;
use once_cell::sync::Lazy;
/// Ratelimit Bucket /// Ratelimit Bucket
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
@@ -30,9 +31,7 @@ struct Entry {
reset: u128, reset: u128,
} }
lazy_static! { static MAP: Lazy<DashMap<u64, Entry>> = Lazy::new(|| DashMap::new());
static ref MAP: DashMap<u64, Entry> = DashMap::new();
}
/// Get the current time from Unix Epoch as a Duration /// Get the current time from Unix Epoch as a Duration
fn now() -> Duration { fn now() -> Duration {