use std::collections::HashMap;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use isothrum_runner::BoxFuture;
use tokio::sync::Mutex;
use crate::proto::Command;
use crate::{Client, ClientError, Followed};
type Connect<C> = Box<dyn Fn(PathBuf) -> BoxFuture<'static, Result<C, ClientError>> + Send + Sync>;
pub struct Pool<C = Client> {
clients: Mutex<HashMap<PathBuf, Arc<C>>>,
connect: Connect<C>,
}
impl<C> std::fmt::Debug for Pool<C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Pool").finish_non_exhaustive()
}
}
impl Pool<Client> {
#[must_use]
pub fn new(binary: Option<PathBuf>) -> Pool<Client> {
Pool::with(move |home| {
let binary = binary.clone();
Box::pin(async move { Client::connect_exact(&home, binary.as_deref()).await })
})
}
}
impl<C: Send + Sync + 'static> Pool<C> {
pub fn with(connect: impl Fn(PathBuf) -> BoxFuture<'static, Result<C, ClientError>> + Send + Sync + 'static) -> Pool<C> {
Pool {
clients: Mutex::new(HashMap::new()),
connect: Box::new(connect),
}
}
pub async fn client(&self, home: &Path) -> Result<Arc<C>, ClientError> {
let mut clients = self.clients.lock().await;
if let Some(client) = clients.get(home) {
return Ok(Arc::clone(client));
}
let client = Arc::new((self.connect)(home.to_path_buf()).await?);
clients.insert(home.to_path_buf(), Arc::clone(&client));
Ok(client)
}
pub async fn forget(&self, home: &Path) {
self.clients.lock().await.remove(home);
}
pub async fn retain(&self, keep: impl Fn(&Path) -> bool) {
self.clients.lock().await.retain(|home, _| keep(home));
}
pub async fn call<T, F>(&self, home: &Path, ask: impl Fn(Arc<C>) -> F) -> Result<T, ClientError>
where
F: Future<Output = Result<T, ClientError>>,
{
self.call_then(home, &ask, |client, _| ask(client)).await
}
async fn call_then<T, F, G>(&self, home: &Path, ask: impl FnOnce(Arc<C>) -> F, again: impl FnOnce(Arc<C>, ClientError) -> G) -> Result<T, ClientError>
where
F: Future<Output = Result<T, ClientError>>,
G: Future<Output = Result<T, ClientError>>,
{
match ask(self.client(home).await?).await {
Err(e) if e.is_broken() => {
tracing::info!(home = %home.display(), error = %e, "the service's connection broke: connecting again");
self.forget(home).await;
let again = again(self.client(home).await?, e).await;
if again.as_ref().is_err_and(ClientError::is_broken) {
self.forget(home).await;
}
again
}
done => done,
}
}
}
impl Pool<Client> {
pub async fn follow(&self, home: &Path, command: Command) -> Result<Followed, ClientError> {
let first = command.clone();
self.call_then(
home,
|client| async move { client.follow(first).await },
|client, why| async move {
match why {
ClientError::Unanswered => client.follow_again(command).await,
_ => client.follow(command).await,
}
},
)
.await
}
}
#[cfg(test)]
mod tests;