Skip to main content

regula_core/
state.rs

1//! GraphState trait and related types.
2//!
3//! The `GraphState` trait defines the requirements for types that can be
4//! used as the state in a REGULA graph. State flows through nodes, which
5//! read current values and produce updates.
6
7use crate::channel::{ChannelSpec, DynChannel};
8use crate::error::Result;
9use indexmap::IndexMap;
10use serde::{de::DeserializeOwned, Serialize};
11use std::collections::HashMap;
12
13/// Trait for types that can be used as graph state.
14///
15/// Implement this trait for your state struct to use it with `StateGraph`.
16/// The derive macro `#[derive(GraphState)]` can auto-implement this trait.
17///
18/// # Requirements
19///
20/// - `Clone`: State is cloned during checkpointing and branching.
21/// - `Send + Sync`: State must be thread-safe for parallel node execution.
22/// - `Serialize + DeserializeOwned`: State must be serializable for checkpoints.
23///
24/// # Examples
25///
26/// ```ignore
27/// use regula_core::{GraphState, ChannelSpec};
28/// use serde::{Serialize, Deserialize};
29///
30/// #[derive(Clone, Serialize, Deserialize)]
31/// struct MyState {
32///     messages: Vec<String>,
33///     counter: i32,
34/// }
35///
36/// impl GraphState for MyState {
37///     fn channels() -> std::collections::HashMap<String, ChannelSpec> {
38///         let mut channels = std::collections::HashMap::new();
39///         channels.insert("messages".to_string(), ChannelSpec::LastValue);
40///         channels.insert("counter".to_string(), ChannelSpec::LastValue);
41///         channels
42///     }
43/// }
44/// ```
45pub trait GraphState: Clone + Send + Sync + Serialize + DeserializeOwned + 'static {
46    /// Returns the channel specifications for each field in the state.
47    ///
48    /// The key is the field name, and the value describes how updates
49    /// to that field should be handled (last value, reducer, etc.).
50    fn channels() -> HashMap<String, ChannelSpec>;
51
52    /// Get the list of field names in the state.
53    fn field_names() -> Vec<&'static str> {
54        vec![]
55    }
56
57    /// Convert the state to a JSON value.
58    fn to_json(&self) -> Result<serde_json::Value> {
59        Ok(serde_json::to_value(self)?)
60    }
61
62    /// Create a state instance from a JSON value.
63    fn from_json(value: serde_json::Value) -> Result<Self> {
64        Ok(serde_json::from_value(value)?)
65    }
66
67    /// Apply a partial update to the state.
68    ///
69    /// The update is a JSON object where keys are field names and
70    /// values are the new values for those fields.
71    fn apply_update(&mut self, update: serde_json::Value) -> Result<()> {
72        if let serde_json::Value::Object(updates) = update {
73            let mut current = self.to_json()?;
74            if let serde_json::Value::Object(ref mut current_obj) = current {
75                for (key, value) in updates {
76                    current_obj.insert(key, value);
77                }
78            }
79            *self = Self::from_json(current)?;
80        }
81        Ok(())
82    }
83}
84
85/// A dynamic state container that stores values in JSON format.
86///
87/// This is used internally by the runtime to manage state with
88/// type-erased channels.
89#[derive(Debug, Clone)]
90pub struct DynState {
91    /// The channel values, keyed by field name.
92    channels: IndexMap<String, DynChannel>,
93}
94
95impl DynState {
96    /// Create a new empty dynamic state.
97    pub fn new() -> Self {
98        Self {
99            channels: IndexMap::new(),
100        }
101    }
102
103    /// Create a dynamic state from channel specifications.
104    pub fn from_specs(specs: HashMap<String, ChannelSpec>) -> Self {
105        let mut channels = IndexMap::new();
106        for (name, spec) in specs {
107            channels.insert(name, DynChannel::new(spec));
108        }
109        Self { channels }
110    }
111
112    /// Create a dynamic state from a GraphState instance.
113    pub fn from_state<S: GraphState>(state: &S) -> Result<Self> {
114        let specs = S::channels();
115        let json = state.to_json()?;
116
117        let mut dyn_state = Self::from_specs(specs);
118
119        if let serde_json::Value::Object(obj) = json {
120            for (key, value) in obj {
121                if let Some(channel) = dyn_state.channels.get_mut(&key) {
122                    channel.set(value)?;
123                }
124            }
125        }
126
127        // Clear modified flags so state is ready for new super-step
128        dyn_state.clear_modified();
129
130        Ok(dyn_state)
131    }
132
133    /// Convert the dynamic state back to a typed GraphState.
134    pub fn to_state<S: GraphState>(&self) -> Result<S> {
135        let mut obj = serde_json::Map::new();
136        for (name, channel) in &self.channels {
137            if let Some(value) = channel.raw_value() {
138                obj.insert(name.clone(), value.clone());
139            }
140        }
141        S::from_json(serde_json::Value::Object(obj))
142    }
143
144    /// Get a channel by name.
145    pub fn get_channel(&self, name: &str) -> Option<&DynChannel> {
146        self.channels.get(name)
147    }
148
149    /// Get a mutable channel by name.
150    pub fn get_channel_mut(&mut self, name: &str) -> Option<&mut DynChannel> {
151        self.channels.get_mut(name)
152    }
153
154    /// Update a channel with a new value.
155    pub fn update_channel(&mut self, name: &str, value: serde_json::Value) -> Result<bool> {
156        if let Some(channel) = self.channels.get_mut(name) {
157            channel.update(value)
158        } else {
159            Ok(false)
160        }
161    }
162
163    /// Apply a partial update (JSON object with field updates).
164    pub fn apply_update(&mut self, update: serde_json::Value) -> Result<()> {
165        if let serde_json::Value::Object(obj) = update {
166            for (key, value) in obj {
167                self.update_channel(&key, value)?;
168            }
169        }
170        Ok(())
171    }
172
173    /// Clear the modified flag on all channels (called between super-steps).
174    pub fn clear_modified(&mut self) {
175        for channel in self.channels.values_mut() {
176            channel.clear_modified();
177        }
178    }
179
180    /// Get all channel values as a JSON object.
181    pub fn to_json(&self) -> serde_json::Value {
182        let mut obj = serde_json::Map::new();
183        for (name, channel) in &self.channels {
184            if let Some(value) = channel.raw_value() {
185                obj.insert(name.clone(), value.clone());
186            }
187        }
188        serde_json::Value::Object(obj)
189    }
190
191    /// Create a checkpoint of the current state.
192    pub fn checkpoint(&self) -> serde_json::Value {
193        let mut obj = serde_json::Map::new();
194        for (name, channel) in &self.channels {
195            if let Some(value) = channel.checkpoint() {
196                obj.insert(name.clone(), value);
197            }
198        }
199        serde_json::Value::Object(obj)
200    }
201
202    /// Restore state from a checkpoint.
203    pub fn restore(&mut self, checkpoint: serde_json::Value) {
204        if let serde_json::Value::Object(obj) = checkpoint {
205            for (name, value) in obj {
206                if let Some(channel) = self.channels.get_mut(&name) {
207                    channel.restore(Some(value));
208                }
209            }
210        }
211    }
212
213    /// Get the list of channel names.
214    pub fn channel_names(&self) -> impl Iterator<Item = &String> {
215        self.channels.keys()
216    }
217}
218
219impl Default for DynState {
220    fn default() -> Self {
221        Self::new()
222    }
223}
224
225/// Macro to create a partial state update.
226///
227/// This macro creates a `serde_json::Value` object that can be
228/// returned from a node to update specific state fields.
229///
230/// # Examples
231///
232/// ```ignore
233/// use regula_core::partial_state;
234///
235/// let update = partial_state! {
236///     messages: vec![new_message],
237///     counter: 42,
238/// };
239/// ```
240#[macro_export]
241macro_rules! partial_state {
242    ($($field:ident : $value:expr),* $(,)?) => {
243        serde_json::json!({
244            $(stringify!($field): $value),*
245        })
246    };
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[derive(Clone, Debug, PartialEq, Serialize, serde::Deserialize)]
254    struct TestState {
255        messages: Vec<String>,
256        counter: i32,
257    }
258
259    impl GraphState for TestState {
260        fn channels() -> HashMap<String, ChannelSpec> {
261            let mut channels = HashMap::new();
262            channels.insert("messages".to_string(), ChannelSpec::LastValue);
263            channels.insert("counter".to_string(), ChannelSpec::LastValue);
264            channels
265        }
266    }
267
268    #[test]
269    fn test_graph_state_to_json() {
270        let state = TestState {
271            messages: vec!["hello".to_string()],
272            counter: 42,
273        };
274
275        let json = state.to_json().unwrap();
276        assert_eq!(json["messages"][0], "hello");
277        assert_eq!(json["counter"], 42);
278    }
279
280    #[test]
281    fn test_graph_state_from_json() {
282        let json = serde_json::json!({
283            "messages": ["hello", "world"],
284            "counter": 10
285        });
286
287        let state: TestState = GraphState::from_json(json).unwrap();
288        assert_eq!(state.messages, vec!["hello", "world"]);
289        assert_eq!(state.counter, 10);
290    }
291
292    #[test]
293    fn test_graph_state_apply_update() {
294        let mut state = TestState {
295            messages: vec!["hello".to_string()],
296            counter: 42,
297        };
298
299        let update = serde_json::json!({
300            "counter": 100
301        });
302
303        state.apply_update(update).unwrap();
304        assert_eq!(state.counter, 100);
305        assert_eq!(state.messages, vec!["hello"]); // Unchanged
306    }
307
308    #[test]
309    fn test_dyn_state_from_state() {
310        let state = TestState {
311            messages: vec!["hello".to_string()],
312            counter: 42,
313        };
314
315        let dyn_state = DynState::from_state(&state).unwrap();
316        
317        assert!(dyn_state.get_channel("messages").is_some());
318        assert!(dyn_state.get_channel("counter").is_some());
319    }
320
321    #[test]
322    fn test_dyn_state_to_state() {
323        let state = TestState {
324            messages: vec!["hello".to_string()],
325            counter: 42,
326        };
327
328        let dyn_state = DynState::from_state(&state).unwrap();
329        let restored: TestState = dyn_state.to_state().unwrap();
330
331        assert_eq!(restored, state);
332    }
333
334    #[test]
335    fn test_dyn_state_update_channel() {
336        let state = TestState {
337            messages: vec!["hello".to_string()],
338            counter: 42,
339        };
340
341        let mut dyn_state = DynState::from_state(&state).unwrap();
342        
343        dyn_state.update_channel("counter", serde_json::json!(100)).unwrap();
344        
345        let restored: TestState = dyn_state.to_state().unwrap();
346        assert_eq!(restored.counter, 100);
347    }
348
349    #[test]
350    fn test_dyn_state_checkpoint_restore() {
351        let state = TestState {
352            messages: vec!["hello".to_string()],
353            counter: 42,
354        };
355
356        let dyn_state = DynState::from_state(&state).unwrap();
357        let checkpoint = dyn_state.checkpoint();
358
359        let mut new_dyn_state = DynState::from_specs(TestState::channels());
360        new_dyn_state.restore(checkpoint);
361
362        let restored: TestState = new_dyn_state.to_state().unwrap();
363        assert_eq!(restored, state);
364    }
365
366    #[test]
367    fn test_partial_state_macro() {
368        let update = partial_state! {
369            counter: 100,
370            messages: vec!["new message"],
371        };
372
373        assert_eq!(update["counter"], 100);
374        assert_eq!(update["messages"][0], "new message");
375    }
376}