Skip to main content

regula_core/channel/
mod.rs

1//! Channel system for state management.
2//!
3//! Channels define how state values are stored, updated, and merged when
4//! multiple nodes write to the same field during a super-step.
5//!
6//! # Channel Types
7//!
8//! - [`LastValue`]: Keeps the most recently written value (default).
9//! - [`Reducer`]: Applies a reducer function to combine values (e.g., append to list).
10//!
11//! # Example
12//!
13//! ```ignore
14//! // In state definition:
15//! struct AgentState {
16//!     messages: Vec<Message>,     // LastValue (default)
17//!     #[reducer(append)]
18//!     history: Vec<String>,       // Uses Reducer with append
19//! }
20//! ```
21
22mod last_value;
23mod reducer;
24
25pub use last_value::LastValue;
26pub use reducer::{Reducer, ReducerFn, ReducerType};
27
28use crate::error::{RegulaError, Result};
29use serde::{de::DeserializeOwned, Serialize};
30use std::fmt::Debug;
31
32/// Specification for how a channel behaves.
33///
34/// This is used during graph construction to determine how state
35/// fields should handle concurrent updates.
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub enum ChannelSpec {
38    /// Keep the last written value. If multiple values are written
39    /// in the same step, an error is raised.
40    LastValue,
41
42    /// Apply a reducer function to combine values.
43    Reducer(ReducerType),
44
45    /// Value is cleared after each step (not persisted).
46    /// This is useful for temporary computation results.
47    Ephemeral,
48
49    /// Allow any value, last writer wins (no error on concurrent writes).
50    AnyValue,
51}
52
53impl Default for ChannelSpec {
54    fn default() -> Self {
55        Self::LastValue
56    }
57}
58
59/// Trait for channel implementations.
60///
61/// Channels manage individual state fields, handling value storage,
62/// updates, and checkpoint serialization.
63pub trait Channel: Send + Sync + Debug {
64    /// The type of value stored in this channel.
65    type Value: Clone + Send + Sync + Serialize + DeserializeOwned;
66
67    /// Update the channel with new values.
68    ///
69    /// For LastValue channels, this expects exactly one value.
70    /// For Reducer channels, values are combined using the reducer function.
71    ///
72    /// Returns `true` if the channel value changed.
73    fn update(&mut self, values: Vec<Self::Value>) -> Result<bool>;
74
75    /// Get the current value, if set.
76    fn get(&self) -> Result<Self::Value>;
77
78    /// Check if the channel has a value.
79    fn is_set(&self) -> bool;
80
81    /// Reset the channel to empty state.
82    fn reset(&mut self);
83
84    /// Get the channel specification.
85    fn spec(&self) -> ChannelSpec;
86
87    /// Serialize the channel value for checkpointing.
88    fn checkpoint(&self) -> Result<Option<serde_json::Value>>;
89
90    /// Restore the channel from a checkpoint.
91    fn restore(&mut self, value: Option<serde_json::Value>) -> Result<()>;
92}
93
94/// A boxed channel that can hold any channel type.
95pub type BoxedChannel<V> = Box<dyn Channel<Value = V>>;
96
97/// Wrapper for dynamic channel access with type erasure.
98///
99/// This allows storing channels of different value types in a single collection.
100#[derive(Debug, Clone)]
101pub struct DynChannel {
102    /// The channel specification.
103    pub spec: ChannelSpec,
104    /// The channel value as JSON (for type-erased storage).
105    value: Option<serde_json::Value>,
106    /// Whether the channel has been modified this step.
107    modified: bool,
108}
109
110impl DynChannel {
111    /// Create a new dynamic channel.
112    pub fn new(spec: ChannelSpec) -> Self {
113        Self {
114            spec,
115            value: None,
116            modified: false,
117        }
118    }
119
120    /// Create a new dynamic channel with an initial value.
121    pub fn with_value<V: Serialize>(spec: ChannelSpec, value: V) -> Result<Self> {
122        Ok(Self {
123            spec,
124            value: Some(serde_json::to_value(value)?),
125            modified: false,
126        })
127    }
128
129    /// Check if the channel has a value.
130    pub fn is_set(&self) -> bool {
131        self.value.is_some()
132    }
133
134    /// Get the value, deserializing to the expected type.
135    pub fn get<V: DeserializeOwned>(&self) -> Result<V> {
136        match &self.value {
137            Some(v) => Ok(serde_json::from_value(v.clone())?),
138            None => Err(RegulaError::EmptyChannel("unknown".to_string())),
139        }
140    }
141
142    /// Set the value, serializing from the given type.
143    pub fn set<V: Serialize>(&mut self, value: V) -> Result<()> {
144        self.value = Some(serde_json::to_value(value)?);
145        self.modified = true;
146        Ok(())
147    }
148
149    /// Update the channel with a new JSON value.
150    pub fn update(&mut self, value: serde_json::Value) -> Result<bool> {
151        match self.spec {
152            ChannelSpec::LastValue => {
153                if self.modified {
154                    return Err(RegulaError::ChannelTypeMismatch {
155                        channel: "unknown".to_string(),
156                        expected: "single write".to_string(),
157                        actual: "multiple writes".to_string(),
158                    });
159                }
160                self.value = Some(value);
161                self.modified = true;
162                Ok(true)
163            }
164            ChannelSpec::AnyValue | ChannelSpec::Ephemeral => {
165                self.value = Some(value);
166                self.modified = true;
167                Ok(true)
168            }
169            ChannelSpec::Reducer(ref reducer_type) => {
170                // Apply reducer logic
171                let new_value = match (&self.value, reducer_type) {
172                    (Some(current), ReducerType::Append) => {
173                        // Both must be arrays
174                        let mut arr = current
175                            .as_array()
176                            .cloned()
177                            .unwrap_or_default();
178                        if let Some(new_arr) = value.as_array() {
179                            arr.extend(new_arr.iter().cloned());
180                        } else {
181                            arr.push(value);
182                        }
183                        serde_json::Value::Array(arr)
184                    }
185                    (None, ReducerType::Append) => {
186                        if value.is_array() {
187                            value
188                        } else {
189                            serde_json::Value::Array(vec![value])
190                        }
191                    }
192                    (Some(current), ReducerType::Add) => {
193                        // Both must be numbers
194                        let c = current.as_f64().unwrap_or(0.0);
195                        let v = value.as_f64().unwrap_or(0.0);
196                        serde_json::Value::from(c + v)
197                    }
198                    (None, ReducerType::Add) => value,
199                    (_, ReducerType::Custom(_)) => {
200                        // Custom reducers need special handling
201                        // For now, just use last value
202                        value
203                    }
204                };
205                self.value = Some(new_value);
206                self.modified = true;
207                Ok(true)
208            }
209        }
210    }
211
212    /// Reset the modified flag for the next step.
213    pub fn clear_modified(&mut self) {
214        self.modified = false;
215        if self.spec == ChannelSpec::Ephemeral {
216            self.value = None;
217        }
218    }
219
220    /// Get the raw JSON value.
221    pub fn raw_value(&self) -> Option<&serde_json::Value> {
222        self.value.as_ref()
223    }
224
225    /// Checkpoint the channel value.
226    pub fn checkpoint(&self) -> Option<serde_json::Value> {
227        if self.spec == ChannelSpec::Ephemeral {
228            None
229        } else {
230            self.value.clone()
231        }
232    }
233
234    /// Restore from a checkpoint.
235    pub fn restore(&mut self, value: Option<serde_json::Value>) {
236        self.value = value;
237        self.modified = false;
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn test_channel_spec_default() {
247        assert_eq!(ChannelSpec::default(), ChannelSpec::LastValue);
248    }
249
250    #[test]
251    fn test_dyn_channel_last_value() {
252        let mut channel = DynChannel::new(ChannelSpec::LastValue);
253        assert!(!channel.is_set());
254
255        channel.update(serde_json::json!("hello")).unwrap();
256        assert!(channel.is_set());
257
258        let value: String = channel.get().unwrap();
259        assert_eq!(value, "hello");
260    }
261
262    #[test]
263    fn test_dyn_channel_reducer_append() {
264        let mut channel = DynChannel::new(ChannelSpec::Reducer(ReducerType::Append));
265        
266        channel.update(serde_json::json!(["a"])).unwrap();
267        channel.update(serde_json::json!(["b", "c"])).unwrap();
268
269        let value: Vec<String> = channel.get().unwrap();
270        assert_eq!(value, vec!["a", "b", "c"]);
271    }
272
273    #[test]
274    fn test_dyn_channel_ephemeral() {
275        let mut channel = DynChannel::new(ChannelSpec::Ephemeral);
276        
277        channel.update(serde_json::json!("temp")).unwrap();
278        assert!(channel.is_set());
279
280        channel.clear_modified();
281        assert!(!channel.is_set()); // Ephemeral values are cleared
282    }
283}