eoka 0.14.1

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
//! Chrome's version, probed with `chrome --version` once per executable.
//!
//! Spawning Chrome only to print its version costs tens of milliseconds on
//! every launch. The result is keyed by the executable's canonical path, size
//! and modification time, kept in memory and in
//! `$XDG_CACHE_HOME/eoka/chrome-version` (or `~/.cache/eoka/chrome-version`,
//! `%LOCALAPPDATA%\eoka\chrome-version`), so an updated Chrome is probed again.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use std::time::UNIX_EPOCH;

use crate::util::LockExt;

#[derive(Clone, PartialEq, Eq, Hash)]
struct Key {
    path: PathBuf,
    len: u64,
    modified_ns: u128,
}

impl Key {
    fn of(executable: &Path) -> Option<Self> {
        let path = std::fs::canonicalize(executable).ok()?;
        let metadata = std::fs::metadata(&path).ok()?;
        let modified_ns = metadata
            .modified()
            .ok()?
            .duration_since(UNIX_EPOCH)
            .ok()?
            .as_nanos();
        Some(Self {
            path,
            len: metadata.len(),
            modified_ns,
        })
    }

    /// One line: size, mtime, then the path, which may contain spaces.
    fn header(&self) -> String {
        format!("{} {} {}", self.len, self.modified_ns, self.path.display())
    }
}

fn memory() -> &'static Mutex<HashMap<Key, String>> {
    static CACHE: OnceLock<Mutex<HashMap<Key, String>>> = OnceLock::new();
    CACHE.get_or_init(Mutex::default)
}

fn cache_dir() -> Option<PathBuf> {
    let absolute =
        |value: std::ffi::OsString| Some(PathBuf::from(value)).filter(|p| p.is_absolute());
    #[cfg(windows)]
    let base = std::env::var_os("LOCALAPPDATA").and_then(absolute);
    #[cfg(not(windows))]
    let base = std::env::var_os("XDG_CACHE_HOME")
        .and_then(absolute)
        .or_else(|| {
            std::env::var_os("HOME")
                .and_then(absolute)
                .map(|home| home.join(".cache"))
        });
    Some(base?.join("eoka").join("chrome-version"))
}

fn file_for(dir: &Path, key: &Key) -> PathBuf {
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    key.path.hash(&mut hasher);
    dir.join(format!("{:016x}", hasher.finish()))
}

/// A cached `a.b.c.d` version, accepted only for exactly this key.
fn parse_entry(contents: &str, key: &Key) -> Option<String> {
    let (header, version) = contents.trim_end().split_once('\n')?;
    let valid = !version.is_empty()
        && version.split('.').count() == 4
        && version
            .split('.')
            .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()));
    (header == key.header() && valid).then(|| version.to_owned())
}

fn read_disk(dir: &Path, key: &Key) -> Option<String> {
    let contents = std::fs::read_to_string(file_for(dir, key)).ok()?;
    parse_entry(&contents, key)
}

fn write_disk(dir: &Path, key: &Key, version: &str) {
    if std::fs::create_dir_all(dir).is_err() {
        return;
    }
    let file = file_for(dir, key);
    let temporary = file.with_extension(format!("tmp{}", std::process::id()));
    let written = std::fs::write(&temporary, format!("{}\n{version}\n", key.header()))
        .and_then(|()| std::fs::rename(&temporary, &file));
    if let Err(error) = written {
        let _ = std::fs::remove_file(&temporary);
        tracing::debug!("Could not cache the Chrome version: {error}");
    }
}

/// The executable's version from the cache, or from `probe` (then cached).
pub(super) fn lookup(executable: &Path, probe: impl FnOnce() -> Option<String>) -> Option<String> {
    lookup_in(cache_dir().as_deref(), executable, probe)
}

fn lookup_in(
    dir: Option<&Path>,
    executable: &Path,
    probe: impl FnOnce() -> Option<String>,
) -> Option<String> {
    let Some(key) = Key::of(executable) else {
        return probe();
    };
    if let Some(version) = memory().lock_unpoisoned().get(&key).cloned() {
        return Some(version);
    }
    if let Some(version) = dir.and_then(|dir| read_disk(dir, &key)) {
        memory().lock_unpoisoned().insert(key, version.clone());
        return Some(version);
    }
    let version = probe()?;
    if let Some(dir) = dir {
        write_disk(dir, &key, &version);
    }
    memory().lock_unpoisoned().insert(key, version.clone());
    Some(version)
}

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

    fn key() -> Key {
        Key {
            path: PathBuf::from("/opt/chrome dir/chrome"),
            len: 42,
            modified_ns: 7,
        }
    }

    #[test]
    fn entries_match_only_their_own_executable() {
        let entry = format!("{}\n156.0.8078.80\n", key().header());
        assert_eq!(
            parse_entry(&entry, &key()).as_deref(),
            Some("156.0.8078.80")
        );
        let mut newer = key();
        newer.modified_ns = 8;
        assert_eq!(parse_entry(&entry, &newer), None);
        assert_eq!(
            parse_entry(&format!("{}\nnot-a-version\n", key().header()), &key()),
            None
        );
        assert_eq!(parse_entry("", &key()), None);
    }

    #[test]
    fn probes_once_and_reads_back_from_disk() {
        let dir = std::env::temp_dir().join(format!("eoka-version-cache-{}", fastrand::u64(..)));
        let executable = dir.join("chrome");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(&executable, b"binary").unwrap();
        let cache = dir.join("cache");
        let key = Key::of(&executable).unwrap();
        let mut probes = 0;
        let mut probe = || {
            probes += 1;
            Some("1.2.3.4".to_owned())
        };
        assert_eq!(
            lookup_in(Some(&cache), &executable, &mut probe).as_deref(),
            Some("1.2.3.4")
        );
        assert_eq!(
            lookup_in(Some(&cache), &executable, &mut probe).as_deref(),
            Some("1.2.3.4")
        );
        assert_eq!(probes, 1);
        // A new process has only the disk copy.
        memory().lock_unpoisoned().remove(&key);
        assert_eq!(
            lookup_in(Some(&cache), &executable, || None).as_deref(),
            Some("1.2.3.4")
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }
}