Skip to main content

leenfetch_core/
lib.rs

1pub mod cache;
2pub mod config;
3pub mod core;
4pub mod modules;
5pub mod system_info;
6#[cfg(test)]
7pub mod test_utils;
8
9pub use system_info::{SystemInfo, PROTOCOL_VERSION};
10
11use anyhow::Result;
12use cache::Cache;
13use config::settings::Config;
14use core::Core;
15use std::sync::{LazyLock, Mutex};
16
17static SYSTEM_INFO_CACHE: LazyLock<Cache<SystemInfo>> = LazyLock::new(|| Cache::new(5));
18static CACHE_MUTEX: Mutex<()> = Mutex::new(());
19
20/// Collects system information using the provided configuration and returns the stable JSON model.
21/// Results are cached for 5 seconds to avoid redundant computation on quick successive calls.
22pub fn gather_system_info(config: &Config) -> Result<SystemInfo> {
23    // Use a lock to prevent cache stampede
24    let _lock = CACHE_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
25
26    // Create a cache key based on config (flags and layout)
27    let cache_key = format!("{:?}_{:?}", config.flags, config.layout.len());
28
29    // Try to get from cache
30    let system_info = SYSTEM_INFO_CACHE.get_or_compute(&cache_key, || {
31        let mut effective = config.clone();
32        if effective.layout.is_empty() {
33            effective.layout = crate::config::default_layout();
34        }
35
36        let core = Core::new_with(effective.flags.clone(), effective.layout.clone());
37        let data = core.collect_data();
38        SystemInfo::from(data)
39    });
40
41    Ok(system_info.clone())
42}
43
44/// Clears the system info cache. Useful for testing or when fresh data is needed.
45pub fn clear_system_info_cache() {
46    SYSTEM_INFO_CACHE.clear();
47}