//! Application-owned cache. All keys are relative and all writes replace through a sibling temp file.
use crate::Result;
use std::{
fs,
io::Write,
path::{Component, Path, PathBuf},
sync::atomic::{AtomicU64, Ordering},
time::{Duration, SystemTime},
};
static NEXT: AtomicU64 = AtomicU64::new(0);
pub fn app_cache_dir() -> Result<PathBuf> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
crate::app_dirs::directory(&std::env::vars().collect(), crate::app_dirs::Kind::Cache)
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
if let Some(path) = std::env::var_os("FMM_CACHE_DIR").filter(|p| !p.is_empty()) {
return Ok(path.into());
}
let local =
std::env::var_os("LOCALAPPDATA").ok_or("LOCALAPPDATA is not set; set FMM_CACHE_DIR")?;
Ok(PathBuf::from(local).join("werry/factoriomodmanager/cache"))
}
}
#[derive(Clone, Debug)]
pub struct Cache {
root: PathBuf,
}
impl Cache {
pub fn new(root: PathBuf) -> Self {
Self { root }
}
pub fn path(&self, key: &str) -> Result<PathBuf> {
if key.is_empty()
|| !Path::new(key)
.components()
.all(|c| matches!(c, Component::Normal(_)))
|| key.contains(':')
{
return Err("Invalid cache key".into());
}
Ok(self.root.join(key))
}
/// Remove only known disposable entries; independent settings/metadata overrides may overlap.
pub fn clear(&self) -> Result<()> {
if !self.root.exists() {
return Ok(());
}
let root = self.root.canonicalize()?;
for key in [
"description-images",
"portal-thumbs",
"full",
"catalogue.json",
"catalogue.fetched-at",
] {
let path = self.path(key)?;
let meta = match fs::symlink_metadata(&path) {
Ok(m) => m,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => return Err(e.into()),
};
if meta.file_type().is_symlink() || !path.canonicalize()?.starts_with(&root) {
return Err("Refusing cache cleanup through a link".into());
}
if meta.is_dir() {
// Cache subdirectories are flat. Refuse unexpected nested directories or links.
let files = fs::read_dir(&path)?.collect::<std::io::Result<Vec<_>>>()?;
for file in &files {
if !file.file_type()?.is_file()
|| !file.path().canonicalize()?.starts_with(&root)
{
return Err("Refusing unexpected cache directory entry".into());
}
}
for file in files {
fs::remove_file(file.path())?;
}
fs::remove_dir(&path)?;
} else {
fs::remove_file(&path)?;
}
}
Ok(())
}
pub fn read(&self, key: &str) -> Option<Vec<u8>> {
fs::read(self.path(key).ok()?).ok()
}
pub fn fresh(&self, key: &str, ttl: Duration) -> bool {
self.path(key)
.ok()
.and_then(|p| fs::metadata(p).ok())
.and_then(|m| m.modified().ok())
.and_then(|t| SystemTime::now().duration_since(t).ok())
.is_some_and(|age| age < ttl)
}
pub fn write(&self, key: &str, bytes: &[u8]) -> Result<PathBuf> {
let path = self.path(key)?;
atomic_write(&path, bytes)?;
Ok(path)
}
}
pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
let parent = path.parent().ok_or("Cache file has no parent")?;
fs::create_dir_all(parent)?;
let temp = parent.join(format!(
".fmm-{}-{}.tmp",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let result = (|| -> Result<()> {
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temp)?;
file.write_all(bytes)?;
file.sync_all()?;
drop(file);
fs::rename(&temp, path)?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(&temp);
}
result
}
/// Stable FNV-1a key; no dependency on randomized HashMap seeds across app restarts.
pub fn url_key(url: &str) -> String {
let hash = url.bytes().fold(0xcbf29ce484222325u64, |h, b| {
(h ^ u64::from(b)).wrapping_mul(0x100000001b3)
});
format!("{hash:016x}")
}