rings-node 1.0.0-pre.6

Rings is a browser-native, structured peer-to-peer network: browser tabs and native daemons find each other by DID and talk over WebRTC, routed by a Chord DHT.
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::Mutex;
use std::task::Context;
use std::task::Poll;

use rings_core::delegation::DelegateeKey;
use tokio::task::AbortHandle;
use tokio::task::JoinError;
use tokio::task::JoinSet;

use crate::error::Result;
use crate::extension::ext::Extensions;
use crate::extension::ext::Scope;
use crate::processor::ProcessorBuilder;
use crate::processor::ProcessorConfig;
use crate::sync_lock::lock;

/// A `namespace` scope over a fresh processor keyed by `delegatee_key`.
///
/// Pre: called inside a Tokio runtime, which the processor's swarm workers start on.
pub(crate) fn test_scope(delegatee_key: DelegateeKey, namespace: &str) -> Result<Scope> {
    let config = ProcessorConfig::new(1, String::new(), delegatee_key, 1);
    let processor = ProcessorBuilder::from_config(&config)?
        .advertise_presence(false)
        .build()?;
    let extensions = Extensions::new(Arc::new(processor));
    Ok(Scope::new(extensions.core(), namespace.to_string()))
}

/// Run `work` on a thread with no entered runtime and return its result.
///
/// Witnesses the "no runtime" branch of a boundary that acquires a `Spawner` before it claims
/// a resource; borrowed fixtures stay usable because the thread is scoped.
pub(crate) fn without_runtime<T: Send>(work: impl FnOnce() -> T + Send) -> T {
    std::thread::scope(|scope| {
        scope
            .spawn(|| {
                assert!(rings_runtime::Spawner::current().is_err());
                work()
            })
            .join()
            .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
    })
}

/// Awaitable witness that blocks effects for the first observed key until explicitly released.
pub(crate) struct BlockingSendProbe<K> {
    blocked: AtomicBool,
    released: AtomicBool,
    blocked_key: Mutex<Option<K>>,
    entered: tokio::sync::Notify,
    release: tokio::sync::Notify,
}

impl<K> Default for BlockingSendProbe<K> {
    fn default() -> Self {
        Self {
            blocked: AtomicBool::new(false),
            released: AtomicBool::new(false),
            blocked_key: Mutex::new(None),
            entered: tokio::sync::Notify::new(),
            release: tokio::sync::Notify::new(),
        }
    }
}

impl<K> BlockingSendProbe<K>
where K: Clone + Eq
{
    /// Block every invocation carrying the first observed key.
    pub(crate) async fn block_key(&self, key: K) -> Result<()> {
        if !self.register(key)? {
            return Ok(());
        }
        self.wait_for_release().await;
        Ok(())
    }

    /// Claim an empty probe for `key`; whether `key` is the claimed key.
    fn register(&self, key: K) -> Result<bool> {
        let mut blocked_key = lock(&self.blocked_key)?;
        if blocked_key.is_none() {
            *blocked_key = Some(key.clone());
            self.blocked.store(true, Ordering::Release);
            self.entered.notify_one();
        }
        Ok(blocked_key.as_ref() == Some(&key))
    }

    async fn wait_for_release(&self) {
        while !self.released.load(Ordering::Acquire) {
            let released = self.release.notified();
            if self.released.load(Ordering::Acquire) {
                return;
            }
            released.await;
        }
    }

    pub(crate) async fn wait_until_blocked(&self) {
        while !self.blocked.load(Ordering::Acquire) {
            let entered = self.entered.notified();
            if self.blocked.load(Ordering::Acquire) {
                return;
            }
            entered.await;
        }
    }

    pub(crate) fn release(&self) {
        self.released.store(true, Ordering::Release);
        self.release.notify_waiters();
    }
}

/// A task a test owns: it runs on the current runtime until it ends or its handle drops, which
/// aborts it. So a test spawns nothing detached either, and the one-spawn law of
/// `crate::tasks` holds in test builds too. A [`JoinSet`] of that one task, awaited for the
/// task's result as a `JoinHandle` is.
pub(crate) struct TestTask<T> {
    /// The set holding the task, which aborts it when dropped.
    set: JoinSet<T>,
    /// The task's handle in the set.
    handle: AbortHandle,
}

impl<T: Send + 'static> TestTask<T> {
    /// Run `task` on the current runtime, owned by the returned handle.
    ///
    /// Pre: called inside a Tokio runtime.
    pub(crate) fn spawn(task: impl Future<Output = T> + Send + 'static) -> Self {
        let mut set = JoinSet::new();
        let handle = set.spawn(task);
        Self { set, handle }
    }
}

impl<T> TestTask<T> {
    /// Whether the task has ended, by completing, panicking or being aborted.
    pub(crate) fn is_finished(&self) -> bool {
        self.handle.is_finished()
    }

    /// Abort the task; awaiting it then yields a cancelled [`JoinError`], unless it had ended.
    pub(crate) fn abort(&self) {
        self.handle.abort();
    }
}

impl<T: 'static> Future for TestTask<T> {
    type Output = std::result::Result<T, JoinError>;

    /// The task's result, once; a handle whose result was taken never yields again.
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match self.set.poll_join_next(cx) {
            Poll::Ready(Some(result)) => Poll::Ready(result),
            Poll::Ready(None) | Poll::Pending => Poll::Pending,
        }
    }
}