sylvia_iot_broker/models/
mod.rsuse std::{error::Error as StdError, sync::Arc};
use async_trait::async_trait;
pub mod application;
pub mod device;
pub mod device_route;
pub mod dldata_buffer;
pub mod network;
pub mod network_route;
pub mod unit;
mod cache_memory;
mod memory;
mod model_mongodb;
mod model_sqlite;
mod mongodb;
mod sqlite;
pub use self::{
cache_memory::{Cache as MemoryCache, Options as MemoryOptions},
memory::{
device::Options as DeviceOptions, device_route::Options as DeviceRouteOptions,
network_route::Options as NetworkRouteOptions,
},
mongodb::conn::{self as mongodb_conn, Options as MongoDbOptions},
sqlite::conn::{self as sqlite_conn, Options as SqliteOptions},
};
pub use model_mongodb::Model as MongoDbModel;
pub use model_sqlite::Model as SqliteModel;
pub enum ConnOptions {
MongoDB(MongoDbOptions),
Sqlite(SqliteOptions),
}
pub enum CacheConnOptions {
Memory {
device: DeviceOptions,
device_route: DeviceRouteOptions,
network_route: NetworkRouteOptions,
},
}
#[async_trait]
pub trait Model: Send + Sync {
async fn close(&self) -> Result<(), Box<dyn StdError>>;
fn unit(&self) -> &dyn unit::UnitModel;
fn application(&self) -> &dyn application::ApplicationModel;
fn network(&self) -> &dyn network::NetworkModel;
fn device(&self) -> &dyn device::DeviceModel;
fn device_route(&self) -> &dyn device_route::DeviceRouteModel;
fn network_route(&self) -> &dyn network_route::NetworkRouteModel;
fn dldata_buffer(&self) -> &dyn dldata_buffer::DlDataBufferModel;
}
#[async_trait]
pub trait Cache: Send + Sync {
async fn close(&self) -> Result<(), Box<dyn StdError>>;
fn device(&self) -> &dyn device::DeviceCache;
fn device_route(&self) -> &dyn device_route::DeviceRouteCache;
fn network_route(&self) -> &dyn network_route::NetworkRouteCache;
}
pub async fn new(opts: &ConnOptions) -> Result<Arc<dyn Model>, Box<dyn StdError>> {
let model: Arc<dyn Model> = match opts {
ConnOptions::MongoDB(opts) => Arc::new(MongoDbModel::new(opts).await?),
ConnOptions::Sqlite(opts) => Arc::new(SqliteModel::new(opts).await?),
};
model.unit().init().await?;
model.application().init().await?;
model.network().init().await?;
model.device().init().await?;
model.device_route().init().await?;
model.network_route().init().await?;
model.dldata_buffer().init().await?;
Ok(model)
}
pub async fn new_cache(
opts: &CacheConnOptions,
model: &Arc<dyn Model>,
) -> Result<Arc<dyn Cache>, Box<dyn StdError>> {
let cache: Arc<dyn Cache> = match opts {
CacheConnOptions::Memory {
device,
device_route,
network_route,
} => {
let opts = MemoryOptions {
device: &device,
device_route: &device_route,
network_route: &network_route,
};
Arc::new(MemoryCache::new(&opts, model))
}
};
Ok(cache)
}