use init4_bin_base::utils::from_env::FromEnv;
#[cfg(any(feature = "postgres", feature = "sqlite"))]
use signet_storage::SqlConnector;
use signet_storage::{DatabaseEnv, MdbxConnector, UnifiedStorage, builder::StorageBuilder};
use std::borrow::Cow;
use tokio_util::sync::CancellationToken;
#[derive(Debug, Clone, serde::Deserialize, FromEnv)]
pub struct StorageConfig {
#[from_env(var = "SIGNET_HOT_PATH", desc = "Path to hot MDBX storage", infallible)]
hot_path: Cow<'static, str>,
#[from_env(var = "SIGNET_COLD_PATH", desc = "Path to cold MDBX storage", infallible)]
cold_path: Cow<'static, str>,
#[from_env(
var = "SIGNET_COLD_SQL_URL",
desc = "SQL connection URL for cold storage",
infallible
)]
#[serde(default)]
cold_sql_url: Cow<'static, str>,
}
impl StorageConfig {
pub const fn new(hot_path: Cow<'static, str>, cold_path: Cow<'static, str>) -> Self {
Self { hot_path, cold_path, cold_sql_url: Cow::Borrowed("") }
}
pub fn hot_path(&self) -> &str {
&self.hot_path
}
pub fn cold_path(&self) -> &str {
&self.cold_path
}
pub fn cold_sql_url(&self) -> &str {
&self.cold_sql_url
}
pub async fn build_storage(
&self,
cancel: CancellationToken,
) -> eyre::Result<UnifiedStorage<DatabaseEnv>> {
let hot = MdbxConnector::new(self.hot_path.as_ref());
let has_mdbx = !self.cold_path.is_empty();
let has_sql = !self.cold_sql_url.is_empty();
match (has_mdbx, has_sql) {
(true, false) => Ok(StorageBuilder::new()
.hot(hot)
.cold(MdbxConnector::new(self.cold_path.as_ref()))
.cancel_token(cancel)
.build()
.await?),
#[cfg(any(feature = "postgres", feature = "sqlite"))]
(false, true) => Ok(StorageBuilder::new()
.hot(hot)
.cold(SqlConnector::new(self.cold_sql_url.as_ref()))
.cancel_token(cancel)
.build()
.await?),
#[cfg(not(any(feature = "postgres", feature = "sqlite")))]
(false, true) => {
eyre::bail!("SIGNET_COLD_SQL_URL requires the 'postgres' or 'sqlite' feature")
}
(true, true) => eyre::bail!(
"both SIGNET_COLD_PATH and SIGNET_COLD_SQL_URL are set; specify exactly one"
),
(false, false) => eyre::bail!(
"neither SIGNET_COLD_PATH nor SIGNET_COLD_SQL_URL is set; specify exactly one"
),
}
}
}