open-net 0.3.2

A cross-platform async networking library with WebSocket clients and network status monitoring.
Documentation
//! User callbacks run outside the network runtime, including initial notifications.

mod data_callback_pool;
mod data_callback_worker;
mod data_callback_worker_lease;
pub(super) use data_callback_pool::DataCallbackPool;

use crate::common::log::log_def::LogType;
use std::future::Future;
use std::io;
use std::panic::{catch_unwind, AssertUnwindSafe};
use tokio_util::sync::CancellationToken;

/// The injectable dispatch boundary reports queue/thread rejection to the caller.
/// Callback captures and completion guards are released if dispatch is rejected.
pub(super) fn try_start_user_callback_with<F, S>(
    thread_name: &'static str,
    callback: F,
    spawn: S,
) -> io::Result<impl Future<Output = ()> + Send>
where
    F: FnOnce() + Send + 'static,
    S: FnOnce(Box<dyn FnOnce() + Send>) -> io::Result<()>,
{
    crate::log_t!(LogType::WSC; "ws.callback_executor.try_start_user_callback_with", "thread_name|arg_callback_present|arg_spawn_present", thread_name, true, true);
    let completed = CancellationToken::new();
    // Create before spawn so rejection and callback unwinding also release waiters.
    let completion_guard = completed.clone().drop_guard();
    let task = Box::new(move || {
        let _completion_guard = completion_guard;
        if catch_unwind(AssertUnwindSafe(callback)).is_err() {
            crate::log_e!(LogType::WSC; "ws.callback_executor.try_start_user_callback_with", "thread_name|error", thread_name, "user_callback_panicked");
        }
        crate::log_s!(LogType::WSC; "ws.callback_executor.try_start_user_callback_with", "thread_name|state", thread_name, "callback_finished");
    });
    if let Err(error) = spawn(task) {
        crate::log_e!(LogType::WSC; "ws.callback_executor.try_start_user_callback_with", "thread_name|kind", thread_name, format!("{:?}", error.kind()));
        return Err(error);
    }
    Ok(async move { completed.cancelled().await })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::module::ws_client::test_support::{check, check_eq, TestResult};
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;
    use std::time::Duration;

    #[tokio::test]
    async fn rejected_data_spawn_returns_the_original_error_and_releases_captures() -> TestResult {
        let called = Arc::new(AtomicBool::new(false));
        let callback_called = Arc::clone(&called);
        let released = CancellationToken::new();
        let guard = released.clone().drop_guard();
        let started = try_start_user_callback_with(
            "rejected-data-callback-test",
            move || {
                let _guard = guard;
                callback_called.store(true, Ordering::SeqCst);
            },
            |task| {
                drop(task);
                Err(io::Error::from(io::ErrorKind::WouldBlock))
            },
        );
        check!(!called.load(Ordering::SeqCst))?;
        check!(released.is_cancelled())?;
        match started {
            Err(error) => check_eq!(error.kind(), io::ErrorKind::WouldBlock)?,
            Ok(_) => {
                return Err(
                    io::Error::other("rejected data callback was reported as started").into(),
                )
            }
        }
        Ok(())
    }

    #[test]
    fn dropping_waiter_still_runs_callback_on_a_runtime_free_thread() -> TestResult {
        let caller = std::thread::current().id();
        let (observed_tx, observed_rx) = std::sync::mpsc::channel();
        let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
        drop(try_start_user_callback_with(
            "detached-callback-test",
            move || {
                // The sender is dropped only after the waiter, so completion proves the
                // submitted callback survives even when nobody polls its future.
                let _ = release_rx.recv();
                let _ = observed_tx.send((
                    std::thread::current().id(),
                    tokio::runtime::Handle::try_current().is_ok(),
                ));
            },
            |task| std::thread::Builder::new().spawn(task).map(drop),
        )?);
        drop(release_tx);
        let (callback_thread, has_runtime) = observed_rx.recv_timeout(Duration::from_secs(5))?;
        check!(callback_thread != caller)?;
        check!(!has_runtime)?;
        Ok(())
    }

    #[tokio::test]
    async fn successful_callback_releases_completion_after_return() -> TestResult {
        let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
        let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
        let called = Arc::new(AtomicBool::new(false));
        let callback_called = Arc::clone(&called);
        let completed = try_start_user_callback_with(
            "completion-callback-test",
            move || {
                let _ = entered_tx.send(());
                let _ = release_rx.recv();
                callback_called.store(true, Ordering::SeqCst);
            },
            |task| std::thread::Builder::new().spawn(task).map(drop),
        )?;
        tokio::pin!(completed);
        tokio::time::timeout(Duration::from_secs(2), entered_rx).await??;
        check!(futures::poll!(&mut completed).is_pending())?;
        check_eq!(called.load(Ordering::SeqCst), false)?;
        drop(release_tx);
        tokio::time::timeout(Duration::from_secs(2), completed).await?;
        check!(called.load(Ordering::SeqCst))?;
        Ok(())
    }
}