Add reusable global structs

This commit is contained in:
fluo10 2025-06-20 08:42:02 +09:00
parent eb428eb537
commit 3a2f53dd46
3 changed files with 74 additions and 53 deletions

View file

@ -1,18 +1,6 @@
use crate::{config::StorageConfig, error::Error}; use crate::{config::StorageConfig, error::Error, global::SimpleGlobal};
use tokio::sync::OnceCell; use tokio::sync::OnceCell;
use uuid::fmt::Simple;
static STORAGE_CONFIG: OnceCell<StorageConfig> = OnceCell::const_new(); pub static STORAGE_CONFIG: SimpleGlobal<StorageConfig> = SimpleGlobal::const_new();
pub async fn get_or_init_storage_config(config: StorageConfig) -> &'static StorageConfig {
STORAGE_CONFIG.get_or_init(|| async {
config
}).await
}
pub fn get_storage_config() -> Option<&'static StorageConfig> {
STORAGE_CONFIG.get()
}
pub fn get_and_unwrap_storage_config() -> &'static StorageConfig {
STORAGE_CONFIG.get().expect("global storage config is uninitialized!")
}

View file

@ -5,43 +5,35 @@ use sea_orm_migration::MigratorTrait;
use crate::error::Error; use crate::error::Error;
use tokio::sync::OnceCell; use tokio::sync::OnceCell;
static DATA_DATABASE_CONNECTION: OnceCell<DatabaseConnection> = OnceCell::const_new(); static DATA_DATABASE_CONNECTION: GlobalDatabaseConnection = GlobalDatabaseConnection::const_new();
static CACHE_DATABASE_CONNECTION: OnceCell<DatabaseConnection> = OnceCell::const_new(); static CACHE_DATABASE_CONNECTION: GlobalDatabaseConnection = GlobalDatabaseConnection::const_new();
pub fn get_data_database_connection() -> Option<&'static DatabaseConnection> { struct GlobalDatabaseConnection {
DATA_DATABASE_CONNECTION.get() inner: OnceCell<DatabaseConnection>
} }
pub fn get_and_unwrap_data_database_connection() -> &'static DatabaseConnection {
get_data_database_connection().expect("global data database connection uninitialized!") impl GlobalDatabaseConnection {
pub const fn const_new() -> Self {
Self {
inner: OnceCell::const_new()
} }
pub async fn get_or_try_init_data_database_connection<T, U>(path: T, _: U) -> Result<&'static DatabaseConnection, Error> }
pub fn get(&'static self) -> Option<&'static DatabaseConnection> {
self.inner.get()
}
pub fn get_and_unwrap(&'static self) -> &'static DatabaseConnection {
self.get().expect(&format!("{} is uninitialized!", &stringify!(self)))
}
pub async fn get_or_try_init<T, U>(&'static self, path: T, _: U) -> Result<&'static DatabaseConnection, Error>
where where
T: AsRef<Path>, T: AsRef<Path>,
U: MigratorTrait U: MigratorTrait
{ {
let url = "sqlite://".to_string() + path.as_ref().to_str().unwrap() + "?mode=rwc"; let url = "sqlite://".to_string() + path.as_ref().to_str().unwrap() + "?mode=rwc";
Ok(DATA_DATABASE_CONNECTION.get_or_try_init(|| async { Ok(self.inner.get_or_try_init(|| async {
let db = Database::connect(&url).await?; let db = Database::connect(&url).await?;
U::up(&db, None).await?; U::up(&db, None).await?;
Ok::<DatabaseConnection, DbErr>(db) Ok::<DatabaseConnection, DbErr>(db)
}).await?) }).await?)
} }
pub fn get_cache_database_connection() -> Option<&'static DatabaseConnection> {
CACHE_DATABASE_CONNECTION.get()
}
pub fn get_and_unwrap_cache_database_connection() -> &'static DatabaseConnection {
CACHE_DATABASE_CONNECTION.get().expect("global data database connection uninitialized!")
}
pub async fn get_or_try_init_cache_database_connection<T, U>(path: T, _: U) -> Result<&'static DatabaseConnection, Error>
where
T: AsRef<Path>,
U: MigratorTrait
{
let url = "sqlite://".to_string() + path.as_ref().to_str().unwrap() + "?mode=rwc";
Ok(DATA_DATABASE_CONNECTION.get_or_try_init(|| async {
let db = Database::connect(&url).await?;
U::up(&db, None).await?;
Ok::<DatabaseConnection, DbErr>(db)
}).await?)
} }

View file

@ -1,4 +1,4 @@
use std::{collections::HashMap, net::{IpAddr, Ipv4Addr}, path::{Path, PathBuf}, sync::LazyLock}; use std::{any::type_name, collections::HashMap, net::{IpAddr, Ipv4Addr}, path::{Path, PathBuf}, sync::LazyLock};
use crate::{config::{P2pConfig, PartialP2pConfig, StorageConfig}, error::Error}; use crate::{config::{P2pConfig, PartialP2pConfig, StorageConfig}, error::Error};
use futures::StreamExt; use futures::StreamExt;
@ -10,7 +10,7 @@ use tokio::sync::{OnceCell, RwLock};
mod peers; mod peers;
pub use peers::GlobalPeers; pub use peers::GlobalPeers;
mod config; mod config;
pub use config::*; pub use config::STORAGE_CONFIG;
mod database_connection; mod database_connection;
pub use database_connection::*; pub use database_connection::*;
use uuid::{ContextV7, Timestamp, Uuid}; use uuid::{ContextV7, Timestamp, Uuid};
@ -33,6 +33,47 @@ pub static DEFAULT_CONFIG_FILE_NAME: LazyLock<PathBuf> = LazyLock::new(|| {
pub static DEFAULT_DATABASE_FILE_NAME: LazyLock<PathBuf> = LazyLock::new(|| { pub static DEFAULT_DATABASE_FILE_NAME: LazyLock<PathBuf> = LazyLock::new(|| {
PathBuf::from(String::new() + env!("CARGO_PKG_NAME") + ".sqlite") PathBuf::from(String::new() + env!("CARGO_PKG_NAME") + ".sqlite")
}); });
fn uninitialized_message<T>(var: T) -> String {
format!("{} is uninitialized!", &stringify!(var))
}
struct SimpleGlobal<T> {
inner: OnceCell<T>
}
impl<T> SimpleGlobal<T> {
pub const fn const_new() -> Self {
Self{inner: OnceCell::const_new()}
}
pub async fn get_or_init(&'static self, source: T) -> &'static T {
self.inner.get_or_init(|| async {
source
}).await
}
pub fn get(&'static self) -> Option<&'static T> {
self.inner.get()
}
pub fn get_and_unwrap(&'static self) -> &'static T {
self.get().expect(&format!("{} is uninitialized!", &stringify!(self)))
}
}
struct GlobalRwLock<T> {
inner: OnceCell<RwLock<T>>
}
impl<T> GlobalRwLock<T> {
pub const fn const_new() -> Self {
Self{inner: OnceCell::const_new()}
}
async fn write(&'static self) -> tokio::sync::RwLockWriteGuard<'_ ,T> {
self.get_peers_once_cell().get().expect(UNINITIALIZED_MESSAGE).write().await
}
async fn read(&'static self) -> RwLockReadGuard<'_, T> {
self.get_peers_once_cell().get().expect(UNINITIALIZED_MESSAGE).read().await
}
}
#[cfg(test)] #[cfg(test)]
pub struct TestGlobal { pub struct TestGlobal {