flatten global structs
This commit is contained in:
parent
a80b9bcdf1
commit
eb428eb537
7 changed files with 93 additions and 68 deletions
|
@ -3,11 +3,11 @@ use sea_orm_migration::prelude::*;
|
|||
pub mod m20220101_000001_create_main_tables;
|
||||
|
||||
#[cfg(any(test, feature="test"))]
|
||||
pub struct MainMigrator;
|
||||
pub struct DataMigrator;
|
||||
|
||||
#[cfg(any(test, feature="test"))]
|
||||
#[async_trait::async_trait]
|
||||
impl MigratorTrait for MainMigrator {
|
||||
impl MigratorTrait for DataMigrator {
|
||||
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
|
||||
vec![Box::new(m20220101_000001_create_main_tables::Migration)]
|
||||
}
|
||||
|
|
18
lazy-supplements-core/src/global/config.rs
Normal file
18
lazy-supplements-core/src/global/config.rs
Normal file
|
@ -0,0 +1,18 @@
|
|||
use crate::{config::StorageConfig, error::Error};
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
static STORAGE_CONFIG: OnceCell<StorageConfig> = OnceCell::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!")
|
||||
}
|
|
@ -5,28 +5,43 @@ use sea_orm_migration::MigratorTrait;
|
|||
use crate::error::Error;
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
use super::storage_config::GlobalStorageConfig;
|
||||
|
||||
static UNINITIALIZED_MESSAGE: &str = "global database connection uninitialized!";
|
||||
|
||||
pub trait GlobalDatabaseConnection: GlobalStorageConfig {
|
||||
fn get_data_database_connection_as_once_cell(&'static self) -> &'static OnceCell<DatabaseConnection>;
|
||||
fn get_data_database_connection(&'static self) -> Option<&'static DatabaseConnection> {
|
||||
self.get_data_database_connection_as_once_cell().get()
|
||||
}
|
||||
fn get_and_unwrap_data_database_connection(&'static self) -> &'static DatabaseConnection {
|
||||
self.get_data_database_connection().expect(UNINITIALIZED_MESSAGE)
|
||||
}
|
||||
async fn get_or_try_init_data_database_connection<T>(&'static self, _: T) -> Result<&DatabaseConnection, Error>
|
||||
where
|
||||
T: MigratorTrait
|
||||
{
|
||||
let url = "sqlite://".to_string() + self.get_and_unwrap_storage_config().get_data_database_path().to_str().unwrap() + "?mode=rwc";
|
||||
Ok(self.get_data_database_connection_as_once_cell().get_or_try_init(|| async {
|
||||
let db = Database::connect(&url).await?;
|
||||
T::up(&db, None).await?;
|
||||
Ok::<DatabaseConnection, DbErr>(db)
|
||||
}).await?)
|
||||
}
|
||||
static DATA_DATABASE_CONNECTION: OnceCell<DatabaseConnection> = OnceCell::const_new();
|
||||
static CACHE_DATABASE_CONNECTION: OnceCell<DatabaseConnection> = OnceCell::const_new();
|
||||
|
||||
pub fn get_data_database_connection() -> Option<&'static DatabaseConnection> {
|
||||
DATA_DATABASE_CONNECTION.get()
|
||||
}
|
||||
pub fn get_and_unwrap_data_database_connection() -> &'static DatabaseConnection {
|
||||
get_data_database_connection().expect("global data database connection uninitialized!")
|
||||
}
|
||||
pub async fn get_or_try_init_data_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?)
|
||||
}
|
||||
|
||||
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?)
|
||||
}
|
|
@ -9,9 +9,10 @@ use tokio::sync::{OnceCell, RwLock};
|
|||
|
||||
mod peers;
|
||||
pub use peers::GlobalPeers;
|
||||
mod storage_config;
|
||||
mod config;
|
||||
pub use config::*;
|
||||
mod database_connection;
|
||||
pub use database_connection::GlobalDatabaseConnection;
|
||||
pub use database_connection::*;
|
||||
use uuid::{ContextV7, Timestamp, Uuid};
|
||||
|
||||
pub fn generate_uuid() -> Uuid {
|
||||
|
@ -33,17 +34,29 @@ pub static DEFAULT_DATABASE_FILE_NAME: LazyLock<PathBuf> = LazyLock::new(|| {
|
|||
PathBuf::from(String::new() + env!("CARGO_PKG_NAME") + ".sqlite")
|
||||
});
|
||||
|
||||
#[cfg(any(test, feature="test"))]
|
||||
#[cfg(test)]
|
||||
pub struct TestGlobal {
|
||||
p2p_config: OnceCell<P2pConfig>,
|
||||
storage_config: OnceCell<StorageConfig>,
|
||||
data_database_connection: OnceCell<DatabaseConnection>,
|
||||
cache_database_connection: OnceCell<DatabaseConnection>,
|
||||
pub storage_config: &'static StorageConfig,
|
||||
pub data_database_connection: &'static DatabaseConnection,
|
||||
pub cache_database_connection: &'static DatabaseConnection,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{cache::migration::CacheMigrator, data::migration::DataMigrator};
|
||||
|
||||
use super::*;
|
||||
static TEST_DATA_DIRECTORY: LazyLock<PathBuf> = todo!();
|
||||
static TEST_DATA_DATABASE_PATH: LazyLock<PathBuf> = todo!();
|
||||
static TEST_CACHE_DIRECTORY: LazyLock<PathBuf> = todo!();
|
||||
static TEST_CACHE_DATABASE_PATH: LazyLock<PathBuf> = todo!();
|
||||
static TEST_STORAGE_CONFIG: LazyLock<StorageConfig> = todo!();
|
||||
|
||||
pub async fn get_or_try_init_test() -> TestGlobal {
|
||||
TestGlobal {
|
||||
storage_config: get_or_init_storage_config(StorageConfig{data_directory: TEST_DATA_DIRECTORY.clone(), cache_directory: TEST_CACHE_DIRECTORY.clone()}).await,
|
||||
data_database_connection: get_or_try_init_data_database_connection(&*TEST_DATA_DATABASE_PATH, DataMigrator ).await.unwrap(),
|
||||
cache_database_connection: get_or_try_init_cache_database_connection(&*TEST_CACHE_DATABASE_PATH, CacheMigrator).await.unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(any(test, feature="test"))]
|
||||
pub static GLOBAL: TestGlobal = TestGlobal{
|
||||
p2p_config: OnceCell::const_new(),
|
||||
storage_config: OnceCell::const_new(),
|
||||
data_database_connection: OnceCell::const_new(),
|
||||
cache_database_connection: OnceCell::const_new(),
|
||||
};
|
||||
|
|
|
@ -1,22 +0,0 @@
|
|||
use std::path::Path;
|
||||
|
||||
use sea_orm::{ConnectOptions, Database, DbErr, DatabaseConnection};
|
||||
use sea_orm_migration::MigratorTrait;
|
||||
use crate::{config::StorageConfig, error::Error};
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
static UNINITIALIZED_MESSAGE: &str = "global storage is uninitialized!";
|
||||
|
||||
pub trait GlobalStorageConfig {
|
||||
|
||||
fn init_storage_config(&'static self, config: StorageConfig) {
|
||||
self.get_storage_config_once_cell().set(config).unwrap();
|
||||
}
|
||||
fn get_storage_config_once_cell(&'static self) -> &'static OnceCell<StorageConfig>;
|
||||
fn get_storage_config(&'static self) -> Option<&'static StorageConfig> {
|
||||
self.get_storage_config_once_cell().get()
|
||||
}
|
||||
fn get_and_unwrap_storage_config(&'static self) -> &'static StorageConfig {
|
||||
self.get_storage_config().expect(UNINITIALIZED_MESSAGE)
|
||||
}
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
use libp2p::{ identity::Keypair, mdns, ping, swarm};
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::{error::Error, global::GlobalPeers};
|
||||
|
||||
#[derive(swarm::NetworkBehaviour)]
|
||||
#[behaviour(to_swarm = "Event")]
|
||||
|
@ -29,17 +29,20 @@ pub enum Event {
|
|||
}
|
||||
|
||||
impl Event {
|
||||
pub async fn run(self) {
|
||||
pub async fn run<T>(self, global: &T)
|
||||
where
|
||||
T: GlobalPeers
|
||||
{
|
||||
match self {
|
||||
Self::Mdns(x) => {
|
||||
match x {
|
||||
mdns::Event::Discovered(e) => {
|
||||
for peer in e {
|
||||
//let mut peers = crate::global::GLOBAL.write_peers().await;
|
||||
//peers.insert(peer.0, peer.1);
|
||||
global.write_peers().await;
|
||||
peers.insert(peer.0, peer.1);
|
||||
}
|
||||
//let peers = crate::global::GLOBAL.read_peers().await;
|
||||
//println!("Peers: {peers:?}");
|
||||
let peers = global.read_peers().await;
|
||||
println!("Peers: {peers:?}");
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
|
|
|
@ -20,7 +20,6 @@ pub static TEST_DATABASE_PATH: std::sync::LazyLock<PathBuf> = std::sync::LazyLoc
|
|||
TEST_DIR_PATH.join("lazy-supplements.sqlite")
|
||||
});
|
||||
|
||||
#[cfg(any(test, feature="test"))]
|
||||
pub fn test_cbor_serialize_deserialize<T>(src: T)
|
||||
where T: DeserializeOwned + Serialize + PartialEq + std::fmt::Debug
|
||||
{
|
||||
|
@ -30,7 +29,6 @@ where T: DeserializeOwned + Serialize + PartialEq + std::fmt::Debug
|
|||
assert_eq!(src, dst);
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature="test"))]
|
||||
pub fn test_toml_serialize_deserialize<T>(src: T)
|
||||
where T: DeserializeOwned + Serialize + PartialEq + std::fmt::Debug
|
||||
{
|
||||
|
|
Loading…
Add table
Reference in a new issue