Skip to main content

nestrs_core/
metadata.rs

1//! Lightweight metadata registry for custom decorator patterns.
2
3use std::collections::HashMap;
4use std::sync::{OnceLock, RwLock};
5
6type Registry = HashMap<String, HashMap<String, String>>;
7
8fn store() -> &'static RwLock<Registry> {
9    static STORE: OnceLock<RwLock<Registry>> = OnceLock::new();
10    STORE.get_or_init(|| RwLock::new(HashMap::new()))
11}
12
13/// Global metadata helpers (handler key + metadata key/value).
14pub struct MetadataRegistry;
15
16impl MetadataRegistry {
17    pub fn set(handler: impl Into<String>, key: impl Into<String>, value: impl Into<String>) {
18        let mut guard = store().write().expect("metadata lock poisoned");
19        let entry = guard.entry(handler.into()).or_default();
20        entry.insert(key.into(), value.into());
21    }
22
23    pub fn get(handler: &str, key: &str) -> Option<String> {
24        let guard = store().read().expect("metadata lock poisoned");
25        guard.get(handler).and_then(|m| m.get(key)).cloned()
26    }
27
28    /// Removes all handler metadata entries in this process.
29    ///
30    /// **Available only with the `test-hooks` feature.** For tests; see `STABILITY.md` in the repo root.
31    #[cfg(feature = "test-hooks")]
32    pub fn clear_for_tests() {
33        let mut guard = store().write().expect("metadata lock poisoned");
34        guard.clear();
35    }
36}