Skip to main content

regula_core/
config.rs

1//! Runtime configuration for graph execution.
2//!
3//! `RunnableConfig` carries context, thread identification, and metadata
4//! through node execution. It provides a type-safe way to pass additional
5//! data to nodes without polluting the state.
6
7use serde::{Deserialize, Serialize};
8use std::any::{Any, TypeId};
9use std::collections::HashMap;
10use std::sync::Arc;
11use uuid::Uuid;
12
13/// Configuration for a graph execution run.
14///
15/// `RunnableConfig` provides context and metadata to nodes during execution.
16/// It includes thread identification for checkpointing, custom data storage,
17/// and execution parameters.
18///
19/// # Examples
20///
21/// ```
22/// use regula_core::RunnableConfig;
23///
24/// let config = RunnableConfig::new()
25///     .with_thread_id("conversation-1")
26///     .with_metadata("user_id", "user-123");
27///
28/// assert_eq!(config.thread_id(), Some("conversation-1"));
29/// ```
30#[derive(Clone, Debug)]
31pub struct RunnableConfig {
32    /// Unique identifier for this execution thread.
33    thread_id: Option<String>,
34
35    /// Checkpoint ID to resume from.
36    checkpoint_id: Option<String>,
37
38    /// Custom metadata (string key-value pairs).
39    metadata: HashMap<String, String>,
40
41    /// Type-erased context values.
42    context: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
43
44    /// Tags for filtering/categorization.
45    tags: Vec<String>,
46
47    /// Maximum number of iterations before timeout.
48    max_iterations: Option<usize>,
49
50    /// Recursion limit for nested graphs.
51    recursion_limit: usize,
52}
53
54impl RunnableConfig {
55    /// Create a new configuration with default values.
56    pub fn new() -> Self {
57        Self {
58            thread_id: None,
59            checkpoint_id: None,
60            metadata: HashMap::new(),
61            context: HashMap::new(),
62            tags: Vec::new(),
63            max_iterations: None,
64            recursion_limit: 25,
65        }
66    }
67
68    /// Create a configuration with a random thread ID.
69    pub fn with_random_thread() -> Self {
70        Self::new().with_thread_id(Uuid::new_v4().to_string())
71    }
72
73    /// Set the thread ID.
74    ///
75    /// The thread ID is used to identify a conversation or session for
76    /// checkpointing and state persistence.
77    pub fn with_thread_id(mut self, thread_id: impl Into<String>) -> Self {
78        self.thread_id = Some(thread_id.into());
79        self
80    }
81
82    /// Set the checkpoint ID to resume from.
83    pub fn with_checkpoint_id(mut self, checkpoint_id: impl Into<String>) -> Self {
84        self.checkpoint_id = Some(checkpoint_id.into());
85        self
86    }
87
88    /// Add a metadata key-value pair.
89    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
90        self.metadata.insert(key.into(), value.into());
91        self
92    }
93
94    /// Add multiple metadata entries.
95    pub fn with_metadata_map(mut self, metadata: HashMap<String, String>) -> Self {
96        self.metadata.extend(metadata);
97        self
98    }
99
100    /// Add a typed context value.
101    ///
102    /// Context values can be retrieved in nodes using `config.get::<T>()`.
103    pub fn with_context<T: Send + Sync + 'static>(mut self, value: T) -> Self {
104        self.context.insert(TypeId::of::<T>(), Arc::new(value));
105        self
106    }
107
108    /// Add a tag.
109    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
110        self.tags.push(tag.into());
111        self
112    }
113
114    /// Add multiple tags.
115    pub fn with_tags(mut self, tags: impl IntoIterator<Item = impl Into<String>>) -> Self {
116        self.tags.extend(tags.into_iter().map(Into::into));
117        self
118    }
119
120    /// Set the maximum iterations.
121    pub fn with_max_iterations(mut self, max: usize) -> Self {
122        self.max_iterations = Some(max);
123        self
124    }
125
126    /// Set the recursion limit.
127    pub fn with_recursion_limit(mut self, limit: usize) -> Self {
128        self.recursion_limit = limit;
129        self
130    }
131
132    /// Get the thread ID.
133    pub fn thread_id(&self) -> Option<&str> {
134        self.thread_id.as_deref()
135    }
136
137    /// Get the checkpoint ID.
138    pub fn checkpoint_id(&self) -> Option<&str> {
139        self.checkpoint_id.as_deref()
140    }
141
142    /// Get a metadata value by key.
143    pub fn get_metadata(&self, key: &str) -> Option<&str> {
144        self.metadata.get(key).map(|s| s.as_str())
145    }
146
147    /// Get all metadata.
148    pub fn metadata(&self) -> &HashMap<String, String> {
149        &self.metadata
150    }
151
152    /// Get a typed context value.
153    ///
154    /// Returns `None` if the value was not set or is the wrong type.
155    pub fn get_context<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
156        self.context
157            .get(&TypeId::of::<T>())
158            .and_then(|v| v.clone().downcast::<T>().ok())
159    }
160
161    /// Get a typed context value, returning an error if not found.
162    pub fn require_context<T: Send + Sync + 'static>(&self) -> crate::error::Result<Arc<T>> {
163        self.get_context::<T>().ok_or_else(|| {
164            crate::error::RegulaError::ConfigKeyNotFound(std::any::type_name::<T>().to_string())
165        })
166    }
167
168    /// Check if a tag is present.
169    pub fn has_tag(&self, tag: &str) -> bool {
170        self.tags.iter().any(|t| t == tag)
171    }
172
173    /// Get all tags.
174    pub fn tags(&self) -> &[String] {
175        &self.tags
176    }
177
178    /// Get the maximum iterations limit.
179    pub fn max_iterations(&self) -> Option<usize> {
180        self.max_iterations
181    }
182
183    /// Get the recursion limit.
184    pub fn recursion_limit(&self) -> usize {
185        self.recursion_limit
186    }
187
188    /// Create a child configuration for nested graph execution.
189    ///
190    /// This decrements the recursion limit and preserves other settings.
191    pub fn child(&self) -> crate::error::Result<Self> {
192        if self.recursion_limit == 0 {
193            return Err(crate::error::RegulaError::MaxIterationsExceeded(0));
194        }
195
196        Ok(Self {
197            thread_id: self.thread_id.clone(),
198            checkpoint_id: None, // Don't inherit checkpoint for nested execution
199            metadata: self.metadata.clone(),
200            context: self.context.clone(),
201            tags: self.tags.clone(),
202            max_iterations: self.max_iterations,
203            recursion_limit: self.recursion_limit - 1,
204        })
205    }
206
207    /// Merge another configuration into this one.
208    ///
209    /// Values from `other` take precedence.
210    pub fn merge(mut self, other: Self) -> Self {
211        if other.thread_id.is_some() {
212            self.thread_id = other.thread_id;
213        }
214        if other.checkpoint_id.is_some() {
215            self.checkpoint_id = other.checkpoint_id;
216        }
217        self.metadata.extend(other.metadata);
218        self.context.extend(other.context);
219        self.tags.extend(other.tags);
220        if other.max_iterations.is_some() {
221            self.max_iterations = other.max_iterations;
222        }
223        self.recursion_limit = other.recursion_limit;
224        self
225    }
226}
227
228impl Default for RunnableConfig {
229    fn default() -> Self {
230        Self::new()
231    }
232}
233
234/// Serializable version of RunnableConfig for checkpointing.
235#[derive(Clone, Debug, Serialize, Deserialize)]
236pub struct ConfigSnapshot {
237    /// Thread ID.
238    pub thread_id: Option<String>,
239    /// Checkpoint ID.
240    pub checkpoint_id: Option<String>,
241    /// Metadata.
242    pub metadata: HashMap<String, String>,
243    /// Tags.
244    pub tags: Vec<String>,
245}
246
247impl From<&RunnableConfig> for ConfigSnapshot {
248    fn from(config: &RunnableConfig) -> Self {
249        Self {
250            thread_id: config.thread_id.clone(),
251            checkpoint_id: config.checkpoint_id.clone(),
252            metadata: config.metadata.clone(),
253            tags: config.tags.clone(),
254        }
255    }
256}
257
258impl From<ConfigSnapshot> for RunnableConfig {
259    fn from(snapshot: ConfigSnapshot) -> Self {
260        Self {
261            thread_id: snapshot.thread_id,
262            checkpoint_id: snapshot.checkpoint_id,
263            metadata: snapshot.metadata,
264            context: HashMap::new(),
265            tags: snapshot.tags,
266            max_iterations: None,
267            recursion_limit: 25,
268        }
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    #[test]
277    fn test_config_new() {
278        let config = RunnableConfig::new();
279        assert!(config.thread_id().is_none());
280        assert!(config.metadata().is_empty());
281    }
282
283    #[test]
284    fn test_config_with_thread_id() {
285        let config = RunnableConfig::new().with_thread_id("thread-1");
286        assert_eq!(config.thread_id(), Some("thread-1"));
287    }
288
289    #[test]
290    fn test_config_with_metadata() {
291        let config = RunnableConfig::new()
292            .with_metadata("key1", "value1")
293            .with_metadata("key2", "value2");
294
295        assert_eq!(config.get_metadata("key1"), Some("value1"));
296        assert_eq!(config.get_metadata("key2"), Some("value2"));
297        assert_eq!(config.get_metadata("key3"), None);
298    }
299
300    #[test]
301    fn test_config_with_context() {
302        #[derive(Clone)]
303        struct MyContext {
304            value: i32,
305        }
306
307        let config = RunnableConfig::new().with_context(MyContext { value: 42 });
308
309        let ctx = config.get_context::<MyContext>().unwrap();
310        assert_eq!(ctx.value, 42);
311    }
312
313    #[test]
314    fn test_config_require_context() {
315        let config = RunnableConfig::new().with_context(42i32);
316
317        let result = config.require_context::<i32>();
318        assert!(result.is_ok());
319        assert_eq!(*result.unwrap(), 42);
320
321        let result = config.require_context::<String>();
322        assert!(result.is_err());
323    }
324
325    #[test]
326    fn test_config_with_tags() {
327        let config = RunnableConfig::new()
328            .with_tag("tag1")
329            .with_tags(vec!["tag2", "tag3"]);
330
331        assert!(config.has_tag("tag1"));
332        assert!(config.has_tag("tag2"));
333        assert!(config.has_tag("tag3"));
334        assert!(!config.has_tag("tag4"));
335    }
336
337    #[test]
338    fn test_config_child() {
339        let config = RunnableConfig::new()
340            .with_thread_id("thread-1")
341            .with_recursion_limit(5);
342
343        let child = config.child().unwrap();
344        assert_eq!(child.thread_id(), Some("thread-1"));
345        assert_eq!(child.recursion_limit(), 4);
346    }
347
348    #[test]
349    fn test_config_child_recursion_limit() {
350        let config = RunnableConfig::new().with_recursion_limit(0);
351        let result = config.child();
352        assert!(result.is_err());
353    }
354
355    #[test]
356    fn test_config_merge() {
357        let config1 = RunnableConfig::new()
358            .with_thread_id("thread-1")
359            .with_metadata("key1", "value1");
360
361        let config2 = RunnableConfig::new()
362            .with_thread_id("thread-2")
363            .with_metadata("key2", "value2");
364
365        let merged = config1.merge(config2);
366        assert_eq!(merged.thread_id(), Some("thread-2")); // config2 takes precedence
367        assert_eq!(merged.get_metadata("key1"), Some("value1"));
368        assert_eq!(merged.get_metadata("key2"), Some("value2"));
369    }
370
371    #[test]
372    fn test_config_snapshot_roundtrip() {
373        let config = RunnableConfig::new()
374            .with_thread_id("thread-1")
375            .with_metadata("key", "value")
376            .with_tag("tag1");
377
378        let snapshot = ConfigSnapshot::from(&config);
379        let restored = RunnableConfig::from(snapshot);
380
381        assert_eq!(restored.thread_id(), Some("thread-1"));
382        assert_eq!(restored.get_metadata("key"), Some("value"));
383        assert!(restored.has_tag("tag1"));
384    }
385
386    #[test]
387    fn test_config_with_random_thread() {
388        let config = RunnableConfig::with_random_thread();
389        assert!(config.thread_id().is_some());
390        assert!(!config.thread_id().unwrap().is_empty());
391    }
392}