File size: 1,891 Bytes
bad8640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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
}