use std::convert::Infallible;
use std::future::Future;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::PoisonError;
use futures::channel::oneshot;
use futures::future::join_all;
use futures::future::select;
use futures::future::Either;
use futures::future::Shared;
use futures::pin_mut;
use futures::FutureExt;
use rings_core::swarm::storage_api::StoreUnconfirmed;
struct Latch {
raised: AtomicBool,
set: Mutex<Option<oneshot::Sender<()>>>,
ready: Shared<oneshot::Receiver<()>>,
current: Mutex<Option<oneshot::Sender<Infallible>>>,
}
fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) struct RegistrationReadiness {
latches: Vec<Latch>,
}
impl RegistrationReadiness {
pub(crate) fn new(tasks: usize) -> Self {
let latches = (0..tasks)
.map(|_| {
let (set, ready) = oneshot::channel();
Latch {
raised: AtomicBool::new(false),
set: Mutex::new(Some(set)),
ready: ready.shared(),
current: Mutex::new(None),
}
})
.collect();
Self { latches }
}
pub(crate) fn is_ready(&self, task: usize) -> bool {
self.latches
.get(task)
.is_some_and(|latch| latch.raised.load(Ordering::Acquire))
}
pub(crate) fn wait<R>(
self: &Arc<Self>,
task: usize,
receipts: Vec<R>,
) -> impl Future<Output = ()> + 'static
where
R: Future<Output = Result<(), StoreUnconfirmed>> + 'static,
{
let (current, superseded) = oneshot::channel::<Infallible>();
if let Some(latch) = self.latches.get(task) {
*locked(&latch.current) = Some(current);
}
let readiness = Arc::clone(self);
async move {
let stored = join_all(receipts);
pin_mut!(stored, superseded);
if let Either::Left((outcomes, _)) = select(stored, superseded).await {
if outcomes.iter().all(Result::is_ok) {
readiness.set(task);
}
}
}
}
fn set(&self, task: usize) {
let Some(latch) = self.latches.get(task) else {
return;
};
latch.raised.store(true, Ordering::Release);
if let Some(sender) = locked(&latch.set).take() {
let _ = sender.send(());
}
}
pub(crate) fn all(self: &Arc<Self>) -> impl Future<Output = ()> + 'static {
let readiness = Arc::clone(self);
let latches = join_all(self.latches.iter().map(|latch| latch.ready.clone()));
async move {
let _readiness = readiness;
latches.await;
}
}
}
#[cfg(all(test, rings_native))]
mod test_readiness;