Skip to content

Commit

Permalink
Migrate lazy_static to once_cell, less macro magic and slightly faster
Browse files Browse the repository at this point in the history
  • Loading branch information
dani-garcia committed Mar 9, 2020
1 parent b6612e9 commit 70f3ab8
Show file tree
Hide file tree
Showing 8 changed files with 59 additions and 84 deletions.
56 changes: 16 additions & 40 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ yubico = { version = "0.7.1", features = ["online-tokio"], default-features = fa
# A `dotenv` implementation for Rust
dotenv = { version = "0.15.0", default-features = false }

# Lazy static macro
lazy_static = "1.4.0"
# Lazy initialization
once_cell = "1.3.1"

# More derives
derive_more = "0.99.3"
Expand Down
6 changes: 3 additions & 3 deletions src/api/admin.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use once_cell::sync::Lazy;
use serde_json::Value;
use std::process::Command;

Expand Down Expand Up @@ -38,9 +39,8 @@ pub fn routes() -> Vec<Route> {
]
}

lazy_static! {
static ref CAN_BACKUP: bool = cfg!(feature = "sqlite") && Command::new("sqlite3").arg("-version").status().is_ok();
}
static CAN_BACKUP: Lazy<bool> =
Lazy::new(|| cfg!(feature = "sqlite") && Command::new("sqlite3").arg("-version").status().is_ok());

#[get("/")]
fn admin_disabled() -> &'static str {
Expand Down
7 changes: 3 additions & 4 deletions src/api/core/two_factor/u2f.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use once_cell::sync::Lazy;
use rocket::Route;
use rocket_contrib::json::Json;
use serde_json;
Expand All @@ -18,10 +19,8 @@ use crate::CONFIG;

const U2F_VERSION: &str = "U2F_V2";

lazy_static! {
static ref APP_ID: String = format!("{}/app-id.json", &CONFIG.domain());
static ref U2F: U2f = U2f::new(APP_ID.clone());
}
static APP_ID: Lazy<String> = Lazy::new(|| format!("{}/app-id.json", &CONFIG.domain()));
static U2F: Lazy<U2f> = Lazy::new(|| U2f::new(APP_ID.clone()));

