RTIX / src /core /utils.rs
github-actions
deploy: clean backend production release
d8ffec9
use base64::{engine::general_purpose, Engine as _};
use std::path::Path;
use tokio::fs;
use dashmap::DashMap;
use once_cell::sync::Lazy;
static HYDRATED_ASSET_CACHE: Lazy<DashMap<String, String>> = Lazy::new(DashMap::new);
pub async fn hydrate_file_to_base64(path_str: Option<String>) -> Option<String> {
let path_val = path_str?;
if path_val.starts_with("data:") || path_val.starts_with("http:") || path_val.starts_with("https:") {
return Some(path_val);
}
if let Some(cached) = HYDRATED_ASSET_CACHE.get(&path_val) {
return Some(cached.clone());
}
if !Path::new(&path_val).exists() {
return None;
}
if let Ok(bytes) = fs::read(&path_val).await {
let extension = Path::new(&path_val)
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("jpg");
let mime = match extension {
"mp4" => "video/mp4",
"png" => "image/png",
_ => "image/jpeg",
};
let base64_str = general_purpose::STANDARD.encode(bytes);
let result = format!("data:{};base64,{}", mime, base64_str);
HYDRATED_ASSET_CACHE.insert(path_val, result.clone());
Some(result)
} else {
None
}
}
/// Clears a specific entry from the hydrated asset cache.
pub fn clear_asset_cache(path: &str) {
HYDRATED_ASSET_CACHE.remove(path);
}
/// Verifies if the returned weight is within the specified deviation threshold (e.g. 0.005 for 0.5%).
pub fn verify_volumetric_integrity(
outbound_weight: f64,
return_weight: f64,
threshold_percent: f64,
) -> bool {
if outbound_weight <= 0.0 {
return true;
} // No weight recorded, bypass
let deviation = (outbound_weight - return_weight).abs();
let threshold = outbound_weight * (threshold_percent / 100.0);
deviation <= threshold
}