use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError};
use id_effect::{Effect, FiberRef, Never, Stream, fail, succeed, suspend};
use crate::client::SqlClient;
use crate::error::SqlError;
use crate::row::SqlRow;
use crate::transaction::{SqlTransaction, TransactionOptions};
use crate::value::SqlValue;
pub const DEFAULT_MAX_TENANT_POOLS: usize = 64;
pub type TenantConnector =
dyn Fn(&str) -> Effect<Option<Arc<dyn SqlClient>>, SqlError> + Send + Sync;
pub type TenantClientFactory = Box<dyn Fn() -> Effect<Arc<dyn SqlClient>, SqlError> + Send + Sync>;
pub fn tenant_database<C: SqlClient + Clone>(client: C) -> TenantClientFactory {
tenant_database_from(move || succeed(Arc::new(client.clone()) as Arc<dyn SqlClient>))
}
pub fn tenant_database_from(
factory: impl Fn() -> Effect<Arc<dyn SqlClient>, SqlError> + Send + Sync + 'static,
) -> TenantClientFactory {
Box::new(factory)
}
static ROUTED_TENANT: LazyLock<FiberRef<Option<Arc<str>>>> = LazyLock::new(|| FiberRef::new(None));
#[derive(Clone)]
pub struct TenantRouter {
connector: Arc<TenantConnector>,
max_pools: usize,
pools: Arc<Mutex<Pools>>,
}
#[derive(Default)]
struct Pools {
open: HashMap<Arc<str>, Pool>,
tick: u64,
}
struct Pool {
client: Arc<dyn SqlClient>,
used: u64,
}
impl Pools {
fn get(&mut self, tenant: &str) -> Option<Arc<dyn SqlClient>> {
self.tick += 1;
let tick = self.tick;
self.open.get_mut(tenant).map(|pool| {
pool.used = tick;
Arc::clone(&pool.client)
})
}
fn insert(
&mut self,
tenant: Arc<str>,
client: Arc<dyn SqlClient>,
max: usize,
) -> (Arc<dyn SqlClient>, Vec<Arc<dyn SqlClient>>) {
if let Some(open) = self.get(&tenant) {
return (open, vec![client]);
}
let mut stale = Vec::new();
while self.open.len() >= max {
let lru = self
.open
.iter()
.min_by_key(|(_, pool)| pool.used)
.map(|(tenant, _)| Arc::clone(tenant))
.expect("at least one open client");
stale.extend(self.open.remove(&lru).map(|pool| pool.client));
}
self.open.insert(
tenant,
Pool {
client: Arc::clone(&client),
used: self.tick,
},
);
(client, stale)
}
}
impl TenantRouter {
pub fn from_resolver(
connector: impl Fn(&str) -> Effect<Option<Arc<dyn SqlClient>>, SqlError> + Send + Sync + 'static,
) -> Self {
Self {
connector: Arc::new(connector),
max_pools: DEFAULT_MAX_TENANT_POOLS,
pools: Arc::default(),
}
}
pub fn from_map<K: Into<String>>(
databases: impl IntoIterator<Item = (K, TenantClientFactory)>,
) -> Self {
let databases: HashMap<String, TenantClientFactory> = databases
.into_iter()
.map(|(tenant, factory)| (tenant.into(), factory))
.collect();
Self::from_resolver(move |tenant| match databases.get(tenant) {
Some(factory) => factory().map(Some),
None => succeed(None),
})
}
#[cfg(feature = "pg")]
pub fn from_pg_configs<K: Into<String>>(
databases: impl IntoIterator<Item = (K, crate::pg::PgPoolConfig)>,
) -> Self {
use crate::pg::{PgSqlClient, pg_pool_from_config_lazy};
Self::from_map(databases.into_iter().map(|(tenant, config)| {
let factory: TenantClientFactory =
Box::new(move || match pg_pool_from_config_lazy(config.clone()) {
Ok(pool) => succeed(Arc::new(PgSqlClient::new(pool)) as Arc<dyn SqlClient>),
Err(e) => fail(e.0),
});
(tenant, factory)
}))
}
#[must_use]
pub fn with_max_pools(mut self, max: usize) -> Self {
self.max_pools = max.max(1);
self
}
#[inline]
pub fn max_pools(&self) -> usize {
self.max_pools
}
pub fn pool_count(&self) -> usize {
self.lock().open.len()
}
pub fn open_tenants(&self) -> Vec<String> {
let mut tenants: Vec<String> = self.lock().open.keys().map(|t| t.to_string()).collect();
tenants.sort_unstable();
tenants
}
pub fn with_tenant<A, E, R>(tenant: impl AsRef<str>, effect: Effect<A, E, R>) -> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
ROUTED_TENANT.locally(Some(Arc::from(tenant.as_ref())), effect)
}
pub fn routed_tenant<E: Send + 'static, R: Send + Sync + 'static>() -> Effect<Option<String>, E, R>
{
ROUTED_TENANT
.get()
.map(|tenant: Option<Arc<str>>| tenant.map(|t| t.to_string()))
}
pub fn for_tenant(&self, tenant: impl AsRef<str>) -> TenantSqlClient {
TenantSqlClient {
router: self.clone(),
tenant: Arc::from(tenant.as_ref()),
}
}
pub fn client_for(&self, tenant: impl AsRef<str>) -> Effect<Arc<dyn SqlClient>, SqlError> {
self.client_of(Arc::from(tenant.as_ref()))
}
fn client_of(&self, tenant: Arc<str>) -> Effect<Arc<dyn SqlClient>, SqlError> {
let router = self.clone();
suspend(move || {
if let Some(open) = router.lock().get(&tenant) {
return succeed(open);
}
let found = (router.connector)(&tenant);
found.flat_map(move |found| match found {
None => fail(SqlError::NotConnected),
Some(client) => client.connect().flat_map(move |()| {
let (client, stale) = router.lock().insert(tenant, client, router.max_pools);
close_all(stale).map(move |()| client)
}),
})
})
}
fn current(&self) -> Effect<Arc<dyn SqlClient>, SqlError> {
let router = self.clone();
ROUTED_TENANT
.get()
.flat_map(move |tenant: Option<Arc<str>>| match tenant {
Some(tenant) => router.client_of(tenant),
None => fail(SqlError::NotConnected),
})
}
fn lock(&self) -> MutexGuard<'_, Pools> {
self.pools.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl fmt::Debug for TenantRouter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TenantRouter")
.field("max_pools", &self.max_pools)
.field("open", &self.pool_count())
.finish_non_exhaustive()
}
}
fn close_all<E: Send + 'static>(clients: Vec<Arc<dyn SqlClient>>) -> Effect<(), E> {
clients
.iter()
.fold(succeed::<(), Never, _>(()), |done, client| {
done.then(client.close())
})
.map_err(|never: Never| match never {})
}
fn query_on(
client: Effect<Arc<dyn SqlClient>, SqlError>,
sql: &str,
params: &[SqlValue],
) -> Effect<Vec<SqlRow>, SqlError> {
let (sql, params) = (sql.to_owned(), params.to_vec());
client.flat_map(move |c| c.query(&sql, ¶ms))
}
fn execute_on(
client: Effect<Arc<dyn SqlClient>, SqlError>,
sql: &str,
params: &[SqlValue],
) -> Effect<u64, SqlError> {
let (sql, params) = (sql.to_owned(), params.to_vec());
client.flat_map(move |c| c.execute(&sql, ¶ms))
}
fn stream_on(
client: Effect<Arc<dyn SqlClient>, SqlError>,
sql: &str,
params: &[SqlValue],
) -> Stream<SqlRow, SqlError> {
let (sql, params) = (sql.to_owned(), params.to_vec());
Stream::from_effect(client.map(|c| vec![c])).flat_map(move |c| c.query_stream(&sql, ¶ms))
}
impl SqlClient for TenantRouter {
fn connect(&self) -> Effect<(), SqlError> {
let router = self.clone();
ROUTED_TENANT
.get()
.flat_map(move |tenant: Option<Arc<str>>| match tenant {
Some(tenant) => router.client_of(tenant).map(|_| ()),
None => succeed(()),
})
}
fn query(&self, sql: &str, params: &[SqlValue]) -> Effect<Vec<SqlRow>, SqlError> {
query_on(self.current(), sql, params)
}
fn execute(&self, sql: &str, params: &[SqlValue]) -> Effect<u64, SqlError> {
execute_on(self.current(), sql, params)
}
fn begin(&self) -> Effect<Arc<dyn SqlTransaction>, SqlError> {
self.current().flat_map(|c| c.begin())
}
fn begin_with(&self, options: TransactionOptions) -> Effect<Arc<dyn SqlTransaction>, SqlError> {
self.current().flat_map(move |c| c.begin_with(options))
}
fn query_stream(&self, sql: &str, params: &[SqlValue]) -> Stream<SqlRow, SqlError> {
stream_on(self.current(), sql, params)
}
fn close(&self) -> Effect<(), Never> {
let router = self.clone();
suspend(move || {
let open: Vec<Arc<dyn SqlClient>> = router
.lock()
.open
.drain()
.map(|(_, pool)| pool.client)
.collect();
close_all(open)
})
}
}
#[derive(Clone)]
pub struct TenantSqlClient {
router: TenantRouter,
tenant: Arc<str>,
}
impl TenantSqlClient {
#[inline]
pub fn tenant(&self) -> &str {
&self.tenant
}
fn client(&self) -> Effect<Arc<dyn SqlClient>, SqlError> {
self.router.client_of(Arc::clone(&self.tenant))
}
}
impl fmt::Debug for TenantSqlClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TenantSqlClient")
.field("tenant", &self.tenant)
.finish_non_exhaustive()
}
}
impl SqlClient for TenantSqlClient {
fn connect(&self) -> Effect<(), SqlError> {
self.client().map(|_| ())
}
fn query(&self, sql: &str, params: &[SqlValue]) -> Effect<Vec<SqlRow>, SqlError> {
query_on(self.client(), sql, params)
}
fn execute(&self, sql: &str, params: &[SqlValue]) -> Effect<u64, SqlError> {
execute_on(self.client(), sql, params)
}
fn begin(&self) -> Effect<Arc<dyn SqlTransaction>, SqlError> {
self.client().flat_map(|c| c.begin())
}
fn begin_with(&self, options: TransactionOptions) -> Effect<Arc<dyn SqlTransaction>, SqlError> {
self.client().flat_map(move |c| c.begin_with(options))
}
fn query_stream(&self, sql: &str, params: &[SqlValue]) -> Stream<SqlRow, SqlError> {
stream_on(self.client(), sql, params)
}
}