use std::{
future::Future,
sync::{Arc, RwLock},
time::Duration,
};
use cortexkit_bus_nats::NatsConnection;
use tokio::sync::watch;
use crate::{BusClient, Error, Result};
#[derive(Clone)]
pub(crate) struct ConnectionBinding {
connection: Arc<RwLock<NatsConnection>>,
changes: watch::Receiver<u64>,
bound: Option<NatsConnection>,
#[cfg(test)]
pub(crate) bucket_watch_capacity_warnings: usize,
}
impl ConnectionBinding {
pub(crate) fn new(client: &BusClient) -> Self {
Self {
connection: client.connection.clone(),
changes: client.connection_changes(),
bound: None,
#[cfg(test)]
bucket_watch_capacity_warnings: 0,
}
}
pub(crate) fn snapshot(&self) -> NatsConnection {
self.connection
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
pub(crate) fn has_changed(&self) -> bool {
self.changes.has_changed().unwrap_or(false)
}
pub(crate) async fn changed(&mut self) -> Result<()> {
self.changes
.changed()
.await
.map_err(|_| Error::Transport("credential maintenance stopped".into()))
}
pub(crate) async fn bind<T, F, Fut>(&mut self, mut open: F) -> Result<T>
where
F: FnMut(NatsConnection) -> Fut,
Fut: Future<Output = Result<T>>,
{
loop {
self.changes.borrow_and_update();
let connection = self.snapshot();
let result = open(connection.clone()).await;
if self.has_changed() {
continue;
}
match result {
Ok(value) => {
self.bound = Some(connection);
return Ok(value);
}
Err(error) => wait_for_replacement(&mut self.changes, &connection, error).await?,
}
}
}
pub(crate) async fn recover(&mut self, error: Error) -> Result<()> {
match &self.bound {
Some(connection) => wait_for_replacement(&mut self.changes, connection, error).await,
None => Err(error),
}
}
}
async fn wait_for_replacement(
changes: &mut watch::Receiver<u64>,
connection: &NatsConnection,
error: Error,
) -> Result<()> {
if !has_ended(connection).await {
return Err(error);
}
changes.changed().await.map_err(|_| error)
}
async fn has_ended(connection: &NatsConnection) -> bool {
matches!(
tokio::time::timeout(Duration::from_millis(50), connection.client().flush()).await,
Ok(Err(_))
)
}