env_watcher/
derive.rs

1use std::collections::HashMap;
2use std::sync::Mutex;
3use std::time::Duration;
4use crossbeam_channel::Receiver;
5use state::Storage;
6use crate::{ChangeState, EnvironmentData, EnvironmentWatcher, Subscribe, Result, Error};
7
8static ENV_WATCHER: Storage<Mutex<EnvironmentWatcher>> = Storage::new();
9static INIT: Storage<Mutex<i8>> = Storage::new();
10
11/// Initialize env watcher (singleton) with duration.
12#[macro_export]
13macro_rules! init_env_watch {
14    ($dur:expr) => {
15        {
16            $crate::derive::init_env_watcher($dur)
17        }
18    }
19}
20
21/// Subscribe with Receiver and Data
22#[macro_export]
23macro_rules! sub_env {
24    ($sub:expr) => {
25        {
26            $crate::derive::subscribe($sub)
27        }
28    }
29}
30
31/// Subscribe by snapshot
32#[macro_export]
33macro_rules! sub_env_snapshot {
34    ($sub:expr) => {
35        {
36            $crate::derive::subscribe_snapshot($sub)
37        }
38    }
39}
40
41#[doc(hidden)]
42pub fn init_env_watcher(interval: Duration) -> Result<()> {
43    let mut init = INIT.get_or_set(|| Mutex::new(0)).lock().unwrap();
44
45    if *init > 0 {
46        return Err(Error::DoubleInitialWatcher);
47    }
48
49    let watcher = ENV_WATCHER.get_or_set(|| Mutex::new(EnvironmentWatcher::new(interval))).lock().unwrap();
50
51    if watcher.size() > 0 {
52        return Err(Error::ReinitializedWithSubscribers);
53    }
54
55    *init = 1;
56
57    Ok(())
58}
59
60#[doc(hidden)]
61pub fn subscribe(sub: Subscribe) -> Result<(HashMap<String, String>, Receiver<ChangeState>)> {
62    let watcher = ENV_WATCHER.get().lock().unwrap();
63    watcher.subscribe(sub)
64}
65
66#[doc(hidden)]
67pub fn subscribe_snapshot(sub: Subscribe) -> Result<EnvironmentData> {
68    let watcher = ENV_WATCHER.get().lock().unwrap();
69    watcher.subscribe_snapshot(sub)
70}