use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
#[cfg(feature = "postgres")]
use std::time::Duration;
use arc_swap::ArcSwap;
use async_trait::async_trait;
use claviron_runtime::AppState;
use claviron_runtime::Register;
use claviron_runtime::congif::{self, ConfigFile, Configurable};
use claviron_runtime::registry::{Bootable, Component, Reloadable, priority};
#[cfg(any(feature = "postgres", feature = "mysql"))]
use sqlx::Connection;
#[cfg(feature = "mysql")]
use sqlx::mysql::MySqlConnectOptions;
#[cfg(feature = "postgres")]
use sqlx::postgres::PgConnectOptions;
#[cfg(feature = "mysql")]
use sqlx::{MySqlConnection, MySqlPool};
#[cfg(feature = "postgres")]
use sqlx::{PgConnection, PgPool};
use tracing::info;
use crate::config::DbFileConfig;
use crate::error::Result;
#[derive(Default)]
pub struct DbState {
#[cfg(feature = "postgres")]
pub postgres: HashMap<String, PgPool>,
#[cfg(feature = "postgres")]
pub postgres_statement_timeout: HashMap<String, Duration>,
#[cfg(feature = "mysql")]
pub mysql: HashMap<String, MySqlPool>,
#[cfg(feature = "sqlite")]
pub sqlite: HashMap<String, sqlx::SqlitePool>,
pub hosting: String,
}
#[derive(Clone)]
pub enum Pool {
#[cfg(feature = "postgres")]
Postgres(PgPool),
#[cfg(feature = "mysql")]
MySql(MySqlPool),
#[cfg(feature = "sqlite")]
Sqlite(sqlx::SqlitePool),
}
pub struct DbService {
config_path: PathBuf,
initial_config: Option<DbFileConfig>,
state: ArcSwap<DbState>,
}
impl DbService {
pub fn empty(config_path: PathBuf) -> Self {
Self {
config_path,
initial_config: None,
state: ArcSwap::from_pointee(DbState::default()),
}
}
pub fn from_config(config: DbFileConfig) -> Self {
Self { initial_config: Some(config), ..Self::empty(PathBuf::new()) }
}
#[cfg(feature = "postgres")]
pub fn postgres(&self) -> Option<PgPool> {
self.postgres_named("default")
}
#[cfg(feature = "postgres")]
pub fn postgres_named(
&self,
name: &str,
) -> Option<PgPool> {
self.state.load().postgres.get(name).cloned()
}
#[cfg(feature = "postgres")]
pub fn postgres_statement_timeout(
&self,
name: &str,
) -> Option<Duration> {
self.state.load().postgres_statement_timeout.get(name).copied()
}
#[cfg(feature = "postgres")]
pub fn postgres_options(&self) -> Option<Arc<PgConnectOptions>> {
self.postgres_named_options("default")
}
#[cfg(feature = "postgres")]
pub fn postgres_named_options(
&self,
name: &str,
) -> Option<Arc<PgConnectOptions>> {
self.state.load().postgres.get(name).map(|p| p.connect_options())
}
#[cfg(feature = "postgres")]
pub async fn postgres_connection(
&self
) -> Option<sqlx::Result<PgConnection>> {
self.postgres_named_connection("default").await
}
#[cfg(feature = "postgres")]
pub async fn postgres_named_connection(
&self,
name: &str,
) -> Option<sqlx::Result<PgConnection>> {
let opts = self.postgres_named_options(name)?;
Some(PgConnection::connect_with(&opts).await)
}
#[cfg(feature = "postgres")]
pub fn claviron_pool(&self) -> Option<PgPool> {
self.postgres()
}
#[cfg(feature = "postgres")]
pub fn claviron_options(&self) -> Option<Arc<PgConnectOptions>> {
self.postgres_options()
}
#[cfg(feature = "postgres")]
pub async fn claviron_connection(
&self
) -> Option<sqlx::Result<PgConnection>> {
self.postgres_connection().await
}
#[cfg(feature = "mysql")]
pub fn mysql(&self) -> Option<MySqlPool> {
self.mysql_named("default")
}
#[cfg(feature = "mysql")]
pub fn mysql_named(
&self,
name: &str,
) -> Option<MySqlPool> {
self.state.load().mysql.get(name).cloned()
}
pub fn profile(
&self,
profile: &str,
) -> std::result::Result<Pool, String> {
let (backend, name) = profile.split_once('.').ok_or_else(|| {
format!("`{profile}` is not <backend>.<name>, as postgres.default")
})?;
let missing = || format!("db.yaml declares no `{profile}`");
match backend {
#[cfg(feature = "postgres")]
"postgres" => self
.postgres_named(name)
.map(Pool::Postgres)
.ok_or_else(missing),
#[cfg(feature = "mysql")]
"mysql" => {
self.mysql_named(name).map(Pool::MySql).ok_or_else(missing)
}
#[cfg(feature = "sqlite")]
"sqlite" => {
self.sqlite_named(name).map(Pool::Sqlite).ok_or_else(missing)
}
other => {
Err(format!("`{profile}`: this build has no {other} backend"))
}
}
}
pub fn hosting_profile(&self) -> String {
self.state.load().hosting.clone()
}
#[cfg(feature = "sqlite")]
pub fn sqlite_named(
&self,
name: &str,
) -> Option<sqlx::SqlitePool> {
self.state.load().sqlite.get(name).cloned()
}
#[cfg(feature = "mysql")]
pub fn mysql_options(&self) -> Option<Arc<MySqlConnectOptions>> {
self.mysql_named_options("default")
}
#[cfg(feature = "mysql")]
pub fn mysql_named_options(
&self,
name: &str,
) -> Option<Arc<MySqlConnectOptions>> {
self.state.load().mysql.get(name).map(|p| p.connect_options())
}
#[cfg(feature = "mysql")]
pub async fn mysql_connection(
&self
) -> Option<sqlx::Result<MySqlConnection>> {
self.mysql_named_connection("default").await
}
#[cfg(feature = "mysql")]
pub async fn mysql_named_connection(
&self,
name: &str,
) -> Option<sqlx::Result<MySqlConnection>> {
let opts = self.mysql_named_options(name)?;
Some(MySqlConnection::connect_with(&opts).await)
}
async fn rebuild(
&self,
state: &AppState,
) -> Result<()> {
let new_state = if let Some(config) = &self.initial_config {
build_state(config, state)?
} else {
let config = state.config_reader().snapshot::<Self>()?;
build_state(&config, state)?
};
self.state.store(Arc::new(new_state));
Ok(())
}
async fn boot_pools(
&self,
state: &AppState,
) -> claviron_runtime::registry::Result<()> {
self.rebuild(state).await.map_err(|e| {
claviron_runtime::registry::Error::msg(format!(
"DbService boot: {e}"
))
})?;
Ok(())
}
}
impl Component<AppState> for DbService {
type Deps = ();
fn name(&self) -> &'static str {
"DbService"
}
fn boot_priority(&self) -> Option<u8> {
Some(priority::FIRST)
}
fn as_reloadable(&self) -> Option<&dyn Reloadable<AppState>> {
self.initial_config.is_none().then_some(self)
}
fn as_configurable(&self) -> Option<&dyn congif::ConfigRegistration> {
self.initial_config.is_none().then_some(self)
}
fn as_bootable(&self) -> Option<&dyn Bootable<AppState, Self::Deps>> {
Some(self)
}
}
#[async_trait]
impl Bootable<AppState> for DbService {
async fn boot(
&self,
_deps: (),
state: &AppState,
) -> claviron_runtime::registry::Result<()> {
self.boot_pools(state).await
}
}
#[async_trait]
impl Configurable for DbService {
type Config = DbFileConfig;
fn source(&self) -> ConfigFile {
ConfigFile::yaml(&self.config_path)
}
async fn configure(
&self,
_config: &DbFileConfig,
) -> congif::Result<()> {
Ok(())
}
}
#[async_trait]
impl Reloadable<AppState> for DbService {
fn priority(&self) -> Option<u8> {
Some(priority::FIRST)
}
async fn reload(
&self,
state: &AppState,
) -> claviron_runtime::registry::Result<()> {
self.rebuild(state).await.map_err(|e| {
claviron_runtime::registry::Error::msg(format!(
"DbService reload: {e}"
))
})?;
Ok(())
}
}
#[derive(Clone, Debug)]
#[cfg(feature = "postgres")]
pub struct PostgresConnected {
pub entry: String,
}
#[cfg(feature = "postgres")]
impl claviron_runtime::events::Event for PostgresConnected {}
fn db_config_path(state: &AppState) -> PathBuf {
state.config_dir().join("db.yaml")
}
impl Register<AppState> for DbService {
fn register(state: &AppState) -> claviron_runtime::registry::Result<()> {
if state.registry_ref().resolve::<Self>().is_some() {
return Ok(());
}
state.bind_config_environment::<Self>()?;
state
.registry_ref()
.register(Arc::new(Self::empty(db_config_path(state))))?;
Ok(())
}
}
pub fn register(state: &AppState) -> claviron_runtime::registry::Result<()> {
<DbService as Register<AppState>>::register(state)
}
pub fn register_with_config(
state: &AppState,
config: DbFileConfig,
) -> claviron_runtime::registry::Result<()> {
state.registry_ref().register(Arc::new(DbService::from_config(config)))?;
Ok(())
}
fn build_state(
cfg: &DbFileConfig,
#[cfg_attr(
not(any(feature = "postgres", feature = "sqlite")),
allow(unused_variables)
)]
app: &AppState,
) -> Result<DbState> {
let mut state = DbState::default();
#[cfg(feature = "postgres")]
for (name, entry) in &cfg.postgres.entries {
let bus = app.events().bus().clone();
let entry_name = name.clone();
let on_connect: crate::postgres::ConnectHook = Arc::new(move || {
bus.emit(PostgresConnected { entry: entry_name.clone() });
});
state.postgres.insert(
name.clone(),
crate::postgres::build_pool_notifying(
name,
entry,
Some(on_connect),
)?,
);
if let Some(timeout) = entry.pool.statement_timeout {
state.postgres_statement_timeout.insert(name.clone(), timeout);
}
}
#[cfg(feature = "mysql")]
for (name, entry) in &cfg.mysql.entries {
state
.mysql
.insert(name.clone(), crate::mysql::build_pool(name, entry)?);
}
#[cfg(feature = "sqlite")]
{
let checking = app
.registry_ref()
.resolve::<claviron_runtime::ConfigCheck>()
.is_some();
for (name, entry) in &cfg.sqlite {
state.sqlite.insert(
name.clone(),
crate::sqlite::build_pool(name, entry, checking)?,
);
}
}
state.hosting = cfg.hosting.clone().unwrap_or_else(|| {
if cfg!(feature = "postgres") {
"postgres.default".to_owned()
} else {
"sqlite.default".to_owned()
}
});
if app.is_worker() {
tracing::debug!("DbService state built");
} else {
info!("DbService state built");
}
Ok(state)
}
#[cfg(test)]
#[path = "../tests/provider.rs"]
mod tests;