pub fn routes() -> Vec<Route> {
routes![
Expand Down
9 changes: 5 additions & 4 deletions src/api/icons.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use once_cell::sync::Lazy;
use std::fs::{create_dir_all, remove_file, symlink_metadata, File};
use std::io::prelude::*;
use std::net::ToSocketAddrs;
Expand Down Expand Up @@ -26,16 +27,16 @@ const FALLBACK_ICON: &[u8; 344] = include_bytes!("../static/fallback-icon.png");

const ALLOWED_CHARS: &str = "_-.";

lazy_static! {
static CLIENT: Lazy<Client> = Lazy::new(|| {
// Reuse the client between requests
static ref CLIENT: Client = Client::builder()
Client::builder()
.use_sys_proxy()
.gzip(true)
.timeout(Duration::from_secs(CONFIG.icon_download_timeout()))
.default_headers(_header_map())
.build()
.unwrap();
}
.unwrap()
});

fn is_valid_domain(domain: &str) -> bool {
// Don't allow empty or too big domains or path traversal
Expand Down
33 changes: 16 additions & 17 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//
use crate::util::read_file;
use chrono::{Duration, Utc};
use once_cell::sync::Lazy;

use jsonwebtoken::{self, Algorithm, Header};
use serde::de::DeserializeOwned;
Expand All @@ -13,23 +14,21 @@ use crate::CONFIG;

const JWT_ALGORITHM: Algorithm = Algorithm::RS256;

lazy_static! {
pub static ref DEFAULT_VALIDITY: Duration = Duration::hours(2);
static ref JWT_HEADER: Header = Header::new(JWT_ALGORITHM);
pub static ref JWT_LOGIN_ISSUER: String = format!("{}|login", CONFIG.domain_origin());
pub static ref JWT_INVITE_ISSUER: String = format!("{}|invite", CONFIG.domain_origin());
pub static ref JWT_DELETE_ISSUER: String = format!("{}|delete", CONFIG.domain_origin());
pub static ref JWT_VERIFYEMAIL_ISSUER: String = format!("{}|verifyemail", CONFIG.domain_origin());
pub static ref JWT_ADMIN_ISSUER: String = format!("{}|admin", CONFIG.domain_origin());
static ref PRIVATE_RSA_KEY: Vec<u8> = match read_file(&CONFIG.private_rsa_key()) {
Ok(key) => key,
Err(e) => panic!("Error loading private RSA Key.\n Error: {}", e),
};
static ref PUBLIC_RSA_KEY: Vec<u8> = match read_file(&CONFIG.public_rsa_key()) {
Ok(key) => key,
Err(e) => panic!("Error loading public RSA Key.\n Error: {}", e),
};
}
pub static DEFAULT_VALIDITY: Lazy<Duration> = Lazy::new(|| Duration::hours(2));
static JWT_HEADER: Lazy<Header> = Lazy::new(|| Header::new(JWT_ALGORITHM));
pub static JWT_LOGIN_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|login", CONFIG.domain_origin()));
static JWT_INVITE_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|invite", CONFIG.domain_origin()));
static JWT_DELETE_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|delete", CONFIG.domain_origin()));
static JWT_VERIFYEMAIL_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|verifyemail", CONFIG.domain_origin()));
static JWT_ADMIN_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|admin", CONFIG.domain_origin()));
static PRIVATE_RSA_KEY: Lazy<Vec<u8>> = Lazy::new(|| match read_file(&CONFIG.private_rsa_key()) {
Ok(key) => key,
Err(e) => panic!("Error loading private RSA Key.\n Error: {}", e),
});
static PUBLIC_RSA_KEY: Lazy<Vec<u8>> = Lazy::new(|| match read_file(&CONFIG.public_rsa_key()) {
Ok(key) => key,
Err(e) => panic!("Error loading public RSA Key.\n Error: {}", e),
});

pub fn encode_jwt<T: Serialize>(claims: &T) -> String {
match jsonwebtoken::encode(&JWT_HEADER, claims, &PRIVATE_RSA_KEY) {
Expand Down
26 changes: 14 additions & 12 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use once_cell::sync::Lazy;
use std::process::exit;
use std::sync::RwLock;

Expand All @@ -6,16 +7,17 @@ use reqwest::Url;
use crate::error::Error;
use crate::util::{get_env, get_env_bool};

lazy_static! {
pub static ref CONFIG: Config = Config::load().unwrap_or_else(|e| {
static CONFIG_FILE: Lazy<String> = Lazy::new(|| {
let data_folder = get_env("DATA_FOLDER").unwrap_or_else(|| String::from("data"));
get_env("CONFIG_FILE").unwrap_or_else(|| format!("{}/config.json", data_folder))
});

pub static CONFIG: Lazy<Config> = Lazy::new(|| {
Config::load().unwrap_or_else(|e| {
println!("Error loading config:\n\t{:?}\n", e);
exit(12)
});
pub static ref CONFIG_FILE: String = {
let data_folder = get_env("DATA_FOLDER").unwrap_or_else(|| String::from("data"));
get_env("CONFIG_FILE").unwrap_or_else(|| format!("{}/config.json", data_folder))
};
}
})
});

pub type Pass = String;

Expand Down Expand Up @@ -54,7 +56,7 @@ macro_rules! make_config {
$($(
builder.$name = make_config! { @getenv &stringify!($name).to_uppercase(), $ty };
)+)+

builder
}

Expand Down Expand Up @@ -420,8 +422,8 @@ fn validate_config(cfg: &ConfigItems) -> Result<(), Error> {
if cfg!(feature = "postgresql") && !db_url.starts_with("postgresql:") {
err!("`DATABASE_URL` should start with postgresql: when using the PostgreSQL server")
}
let dom = cfg.domain.to_lowercase();

let dom = cfg.domain.to_lowercase();
if !dom.starts_with("http://") && !dom.starts_with("https://") {
err!("DOMAIN variable needs to contain the protocol (http, https). Use 'http[s]://bw.example.com' instead of 'bw.example.com'");
}
Expand Down Expand Up @@ -555,7 +557,7 @@ impl Config {
warn!("Failed to parse email address '{}'", email);
return false;
}

// Allow signups if the whitelist is empty/not configured
// (it doesn't contain any domains), or if it matches at least
// one domain.
Expand Down
2 changes: 0 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate derive_more;
#[macro_use]
extern crate num_derive;
Expand Down

0 comments on commit 70f3ab8

Please sign in to comment.