caretta-sync/core/src/global/config.rs

46 lines
1.5 KiB
Rust
Raw Normal View History

2025-08-18 08:22:20 +09:00
use tempfile::TempDir;
use tokio::sync::OnceCell;
2025-06-20 07:28:51 +09:00
2025-08-18 08:22:20 +09:00
use crate::{config::{Config, PartialP2pConfig, PartialRpcConfig, PartialStorageConfig, StorageConfig}, error::Error, global::GlobalConstant};
2025-06-20 07:28:51 +09:00
2025-08-18 08:22:20 +09:00
pub static CONFIG: GlobalConfig = GlobalConfig::const_new();
pub struct GlobalConfig {
inner: OnceCell<Config>
}
2025-06-22 11:29:44 +09:00
2025-08-18 08:22:20 +09:00
impl GlobalConfig {
pub const fn const_new() -> Self {
Self{
inner: OnceCell::const_new()
}
}
pub async fn get_or_init(&'static self, source: Config) -> &'static Config {
self.inner.get_or_init(|| async {
source
}).await
}
pub fn get(&'static self) -> Option<&'static Config> {
self.inner.get()
}
pub fn get_and_unwrap(&'static self) -> &'static Config {
self.get().expect(&format!("Config is uninitialized!"))
}
#[cfg(any(test, feature=test))]
pub async fn get_or_init_test(&'static self) -> &'static Config {
let temp_dir = TempDir::new().unwrap().keep();
let mut data_dir = temp_dir.clone();
data_dir.push("data");
let mut cache_dir = temp_dir;
cache_dir.push("cache");
self.get_or_init(Config {
p2p: PartialP2pConfig::default().with_new_secret().try_into().unwrap(),
storage: StorageConfig {
data_directory: data_dir,
cache_directory: cache_dir,
},
rpc: PartialRpcConfig::default().try_into().unwrap(),
}).await
2025-06-22 11:29:44 +09:00
}
}