pub mod helpers;
pub mod traits;
pub mod validators;
pub use helpers::{Helper, HelperRegistry};
pub use traits::*;
pub use validators::{Validator, ValidatorRegistry};
use once_cell::sync::Lazy;
use std::sync::Arc;
use tokio::sync::RwLock;
static GLOBAL_DEFINITIONS: Lazy<Arc<RwLock<Definitions>>> =
Lazy::new(|| Arc::new(RwLock::new(Definitions::new())));
pub struct Definitions {
pub helpers: HelperRegistry,
pub validators: ValidatorRegistry,
pub session_storage_factory: Option<traits::SessionStorageFactory>,
pub cache_storage_factory: Option<Box<dyn std::any::Any + Send + Sync>>,
}
impl Definitions {
pub fn new() -> Self {
Self {
helpers: HelperRegistry::new(),
validators: ValidatorRegistry::new(),
session_storage_factory: None,
cache_storage_factory: None,
}
}
pub fn register_helper(&mut self, name: &str, helper: impl Helper + 'static) {
self.helpers.register(name, helper);
}
pub fn register_validator(&mut self, name: &str, validator: impl Validator + 'static) {
self.validators.register(name, validator);
}
pub fn has_helper(&self, name: &str) -> bool {
self.helpers.exists(name)
}
pub fn has_validator(&self, name: &str) -> bool {
self.validators.exists(name)
}
pub fn set_session_storage_factory(&mut self, factory: traits::SessionStorageFactory) {
log::debug!("Registering custom session storage factory");
self.session_storage_factory = Some(factory);
}
pub fn get_session_storage_factory(&self) -> Option<traits::SessionStorageFactory> {
self.session_storage_factory
}
pub fn has_session_storage_factory(&self) -> bool {
self.session_storage_factory.is_some()
}
pub async fn initialize(&self) -> crate::error::Result<()> {
log::info!("Initializing RustF definitions");
log::debug!("Registered {} helpers", self.helpers.count());
log::debug!("Registered {} validators", self.validators.count());
if self.session_storage_factory.is_some() {
log::debug!("Custom session storage factory registered");
}
Ok(())
}
}
impl Default for Definitions {
fn default() -> Self {
Self::new()
}
}
pub type InstallFn = fn(&mut Definitions);
pub async fn load(definitions: Definitions) -> crate::error::Result<()> {
log::info!("Loading user definitions");
*GLOBAL_DEFINITIONS.write().await = definitions;
GLOBAL_DEFINITIONS.read().await.initialize().await?;
Ok(())
}
pub async fn get() -> Arc<RwLock<Definitions>> {
GLOBAL_DEFINITIONS.clone()
}
pub async fn get_mut() -> tokio::sync::RwLockWriteGuard<'static, Definitions> {
GLOBAL_DEFINITIONS.write().await
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_definitions_creation() {
let defs = Definitions::new();
assert!(defs.helpers.count() > 0);
assert!(defs.validators.count() > 0);
}
#[tokio::test]
async fn test_global_definitions() {
let defs = get().await;
assert!(defs.read().await.helpers.count() > 0);
}
}