statsig_rust/
statsig_global.rs

1use crate::log_d;
2use arc_swap::ArcSwap;
3use parking_lot::Mutex;
4use std::sync::{Arc, OnceLock};
5use tokio::runtime::Runtime;
6
7const TAG: &str = "StatsigGlobal";
8
9static ONCE: OnceLock<ArcSwap<StatsigGlobal>> = OnceLock::new();
10
11pub struct StatsigGlobal {
12    pub tokio_runtime: Mutex<Option<Arc<Runtime>>>,
13    pub pid: u32,
14}
15
16impl StatsigGlobal {
17    pub fn get() -> Arc<StatsigGlobal> {
18        let ptr = ONCE.get_or_init(|| ArcSwap::from_pointee(StatsigGlobal::new()));
19
20        if ptr.load().pid != current_pid() {
21            ptr.store(Arc::new(StatsigGlobal::new()));
22        }
23
24        ptr.load().clone()
25    }
26
27    pub fn reset() {
28        log_d!(TAG, "Resetting StatsigGlobal");
29        let mut did_init = false;
30
31        let ptr = ONCE.get_or_init(|| {
32            did_init = true;
33            ArcSwap::from_pointee(StatsigGlobal::new())
34        });
35
36        if did_init {
37            return;
38        }
39
40        ptr.store(Arc::new(StatsigGlobal::new()));
41    }
42
43    fn new() -> Self {
44        Self {
45            tokio_runtime: Mutex::new(None),
46            pid: current_pid(),
47        }
48    }
49}
50
51#[inline]
52fn current_pid() -> u32 {
53    #[cfg(not(target_family = "wasm"))]
54    return std::process::id();
55
56    #[cfg(target_family = "wasm")]
57    return 0;
58}