eoka 0.12.1

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
//! Small concurrency helpers shared across modules.

use std::future::Future;
use std::sync::{Mutex, MutexGuard};
use std::time::Duration;

use tokio::task::JoinHandle;
use tokio::time::Instant;

/// Locking that tolerates poisoning. eoka's shared state stays consistent
/// across a panicking holder, so the guard is recovered instead of propagating
/// the panic into unrelated callers.
pub(crate) trait LockExt<T> {
    fn lock_unpoisoned(&self) -> MutexGuard<'_, T>;
}

impl<T> LockExt<T> for Mutex<T> {
    fn lock_unpoisoned(&self) -> MutexGuard<'_, T> {
        self.lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }
}

/// Spawn `future` on the current Tokio runtime, if there is one. Used by
/// `Drop` implementations, which cannot await their asynchronous cleanup.
pub(crate) fn spawn_detached<F>(future: F) -> Option<JoinHandle<F::Output>>
where
    F: Future + Send + 'static,
    F::Output: Send + 'static,
{
    tokio::runtime::Handle::try_current()
        .ok()
        .map(|runtime| runtime.spawn(future))
}

/// `start + timeout`, saturating a timeout too large for an `Instant` to
/// roughly 30 years, as `tokio::time::timeout` does.
pub(crate) fn deadline_after(start: Instant, timeout: Duration) -> Instant {
    start
        .checked_add(timeout)
        .unwrap_or_else(|| start + Duration::from_secs(86_400 * 365 * 30))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn deadline_after_saturates_oversized_timeouts() {
        let start = Instant::now();
        let short = Duration::from_secs(5);
        assert_eq!(deadline_after(start, short), start + short);
        assert!(deadline_after(start, Duration::MAX) > start + short);
    }

    #[test]
    fn lock_unpoisoned_recovers_a_poisoned_mutex() {
        let mutex = std::sync::Arc::new(Mutex::new(1));
        let poisoner = std::sync::Arc::clone(&mutex);
        let _ = std::thread::spawn(move || {
            let _guard = poisoner.lock().unwrap();
            panic!("poison");
        })
        .join();
        assert!(mutex.is_poisoned());
        assert_eq!(*mutex.lock_unpoisoned(), 1);
    }

    #[test]
    fn spawn_detached_needs_a_runtime() {
        assert!(spawn_detached(async {}).is_none());
    }
}