⬆️ Replace LazyStatic with new std::sync::LazyLock

This commit is contained in:
Manuel Cillero 2024-07-27 14:00:27 +02:00
parent 2caa7e924b
commit dfb34d2e36
13 changed files with 67 additions and 62 deletions

View file

@ -42,8 +42,7 @@ concat-string = "1.0.1"
figlet-rs = "0.1.5"
itoa = "1.0.11"
nom = "7.1.3"
once_cell = "1.19.0"
paste = "1.0.14"
paste = "1.0.15"
substring = "1.4.5"
term_size = "0.3.2"
toml = "0.8.12"

View file

@ -6,7 +6,7 @@ use crate::core::{package, package::PackageRef};
use crate::html::Markup;
use crate::response::page::{ErrorPage, ResultPage};
use crate::service::HttpRequest;
use crate::{config, locale, service, trace, LazyStatic};
use crate::{config, locale, service, trace};
#[cfg(feature = "database")]
use crate::db;
@ -18,6 +18,7 @@ use actix_session::SessionMiddleware;
use substring::Substring;
use std::io::Error;
use std::sync::LazyLock;
pub struct Application;
@ -44,14 +45,14 @@ impl Application {
Self::show_banner();
// Starts logging and event tracing.
LazyStatic::force(&trace::TRACING);
LazyLock::force(&trace::TRACING);
// Validates the default language identifier.
LazyStatic::force(&locale::LANGID_DEFAULT);
LazyLock::force(&locale::LANGID_DEFAULT);
#[cfg(feature = "database")]
// Connects to the database.
LazyStatic::force(&db::DBCONN);
LazyLock::force(&db::DBCONN);
// Registers the application's packages.
package::all::register_packages(root_package);

View file

@ -1,8 +1,10 @@
use crate::{config, LazyStatic};
use crate::config;
use std::sync::LazyLock;
use figlet_rs::FIGfont;
pub static FIGFONT: LazyStatic<FIGfont> = LazyStatic::new(|| {
pub static FIGFONT: LazyLock<FIGfont> = LazyLock::new(|| {
let slant = include_str!("slant.flf");
let small = include_str!("small.flf");
let speed = include_str!("speed.flf");

View file

@ -119,12 +119,14 @@ mod path;
mod source;
mod value;
use crate::concat_string;
use crate::config::data::ConfigData;
use crate::config::file::File;
use crate::{concat_string, LazyStatic};
use serde::Deserialize;
use std::sync::LazyLock;
use std::env;
/// Directorio donde se encuentran los archivos de configuración.
@ -134,7 +136,7 @@ const CONFIG_DIR: &str = "config";
/// archivos de configuración.
#[rustfmt::skip]
pub static CONFIG: LazyStatic<ConfigData> = LazyStatic::new(|| {
pub static CONFIG: LazyLock<ConfigData> = LazyLock::new(|| {
// Modo de ejecución según la variable de entorno PAGETOP_RUN_MODE. Por defecto 'default'.
let run_mode = env::var("PAGETOP_RUN_MODE").unwrap_or_else(|_| "default".into());
@ -182,7 +184,7 @@ macro_rules! default_settings {
"Assigned or predefined values for configuration settings associated to the ",
"[`Settings`] type."
)]
pub static SETTINGS: $crate::LazyStatic<Settings> = $crate::LazyStatic::new(|| {
pub static SETTINGS: std::sync::LazyLock<Settings> = std::sync::LazyLock::new(|| {
let mut settings = $crate::config::CONFIG.clone();
$(
settings.set_default($key, $value).unwrap();

View file

@ -1,12 +1,11 @@
use crate::core::action::{ActionBox, ActionKey, ActionTrait, ActionsList};
use crate::LazyStatic;
use std::collections::HashMap;
use std::sync::RwLock;
use std::sync::{LazyLock, RwLock};
// Registered actions.
static ACTIONS: LazyStatic<RwLock<HashMap<ActionKey, ActionsList>>> =
LazyStatic::new(|| RwLock::new(HashMap::new()));
static ACTIONS: LazyLock<RwLock<HashMap<ActionKey, ActionsList>>> =
LazyLock::new(|| RwLock::new(HashMap::new()));
pub fn add_action(action: ActionBox) {
let key = action.key();

View file

@ -1,22 +1,22 @@
use crate::core::action::add_action;
use crate::core::package::PackageRef;
use crate::core::theme::all::THEMES;
use crate::{config, service, service_for_static_files, static_files, trace, LazyStatic};
use crate::{config, service, service_for_static_files, static_files, trace};
#[cfg(feature = "database")]
use crate::db::*;
use std::sync::RwLock;
use std::sync::{LazyLock, RwLock};
static_files!(base);
// PACKAGES ****************************************************************************************
static ENABLED_PACKAGES: LazyStatic<RwLock<Vec<PackageRef>>> =
LazyStatic::new(|| RwLock::new(Vec::new()));
static ENABLED_PACKAGES: LazyLock<RwLock<Vec<PackageRef>>> =
LazyLock::new(|| RwLock::new(Vec::new()));
static DROPPED_PACKAGES: LazyStatic<RwLock<Vec<PackageRef>>> =
LazyStatic::new(|| RwLock::new(Vec::new()));
static DROPPED_PACKAGES: LazyLock<RwLock<Vec<PackageRef>>> =
LazyLock::new(|| RwLock::new(Vec::new()));
// REGISTER PACKAGES *******************************************************************************

View file

@ -1,17 +1,16 @@
use crate::config;
use crate::core::theme::ThemeRef;
use crate::LazyStatic;
use std::sync::RwLock;
use std::sync::{LazyLock, RwLock};
// THEMES ******************************************************************************************
pub static THEMES: LazyStatic<RwLock<Vec<ThemeRef>>> = LazyStatic::new(|| RwLock::new(Vec::new()));
pub static THEMES: LazyLock<RwLock<Vec<ThemeRef>>> = LazyLock::new(|| RwLock::new(Vec::new()));
// DEFAULT THEME ***********************************************************************************
pub static THEME_DEFAULT: LazyStatic<ThemeRef> =
LazyStatic::new(|| match theme_by_short_name(&config::SETTINGS.app.theme) {
pub static THEME_DEFAULT: LazyLock<ThemeRef> =
LazyLock::new(|| match theme_by_short_name(&config::SETTINGS.app.theme) {
Some(theme) => theme,
None => &crate::base::theme::Inception,
});

View file

@ -1,15 +1,15 @@
use crate::core::component::{AnyComponent, AnyOp, MixedComponents};
use crate::core::theme::ThemeRef;
use crate::{fn_builder, AutoDefault, LazyStatic, TypeId};
use crate::{fn_builder, AutoDefault, TypeId};
use std::collections::HashMap;
use std::sync::RwLock;
use std::sync::{LazyLock, RwLock};
static THEME_REGIONS: LazyStatic<RwLock<HashMap<TypeId, ComponentsInRegions>>> =
LazyStatic::new(|| RwLock::new(HashMap::new()));
static THEME_REGIONS: LazyLock<RwLock<HashMap<TypeId, ComponentsInRegions>>> =
LazyLock::new(|| RwLock::new(HashMap::new()));
static COMMON_REGIONS: LazyStatic<RwLock<ComponentsInRegions>> =
LazyStatic::new(|| RwLock::new(ComponentsInRegions::default()));
static COMMON_REGIONS: LazyLock<RwLock<ComponentsInRegions>> =
LazyLock::new(|| RwLock::new(ComponentsInRegions::default()));
#[derive(AutoDefault)]
pub struct ComponentsInRegions(HashMap<&'static str, MixedComponents>);

View file

@ -1,7 +1,7 @@
//! Database access.
use crate::util::TypeInfo;
use crate::{config, trace, LazyStatic};
use crate::{config, trace};
pub use url::Url as DbUri;
@ -10,11 +10,13 @@ pub use sea_orm::{DatabaseConnection as DbConn, ExecResult, QueryResult};
use sea_orm::{ConnectOptions, ConnectionTrait, Database, DatabaseBackend, Statement};
use std::sync::LazyLock;
pub(crate) use futures::executor::block_on as run_now;
const DBCONN_NOT_INITIALIZED: &str = "Database connection not initialized";
pub(crate) static DBCONN: LazyStatic<Option<DbConn>> = LazyStatic::new(|| {
pub(crate) static DBCONN: LazyLock<Option<DbConn>> = LazyLock::new(|| {
if !config::SETTINGS.database.db_name.trim().is_empty() {
trace::info!(
"Connecting to database \"{}\" using a pool of {} connections",

View file

@ -87,7 +87,6 @@ pub use pagetop_macros::{fn_builder, main, test, AutoDefault, ComponentClasses};
// GLOBAL.
// *************************************************************************************************
pub use once_cell::sync::Lazy as LazyStatic;
pub use static_files::Resource as StaticResource;
pub type HashMapResources = std::collections::HashMap<&'static str, StaticResource>;

View file

@ -98,10 +98,13 @@ use fluent_templates::StaticLoader as Locales;
use unic_langid::langid;
use std::collections::HashMap;
use std::sync::LazyLock;
use std::fmt;
const LANGUAGE_SET_FAILURE: &str = "language_set_failure";
static LANGUAGES: LazyStatic<HashMap<String, (LanguageIdentifier, &str)>> = LazyStatic::new(|| {
static LANGUAGES: LazyLock<HashMap<String, (LanguageIdentifier, &str)>> = LazyLock::new(|| {
kv![
"en" => (langid!("en-US"), "English"),
"en-GB" => (langid!("en-GB"), "English (British)"),
@ -111,12 +114,12 @@ static LANGUAGES: LazyStatic<HashMap<String, (LanguageIdentifier, &str)>> = Lazy
]
});
pub static LANGID_FALLBACK: LazyStatic<LanguageIdentifier> = LazyStatic::new(|| langid!("en-US"));
pub static LANGID_FALLBACK: LazyLock<LanguageIdentifier> = LazyLock::new(|| langid!("en-US"));
/// Sets the application's default
/// [Unicode Language Identifier](https://unicode.org/reports/tr35/tr35.html#Unicode_language_identifier)
/// through `SETTINGS.app.language`.
pub static LANGID_DEFAULT: LazyStatic<&LanguageIdentifier> = LazyStatic::new(|| {
pub static LANGID_DEFAULT: LazyLock<&LanguageIdentifier> = LazyLock::new(|| {
langid_for(config::SETTINGS.app.language.as_str()).unwrap_or(&LANGID_FALLBACK)
});

View file

@ -1,11 +1,11 @@
//! The PageTop Prelude.
//! The `PageTop` Prelude.
// RE-EXPORTED MACROS AND DERIVES.
pub use crate::{concat_string, fn_builder, main, paste, test};
pub use crate::{AutoDefault, ComponentClasses};
// GLOBAL.
pub use crate::{HashMapResources, LazyStatic, TypeId, Weight};
pub use crate::{HashMapResources, TypeId, Weight};
// MACROS.

View file

@ -1,21 +1,18 @@
//! Application tracing and event logging.
//!
//! PageTop recopila la información de diagnóstico de la aplicación de manera estructurada y basada
//! en eventos.
//! `PageTop` collects application diagnostic information in a structured and event-based manner.
//!
//! En sistemas asíncronos, interpretar los mensajes de registro tradicionales (*log*) a menudo
//! resulta complicado. Las tareas individuales se multiplexan para el mismo subproceso y los
//! eventos y mensajes de registro asociados se entremezclan, dificultando el seguimiento de la
//! secuencia lógica.
//! In asynchronous systems, interpreting traditional log messages often becomes complicated.
//! Individual tasks are multiplexed to the same thread, and associated events and log messages get
//! intermingled, making it difficult to follow the logical sequence.
//!
//! PageTop usa [`tracing`](https://docs.rs/tracing) para permitir a las **aplicaciones** y los
//! **módulos** registrar eventos estructurados con información añadida sobre *temporalidad* y
//! *causalidad*. A diferencia de un mensaje de registro, un intervalo (*span*) tiene una hora de
//! inicio y de finalización, puede entrar y salir del flujo de la ejecución y puede existir dentro
//! de un árbol anidado de intervalos similares. Además, estos intervalos están *estructurados*, con
//! capacidad para grabar tipos de datos y mensajes de texto.
//! `PageTop` uses [`tracing`](https://docs.rs/tracing) to allow **applications** and **modules** to
//! log structured events with added information about *temporality* and *causality*. Unlike a log
//! message, a span has a start and end time, can enter and exit the execution flow, and can exist
//! within a nested tree of similar spans. Additionally, these spans are *structured*, with the
//! ability to record data types and text messages.
use crate::{config, LazyStatic};
use crate::config;
pub use tracing::{debug, error, info, trace, warn};
pub use tracing::{debug_span, error_span, info_span, trace_span, warn_span};
@ -23,19 +20,21 @@ pub use tracing::{debug_span, error_span, info_span, trace_span, warn_span};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::EnvFilter;
/// Registro de trazas y eventos de la aplicación.
use std::sync::LazyLock;
/// Application tracing and event logging.
///
/// Para aumentar el rendimiento, un subproceso dedicado utiliza un sistema de escritura sin bloqueo
/// (*non-blocking writer*) que actúa periódicamente en vez de enviar cada traza o evento al
/// instante. Si el programa termina abruptamente (por ejemplo, por un panic! o un
/// std::process::exit), es posible que algunas trazas o eventos no se envíen.
/// To increase performance, a dedicated thread uses a non-blocking writer system that acts
/// periodically instead of sending each trace or event instantly. If the program terminates
/// abruptly (e.g., due to a panic! or a `std::process::exit`), some traces or events might not be
/// sent.
///
/// Puesto que las trazas o eventos registrados poco antes de la caída de una aplicación suelen ser
/// importantes para diagnosticar la causa del fallo, con `Lazy<WorkerGuard>` se garantiza que todos
/// los registros almacenados se enviarán antes de terminar la ejecución.
/// Since traces or events logged shortly before an application crash are often important for
/// diagnosing the cause of the failure, `Lazy<WorkerGuard>` ensures that all stored logs are sent
/// before terminating execution.
#[rustfmt::skip]
pub(crate) static TRACING: LazyStatic<WorkerGuard> = LazyStatic::new(|| {
pub(crate) static TRACING: LazyLock<WorkerGuard> = LazyLock::new(|| {
let env_filter = EnvFilter::try_new(&config::SETTINGS.log.tracing)
.unwrap_or_else(|_| EnvFilter::new("Info"));