use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, Mutex as StdMutex, OnceLock, PoisonError};
use async_lock::{Mutex as AsyncMutex, MutexGuardArc};
use crate::core::{
CreateContextParams, CredentialsParams, Error, IntoProxySpec, ProxySpec, Result,
};
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ConnKey(Arc<str>);
impl ConnKey {
pub fn new(id: impl Into<String>) -> Self {
ConnKey(Arc::from(id.into().as_str()))
}
pub fn from_arc<T>(conn: &Arc<T>) -> Self {
ConnKey(Arc::from(format!("arc:{:p}", Arc::as_ptr(conn)).as_str()))
}
pub fn from_ptr<T>(conn: &T) -> Self {
ConnKey(Arc::from(format!("ptr:{:p}", conn as *const T).as_str()))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl From<&str> for ConnKey {
fn from(s: &str) -> Self {
ConnKey::new(s)
}
}
impl From<String> for ConnKey {
fn from(s: String) -> Self {
ConnKey::new(s)
}
}
impl From<&String> for ConnKey {
fn from(s: &String) -> Self {
ConnKey::new(s.as_str())
}
}
impl std::fmt::Display for ConnKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
type Slot = Arc<AsyncMutex<()>>;
#[derive(Default)]
struct Inner {
slots: StdMutex<HashMap<(ConnKey, String), Slot>>,
}
#[derive(Clone, Default)]
pub struct Registry(Arc<Inner>);
impl Registry {
pub fn new() -> Self {
Registry::default()
}
pub fn global() -> &'static Registry {
static GLOBAL: OnceLock<Registry> = OnceLock::new();
GLOBAL.get_or_init(Registry::new)
}
pub fn tracked_slots(&self) -> usize {
self.0
.slots
.lock()
.unwrap_or_else(PoisonError::into_inner)
.len()
}
fn slot(&self, key: &(ConnKey, String)) -> Slot {
let mut slots = self.0.slots.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(existing) = slots.get(key) {
return Arc::clone(existing);
}
let created: Slot = Arc::new(AsyncMutex::new(()));
slots.insert(key.clone(), Arc::clone(&created));
created
}
fn prune(&self, key: &(ConnKey, String)) {
let mut slots = self.0.slots.lock().unwrap_or_else(PoisonError::into_inner);
if slots
.get(key)
.is_some_and(|slot| Arc::strong_count(slot) == 1)
{
slots.remove(key);
}
}
fn prepare(
&self,
conn: ConnKey,
proxy: impl IntoProxySpec,
) -> Result<(ProxySpec, (ConnKey, String), Slot)> {
let spec = proxy.into_proxy_spec()?;
spec.check_registrable()?;
let key = (conn, spec.server().to_string());
let slot = self.slot(&key);
Ok((spec, key, slot))
}
pub async fn acquire(
&self,
conn: impl Into<ConnKey>,
proxy: impl IntoProxySpec,
) -> Result<Registration> {
let (spec, key, slot) = self.prepare(conn.into(), proxy)?;
let guard = slot.lock_arc().await;
Ok(Registration {
spec,
key,
registry: self.clone(),
guard: Some(guard),
})
}
pub fn acquire_blocking(
&self,
conn: impl Into<ConnKey>,
proxy: impl IntoProxySpec,
) -> Result<Registration> {
let (spec, key, slot) = self.prepare(conn.into(), proxy)?;
let guard = slot.lock_arc_blocking();
Ok(Registration {
spec,
key,
registry: self.clone(),
guard: Some(guard),
})
}
}
impl std::fmt::Debug for Registry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Registry")
.field("tracked_slots", &self.tracked_slots())
.finish()
}
}
#[derive(Debug)]
#[must_use = "the slot is released as soon as this is dropped — hold it across \
BOTH commands, or another task can register over you"]
pub struct Registration {
spec: ProxySpec,
key: (ConnKey, String),
registry: Registry,
guard: Option<MutexGuardArc<()>>,
}
impl Registration {
pub fn spec(&self) -> &ProxySpec {
&self.spec
}
pub fn server(&self) -> &str {
self.spec.server()
}
pub fn credentials_params(&self) -> CredentialsParams<'_> {
self.spec.credentials_params()
}
pub fn create_context_params(&self) -> CreateContextParams<'_> {
self.spec.create_context_params()
}
}
impl Drop for Registration {
fn drop(&mut self) {
self.guard.take();
self.registry.prune(&self.key);
}
}
pub async fn proxy_registration(
conn: impl Into<ConnKey>,
proxy: impl IntoProxySpec,
) -> Result<Registration> {
Registry::global().acquire(conn, proxy).await
}
pub fn proxy_registration_blocking(
conn: impl Into<ConnKey>,
proxy: impl IntoProxySpec,
) -> Result<Registration> {
Registry::global().acquire_blocking(conn, proxy)
}
pub async fn with_proxy_registration<P, F, Fut, T, E>(
conn: impl Into<ConnKey>,
proxy: P,
body: F,
) -> Result<T, E>
where
P: IntoProxySpec,
F: FnOnce(ProxySpec) -> Fut,
Fut: Future<Output = Result<T, E>>,
E: From<Error>,
{
let registration = proxy_registration(conn, proxy).await.map_err(E::from)?;
let out = body(registration.spec().clone()).await;
drop(registration);
out
}
pub fn with_proxy_registration_blocking<P, F, T, E>(
conn: impl Into<ConnKey>,
proxy: P,
body: F,
) -> Result<T, E>
where
P: IntoProxySpec,
F: FnOnce(&ProxySpec) -> Result<T, E>,
E: From<Error>,
{
let registration = proxy_registration_blocking(conn, proxy).map_err(E::from)?;
let out = body(registration.spec());
drop(registration);
out
}