use tokio::sync::mpsc;
use tokio::time::{Duration, sleep};
pub async fn add_to_tx_with_retry<T>(
tx: &mpsc::Sender<T>,
message: &T,
from_location: &str,
to_location: &str,
) where
T: Clone + Send + Sync,
{
let mut attempts = 0;
let max_attempts = 5;
loop {
match tx.try_send(message.clone()) {
Ok(_) => {
break;
}
Err(mpsc::error::TrySendError::Full(_)) => {
attempts += 1;
if attempts >= max_attempts {
log::error!(
"Failed to add message to TX channel from {from_location} to {to_location} after {max_attempts} attempts"
);
break;
}
sleep(Duration::from_millis(100 * 2u64.pow(attempts))).await;
}
Err(mpsc::error::TrySendError::Closed(_)) => {
log::error!(
"TX channel is closed. Cannot send message from {from_location} to {to_location}"
);
break;
}
}
}
}