rust_rule_engine/engine/
facts.rs

1use crate::errors::{Result, RuleEngineError};
2use crate::types::{Context, Value};
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5use std::sync::{Arc, RwLock};
6
7/// Facts - represents the working memory of data objects
8/// Similar to Grule's DataContext concept
9#[derive(Debug, Clone)]
10pub struct Facts {
11    data: Arc<RwLock<HashMap<String, Value>>>,
12    fact_types: Arc<RwLock<HashMap<String, String>>>,
13}
14
15impl Facts {
16    /// Create a generic object from key-value pairs
17    pub fn create_object(pairs: Vec<(String, Value)>) -> Value {
18        let mut map = HashMap::new();
19        for (key, value) in pairs {
20            map.insert(key, value);
21        }
22        Value::Object(map)
23    }
24
25    /// Create a user object
26    pub fn new() -> Self {
27        Self {
28            data: Arc::new(RwLock::new(HashMap::new())),
29            fact_types: Arc::new(RwLock::new(HashMap::new())),
30        }
31    }
32
33    /// Add a fact object to the working memory
34    pub fn add<T>(&self, name: &str, fact: T) -> Result<()>
35    where
36        T: Serialize + std::fmt::Debug,
37    {
38        let value =
39            serde_json::to_value(&fact).map_err(|e| RuleEngineError::SerializationError {
40                message: e.to_string(),
41            })?;
42
43        let fact_value = Value::from(value);
44
45        let mut data = self.data.write().unwrap();
46        let mut types = self.fact_types.write().unwrap();
47
48        data.insert(name.to_string(), fact_value);
49        types.insert(name.to_string(), std::any::type_name::<T>().to_string());
50
51        Ok(())
52    }
53
54    /// Add a simple value fact
55    pub fn add_value(&self, name: &str, value: Value) -> Result<()> {
56        let mut data = self.data.write().unwrap();
57        let mut types = self.fact_types.write().unwrap();
58
59        data.insert(name.to_string(), value);
60        types.insert(name.to_string(), "Value".to_string());
61
62        Ok(())
63    }
64
65    /// Get a fact by name
66    pub fn get(&self, name: &str) -> Option<Value> {
67        let data = self.data.read().unwrap();
68        data.get(name).cloned()
69    }
70
71    /// Get a nested fact property (e.g., "User.Profile.Age")
72    pub fn get_nested(&self, path: &str) -> Option<Value> {
73        let parts: Vec<&str> = path.split('.').collect();
74        if parts.is_empty() {
75            return None;
76        }
77
78        let data = self.data.read().unwrap();
79        let mut current = data.get(parts[0])?;
80
81        for part in parts.iter().skip(1) {
82            match current {
83                Value::Object(ref obj) => {
84                    current = obj.get(*part)?;
85                }
86                _ => return None,
87            }
88        }
89
90        Some(current.clone())
91    }
92
93    /// Set a fact value
94    pub fn set(&self, name: &str, value: Value) {
95        let mut data = self.data.write().unwrap();
96        data.insert(name.to_string(), value);
97    }
98
99    /// Set a nested fact property
100    pub fn set_nested(&self, path: &str, value: Value) -> Result<()> {
101        let parts: Vec<&str> = path.split('.').collect();
102        if parts.is_empty() {
103            return Err(RuleEngineError::FieldNotFound {
104                field: path.to_string(),
105            });
106        }
107
108        let mut data = self.data.write().unwrap();
109
110        if parts.len() == 1 {
111            data.insert(parts[0].to_string(), value);
112            return Ok(());
113        }
114
115        // Navigate to parent and set the nested value
116        let root_key = parts[0];
117        let root_value = data
118            .get_mut(root_key)
119            .ok_or_else(|| RuleEngineError::FieldNotFound {
120                field: root_key.to_string(),
121            })?;
122
123        self.set_nested_in_value(root_value, &parts[1..], value)?;
124        Ok(())
125    }
126
127    #[allow(clippy::only_used_in_recursion)]
128    fn set_nested_in_value(&self, current: &mut Value, path: &[&str], value: Value) -> Result<()> {
129        if path.is_empty() {
130            return Ok(());
131        }
132
133        if path.len() == 1 {
134            // We're at the target field
135            match current {
136                Value::Object(ref mut obj) => {
137                    obj.insert(path[0].to_string(), value);
138                    Ok(())
139                }
140                _ => Err(RuleEngineError::TypeMismatch {
141                    expected: "Object".to_string(),
142                    actual: format!("{:?}", current),
143                }),
144            }
145        } else {
146            // Continue navigating
147            match current {
148                Value::Object(ref mut obj) => {
149                    let next_value =
150                        obj.get_mut(path[0])
151                            .ok_or_else(|| RuleEngineError::FieldNotFound {
152                                field: path[0].to_string(),
153                            })?;
154                    self.set_nested_in_value(next_value, &path[1..], value)
155                }
156                _ => Err(RuleEngineError::TypeMismatch {
157                    expected: "Object".to_string(),
158                    actual: format!("{:?}", current),
159                }),
160            }
161        }
162    }
163
164    /// Remove a fact
165    pub fn remove(&self, name: &str) -> Option<Value> {
166        let mut data = self.data.write().unwrap();
167        let mut types = self.fact_types.write().unwrap();
168
169        types.remove(name);
170        data.remove(name)
171    }
172
173    /// Clear all facts
174    pub fn clear(&self) {
175        let mut data = self.data.write().unwrap();
176        let mut types = self.fact_types.write().unwrap();
177
178        data.clear();
179        types.clear();
180    }
181
182    /// Get all fact names
183    pub fn get_fact_names(&self) -> Vec<String> {
184        let data = self.data.read().unwrap();
185        data.keys().cloned().collect()
186    }
187
188    /// Get fact count
189    pub fn count(&self) -> usize {
190        let data = self.data.read().unwrap();
191        data.len()
192    }
193
194    /// Check if a fact exists
195    pub fn contains(&self, name: &str) -> bool {
196        let data = self.data.read().unwrap();
197        data.contains_key(name)
198    }
199
200    /// Get the type name of a fact
201    pub fn get_fact_type(&self, name: &str) -> Option<String> {
202        let types = self.fact_types.read().unwrap();
203        types.get(name).cloned()
204    }
205
206    /// Convert to Context for rule evaluation
207    pub fn to_context(&self) -> Context {
208        let data = self.data.read().unwrap();
209        data.clone()
210    }
211
212    /// Create Facts from Context
213    pub fn from_context(context: Context) -> Self {
214        let facts = Facts::new();
215        {
216            let mut data = facts.data.write().unwrap();
217            *data = context;
218        }
219        facts
220    }
221
222    /// Merge another Facts instance into this one
223    pub fn merge(&self, other: &Facts) {
224        let other_data = other.data.read().unwrap();
225        let other_types = other.fact_types.read().unwrap();
226
227        let mut data = self.data.write().unwrap();
228        let mut types = self.fact_types.write().unwrap();
229
230        for (key, value) in other_data.iter() {
231            data.insert(key.clone(), value.clone());
232        }
233
234        for (key, type_name) in other_types.iter() {
235            types.insert(key.clone(), type_name.clone());
236        }
237    }
238
239    /// Get a snapshot of all facts
240    pub fn snapshot(&self) -> FactsSnapshot {
241        let data = self.data.read().unwrap();
242        let types = self.fact_types.read().unwrap();
243
244        FactsSnapshot {
245            data: data.clone(),
246            fact_types: types.clone(),
247        }
248    }
249
250    /// Restore from a snapshot
251    pub fn restore(&self, snapshot: FactsSnapshot) {
252        let mut data = self.data.write().unwrap();
253        let mut types = self.fact_types.write().unwrap();
254
255        *data = snapshot.data;
256        *types = snapshot.fact_types;
257    }
258}
259
260impl Default for Facts {
261    fn default() -> Self {
262        Self::new()
263    }
264}
265
266/// A snapshot of Facts state
267#[derive(Debug, Clone, Serialize, Deserialize)]
268pub struct FactsSnapshot {
269    /// The fact data stored as key-value pairs
270    pub data: HashMap<String, Value>,
271    /// Type information for each fact
272    pub fact_types: HashMap<String, String>,
273}
274
275/// Trait for objects that can be used as facts
276pub trait Fact: Serialize + std::fmt::Debug {
277    /// Get the name of this fact type
278    fn fact_name() -> &'static str;
279}
280
281/// Macro to implement Fact trait easily
282#[macro_export]
283macro_rules! impl_fact {
284    ($type:ty, $name:expr) => {
285        impl Fact for $type {
286            fn fact_name() -> &'static str {
287                $name
288            }
289        }
290    };
291}
292
293/// Helper functions for working with fact objects
294pub struct FactHelper;
295
296impl FactHelper {
297    /// Create a generic object with key-value pairs
298    pub fn create_object(pairs: Vec<(&str, Value)>) -> Value {
299        let mut object = HashMap::new();
300        for (key, value) in pairs {
301            object.insert(key.to_string(), value);
302        }
303        Value::Object(object)
304    }
305
306    /// Create a User fact from common fields
307    pub fn create_user(name: &str, age: i64, email: &str, country: &str, is_vip: bool) -> Value {
308        let mut user = HashMap::new();
309        user.insert("Name".to_string(), Value::String(name.to_string()));
310        user.insert("Age".to_string(), Value::Integer(age));
311        user.insert("Email".to_string(), Value::String(email.to_string()));
312        user.insert("Country".to_string(), Value::String(country.to_string()));
313        user.insert("IsVIP".to_string(), Value::Boolean(is_vip));
314
315        Value::Object(user)
316    }
317
318    /// Create a Product fact
319    pub fn create_product(
320        name: &str,
321        price: f64,
322        category: &str,
323        in_stock: bool,
324        stock_count: i64,
325    ) -> Value {
326        let mut product = HashMap::new();
327        product.insert("Name".to_string(), Value::String(name.to_string()));
328        product.insert("Price".to_string(), Value::Number(price));
329        product.insert("Category".to_string(), Value::String(category.to_string()));
330        product.insert("InStock".to_string(), Value::Boolean(in_stock));
331        product.insert("StockCount".to_string(), Value::Integer(stock_count));
332
333        Value::Object(product)
334    }
335
336    /// Create an Order fact
337    pub fn create_order(
338        id: &str,
339        user_id: &str,
340        total: f64,
341        item_count: i64,
342        status: &str,
343    ) -> Value {
344        let mut order = HashMap::new();
345        order.insert("ID".to_string(), Value::String(id.to_string()));
346        order.insert("UserID".to_string(), Value::String(user_id.to_string()));
347        order.insert("Total".to_string(), Value::Number(total));
348        order.insert("ItemCount".to_string(), Value::Integer(item_count));
349        order.insert("Status".to_string(), Value::String(status.to_string()));
350
351        Value::Object(order)
352    }
353
354    /// Create a TestCar object for method call demo
355    pub fn create_test_car(
356        speed_up: bool,
357        speed: f64,
358        max_speed: f64,
359        speed_increment: f64,
360    ) -> Value {
361        let mut car = HashMap::new();
362        car.insert("speedUp".to_string(), Value::Boolean(speed_up));
363        car.insert("speed".to_string(), Value::Number(speed));
364        car.insert("maxSpeed".to_string(), Value::Number(max_speed));
365        car.insert("Speed".to_string(), Value::Number(speed));
366        car.insert("SpeedIncrement".to_string(), Value::Number(speed_increment));
367        car.insert(
368            "_type".to_string(),
369            Value::String("TestCarClass".to_string()),
370        );
371
372        Value::Object(car)
373    }
374
375    /// Create a DistanceRecord object for method call demo  
376    pub fn create_distance_record(total_distance: f64) -> Value {
377        let mut record = HashMap::new();
378        record.insert("TotalDistance".to_string(), Value::Number(total_distance));
379        record.insert(
380            "_type".to_string(),
381            Value::String("DistanceRecordClass".to_string()),
382        );
383
384        Value::Object(record)
385    }
386
387    /// Create a Transaction fact for fraud detection
388    pub fn create_transaction(
389        id: &str,
390        amount: f64,
391        location: &str,
392        timestamp: i64,
393        user_id: &str,
394    ) -> Value {
395        let mut transaction = HashMap::new();
396        transaction.insert("ID".to_string(), Value::String(id.to_string()));
397        transaction.insert("Amount".to_string(), Value::Number(amount));
398        transaction.insert("Location".to_string(), Value::String(location.to_string()));
399        transaction.insert("Timestamp".to_string(), Value::Integer(timestamp));
400        transaction.insert("UserID".to_string(), Value::String(user_id.to_string()));
401
402        Value::Object(transaction)
403    }
404}
405
406#[cfg(test)]
407mod tests {
408    use super::*;
409
410    #[test]
411    fn test_facts_basic_operations() {
412        let facts = Facts::new();
413
414        // Add facts
415        facts.add_value("age", Value::Integer(25)).unwrap();
416        facts
417            .add_value("name", Value::String("John".to_string()))
418            .unwrap();
419
420        // Get facts
421        assert_eq!(facts.get("age"), Some(Value::Integer(25)));
422        assert_eq!(facts.get("name"), Some(Value::String("John".to_string())));
423
424        // Count
425        assert_eq!(facts.count(), 2);
426
427        // Contains
428        assert!(facts.contains("age"));
429        assert!(!facts.contains("email"));
430    }
431
432    #[test]
433    fn test_nested_facts() {
434        let facts = Facts::new();
435        let user = FactHelper::create_user("John", 25, "john@example.com", "US", true);
436
437        facts.add_value("User", user).unwrap();
438
439        // Get nested values
440        assert_eq!(facts.get_nested("User.Age"), Some(Value::Integer(25)));
441        assert_eq!(
442            facts.get_nested("User.Name"),
443            Some(Value::String("John".to_string()))
444        );
445
446        // Set nested values
447        facts.set_nested("User.Age", Value::Integer(26)).unwrap();
448        assert_eq!(facts.get_nested("User.Age"), Some(Value::Integer(26)));
449    }
450
451    #[test]
452    fn test_facts_snapshot() {
453        let facts = Facts::new();
454        facts
455            .add_value("test", Value::String("value".to_string()))
456            .unwrap();
457
458        let snapshot = facts.snapshot();
459
460        facts.clear();
461        assert_eq!(facts.count(), 0);
462
463        facts.restore(snapshot);
464        assert_eq!(facts.count(), 1);
465        assert_eq!(facts.get("test"), Some(Value::String("value".to_string())));
466    }
467}