Skip to main content

camel_component_wasm/
state_store.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3use std::sync::Mutex;
4
5/// Persistent key-value store scoped to a WASM producer (per route endpoint).
6///
7/// Each route endpoint using a WASM component gets its own independent state store.
8/// If two routes use the same `.wasm` file, they maintain separate state.
9/// Owned by `WasmProducer` and passed to `WasmRuntime` when creating host state.
10#[derive(Debug, Clone)]
11pub struct StateStore {
12    data: Arc<Mutex<HashMap<String, String>>>,
13}
14
15impl StateStore {
16    pub fn new() -> Self {
17        Self {
18            data: Arc::new(Mutex::new(HashMap::new())),
19        }
20    }
21
22    pub fn store(&self, key: &str, value: &str) -> Result<(), String> {
23        let mut guard = self
24            .data
25            .lock()
26            .map_err(|e| format!("lock poisoned: {}", e))?;
27        guard.insert(key.to_string(), value.to_string());
28        Ok(())
29    }
30
31    pub fn load(&self, key: &str) -> Result<Option<String>, String> {
32        let guard = self
33            .data
34            .lock()
35            .map_err(|e| format!("lock poisoned: {}", e))?;
36        Ok(guard.get(key).cloned())
37    }
38
39    pub fn is_empty(&self) -> bool {
40        self.len() == 0
41    }
42
43    pub fn len(&self) -> usize {
44        self.data.lock().map(|g| g.len()).unwrap_or(0)
45    }
46}
47
48impl Default for StateStore {
49    fn default() -> Self {
50        Self::new()
51    }
52}