fleetforge_runtime/
features.rs

1use std::sync::atomic::{AtomicBool, Ordering};
2use std::sync::OnceLock;
3
4use fleetforge_trust::TRUST_MESH_ALPHA_FLAG;
5
6static TRUST_MESH_CACHE: OnceLock<AtomicBool> = OnceLock::new();
7
8/// Checks whether the Trust Mesh alpha flag is enabled.
9pub fn trust_mesh_alpha_enabled() -> bool {
10    if let Ok(env_value) = std::env::var(TRUST_MESH_ALPHA_FLAG) {
11        return parse_bool(&env_value);
12    }
13    TRUST_MESH_CACHE
14        .get_or_init(|| AtomicBool::new(read_flag()))
15        .load(Ordering::Relaxed)
16}
17
18/// Enables or disables the Trust Mesh alpha flag for the current process.
19pub fn set_trust_mesh_alpha(enabled: bool) {
20    if enabled {
21        std::env::set_var(TRUST_MESH_ALPHA_FLAG, "1");
22    } else {
23        std::env::remove_var(TRUST_MESH_ALPHA_FLAG);
24    }
25    TRUST_MESH_CACHE
26        .get_or_init(|| AtomicBool::new(enabled))
27        .store(enabled, Ordering::Relaxed);
28}
29
30fn read_flag() -> bool {
31    std::env::var(TRUST_MESH_ALPHA_FLAG)
32        .ok()
33        .map(|value| parse_bool(&value))
34        .unwrap_or(false)
35}
36
37fn parse_bool(value: &str) -> bool {
38    matches!(
39        value.trim().to_ascii_lowercase().as_str(),
40        "1" | "true" | "yes" | "on"
41    )
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn parses_truthy_values() {
50        for value in ["1", "true", "TRUE", " yes ", "On"] {
51            assert!(parse_bool(value), "{value} should be true");
52        }
53        for value in ["0", "no", "false", "off", ""] {
54            assert!(!parse_bool(value), "{value} should be false");
55        }
56    }
57
58    #[test]
59    fn reflects_environment_flag() {
60        std::env::remove_var(TRUST_MESH_ALPHA_FLAG);
61        assert!(!trust_mesh_alpha_enabled());
62
63        std::env::set_var(TRUST_MESH_ALPHA_FLAG, "true");
64        assert!(trust_mesh_alpha_enabled());
65
66        std::env::remove_var(TRUST_MESH_ALPHA_FLAG);
67    }
68}