use crate::error::{Error, Result as RustfResult};
use anyhow::Result;
use async_trait::async_trait;
use dashmap::DashMap;
use once_cell::sync::OnceCell;
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Arc;
#[async_trait]
pub trait SharedModule: Send + Sync {
fn name(&self) -> &'static str;
fn module_type(&self) -> SharedModuleType;
async fn initialize(&self) -> Result<()> {
Ok(())
}
async fn shutdown(&self) -> Result<()> {
Ok(())
}
fn as_any(&self) -> &dyn Any;
}
#[derive(Debug, Clone, PartialEq)]
pub enum SharedModuleType {
Service,
Util,
Helper,
Trait,
}
impl std::fmt::Display for SharedModuleType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SharedModuleType::Service => write!(f, "service"),
SharedModuleType::Util => write!(f, "util"),
SharedModuleType::Helper => write!(f, "helper"),
SharedModuleType::Trait => write!(f, "trait"),
}
}
}
pub struct ModuleRegistry {
modules: DashMap<String, Arc<dyn SharedModule>>,
}
impl ModuleRegistry {
pub fn new() -> Self {
Self {
modules: DashMap::new(),
}
}
pub fn register<T: SharedModule + 'static>(&self, name: &str, module: T) -> RustfResult<()> {
if self.modules.contains_key(name) {
return Err(Error::internal(format!(
"Module with name '{}' is already registered",
name
)));
}
let module = Arc::new(module);
self.modules
.insert(name.to_string(), module as Arc<dyn SharedModule>);
Ok(())
}
pub fn get(&self, name: &str) -> RustfResult<Arc<dyn SharedModule>> {
self.modules
.get(name)
.map(|entry| entry.clone())
.ok_or_else(|| Error::internal(format!("Module '{}' not found", name)))
}
pub fn get_opt(&self, name: &str) -> Option<Arc<dyn SharedModule>> {
self.modules.get(name).map(|entry| entry.clone())
}
pub async fn shutdown_all(&self) -> Result<()> {
for entry in self.modules.iter() {
let name = entry.key().clone();
let module = entry.value().clone();
log::debug!("Shutting down shared module: {}", name);
if let Err(e) = module.shutdown().await {
log::warn!("Error shutting down module '{}': {}", name, e);
}
}
Ok(())
}
pub fn list_modules(&self) -> Vec<(String, SharedModuleType)> {
self.modules
.iter()
.map(|entry| {
let name = entry.key().clone();
let module_type = entry.value().module_type();
(name, module_type)
})
.collect()
}
pub fn contains(&self, name: &str) -> bool {
self.modules.contains_key(name)
}
}
impl Default for ModuleRegistry {
fn default() -> Self {
Self::new()
}
}
#[derive(Default)]
pub struct SharedRegistry {
modules: HashMap<TypeId, Arc<dyn SharedModule>>,
modules_by_name: HashMap<String, Arc<dyn SharedModule>>,
}
impl SharedRegistry {
pub fn new() -> Self {
Self {
modules: HashMap::new(),
modules_by_name: HashMap::new(),
}
}
pub fn register<T: SharedModule + 'static>(&mut self, module: T) {
let module = Arc::new(module);
let type_id = TypeId::of::<T>();
let name = module.name().to_string();
self.modules
.insert(type_id, module.clone() as Arc<dyn SharedModule>);
self.modules_by_name
.insert(name, module as Arc<dyn SharedModule>);
}
pub fn get<T: SharedModule + 'static>(&self) -> Option<&T> {
let type_id = TypeId::of::<T>();
self.modules
.get(&type_id)
.and_then(|module| module.as_ref().as_any().downcast_ref::<T>())
}
pub fn get_by_name(&self, name: &str) -> Option<Arc<dyn SharedModule>> {
self.modules_by_name.get(name).cloned()
}
pub async fn initialize_all(&self) -> Result<()> {
for (name, module) in &self.modules_by_name {
log::debug!("Initializing shared module: {}", name);
module
.initialize()
.await
.map_err(|e| anyhow::anyhow!("Failed to initialize module '{}': {}", name, e))?;
}
Ok(())
}
pub async fn shutdown_all(&self) -> Result<()> {
for (name, module) in &self.modules_by_name {
log::debug!("Shutting down shared module: {}", name);
if let Err(e) = module.shutdown().await {
log::warn!("Error shutting down module '{}': {}", name, e);
}
}
Ok(())
}
pub fn list_modules(&self) -> Vec<(&str, SharedModuleType)> {
self.modules_by_name
.values()
.map(|module| (module.name(), module.module_type()))
.collect()
}
pub fn contains<T: SharedModule + 'static>(&self) -> bool {
let type_id = TypeId::of::<T>();
self.modules.contains_key(&type_id)
}
pub fn contains_name(&self, name: &str) -> bool {
self.modules_by_name.contains_key(name)
}
}
#[macro_export]
macro_rules! impl_shared_util {
($struct_name:ident) => {
#[async_trait::async_trait]
impl $crate::shared::SharedModule for $struct_name {
fn name(&self) -> &'static str {
stringify!($struct_name)
}
fn module_type(&self) -> $crate::shared::SharedModuleType {
$crate::shared::SharedModuleType::Util
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
};
}
#[macro_export]
macro_rules! impl_shared_service {
($struct_name:ident) => {
#[async_trait::async_trait]
impl $crate::shared::SharedModule for $struct_name {
fn name(&self) -> &'static str {
stringify!($struct_name)
}
fn module_type(&self) -> $crate::shared::SharedModuleType {
$crate::shared::SharedModuleType::Service
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
};
}
#[macro_export]
macro_rules! impl_shared_helper {
($struct_name:ident) => {
#[async_trait::async_trait]
impl $crate::shared::SharedModule for $struct_name {
fn name(&self) -> &'static str {
stringify!($struct_name)
}
fn module_type(&self) -> $crate::shared::SharedModuleType {
$crate::shared::SharedModuleType::Helper
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
};
}
#[cfg(test)]
mod tests {
use super::*;
pub struct TestUtils;
impl_shared_util!(TestUtils);
impl TestUtils {
#[allow(dead_code)]
pub fn add_numbers(a: i32, b: i32) -> i32 {
a + b
}
}
pub struct TestService {
pub config: String,
}
impl_shared_service!(TestService);
impl TestService {
pub fn new(config: String) -> Self {
Self { config }
}
#[allow(dead_code)]
pub async fn do_something(&self) -> Result<String> {
Ok(format!("Service result: {}", self.config))
}
}
#[tokio::test]
async fn test_module_registry_named_registration() {
let registry = ModuleRegistry::new();
let service1 = TestService::new("primary".to_string());
let service2 = TestService::new("backup".to_string());
registry.register("service-primary", service1).unwrap();
registry.register("service-backup", service2).unwrap();
let _primary = registry.get("service-primary").unwrap();
assert!(registry.contains("service-primary"));
assert!(registry.contains("service-backup"));
let modules = registry.list_modules();
assert_eq!(modules.len(), 2);
registry.shutdown_all().await.unwrap();
}
#[tokio::test]
async fn test_module_registry_duplicate_name() {
let registry = ModuleRegistry::new();
let service = TestService::new("config".to_string());
registry.register("test-service", service).unwrap();
let service2 = TestService::new("config2".to_string());
let result = registry.register("test-service", service2);
assert!(result.is_err());
assert!(result
.unwrap_err()
.to_string()
.contains("already registered"));
}
#[tokio::test]
async fn test_module_registry_not_found() {
let registry = ModuleRegistry::new();
let result = registry.get("non-existent");
assert!(result.is_err());
let opt = registry.get_opt("non-existent");
assert!(opt.is_none());
}
}
static MODULE_REGISTRY: OnceCell<ModuleRegistry> = OnceCell::new();
pub struct MODULE;
impl MODULE {
pub fn init() -> RustfResult<()> {
MODULE_REGISTRY
.set(ModuleRegistry::new())
.map_err(|_| Error::internal("MODULE registry has already been initialized"))
}
pub fn register<T: SharedModule + 'static>(name: &str, module: T) -> RustfResult<()> {
let registry = MODULE_REGISTRY.get().ok_or_else(|| {
Error::internal(
"MODULE registry not initialized. Call MODULE::init() during app startup",
)
})?;
registry.register(name, module)
}
pub fn get(name: &str) -> RustfResult<Arc<dyn SharedModule>> {
let registry = MODULE_REGISTRY.get().ok_or_else(|| {
Error::internal(
"MODULE registry not initialized. Call MODULE::init() during app startup",
)
})?;
registry.get(name)
}
pub fn get_opt(name: &str) -> Option<Arc<dyn SharedModule>> {
MODULE_REGISTRY.get()?.get_opt(name)
}
pub fn exists(name: &str) -> bool {
MODULE_REGISTRY
.get()
.map(|r| r.contains(name))
.unwrap_or(false)
}
pub fn is_initialized() -> bool {
MODULE_REGISTRY.get().is_some()
}
pub fn list() -> Vec<(String, String)> {
MODULE_REGISTRY
.get()
.map(|r| {
r.list_modules()
.into_iter()
.map(|(name, module_type)| (name, module_type.to_string()))
.collect()
})
.unwrap_or_default()
}
pub fn get_registry() -> Option<&'static ModuleRegistry> {
MODULE_REGISTRY.get()
}
}