eoka 0.15.0

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
//! Small helpers shared across modules: locking, detached tasks, deadlines,
//! redaction and private file writes.

use std::future::Future;
use std::path::Path;
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))
}

/// Prints in place of a secret in `Debug` output.
pub(crate) struct Redacted;

impl std::fmt::Debug for Redacted {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("<redacted>")
    }
}

/// Query strings and fragments often carry tokens.
pub(crate) fn without_query(url: &str) -> &str {
    &url[..url.find(['?', '#']).unwrap_or(url.len())]
}

/// Atomically writes `contents` to `path`, readable only by the owner.
pub(crate) fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
    use std::io::Write;

    let name = path
        .file_name()
        .ok_or_else(|| std::io::Error::other("Path has no file name"))?
        .to_string_lossy();
    let temporary = path.with_file_name(format!(".{name}.{:016x}.tmp", fastrand::u64(..)));
    let mut options = std::fs::OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let result = options
        .open(&temporary)
        .and_then(|mut file| {
            file.write_all(contents)?;
            file.sync_all()
        })
        .and_then(|()| std::fs::rename(&temporary, path));
    if result.is_err() {
        let _ = std::fs::remove_file(&temporary);
    }
    result
}

#[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());
    }
}