Skip to main content

json_eval_rs/jsoneval/
eval_data.rs

1use serde_json::{Map, Value};
2use std::borrow::Cow;
3use std::sync::{
4    atomic::{AtomicU64, Ordering},
5    Arc,
6};
7
8use crate::jsoneval::path_utils;
9
10static NEXT_INSTANCE_ID: AtomicU64 = AtomicU64::new(0);
11
12/// Version tracker for data mutations
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub struct DataVersion(pub u64);
15
16/// Tracked data wrapper that gates all mutations for safety
17///
18/// # Design Philosophy
19///
20/// EvalData serves as the single gatekeeper for all data mutations in the system.
21/// All write operations (set, push_to_array, get_mut, etc.) MUST go through this
22/// type to ensure proper version tracking and mutation safety.
23///
24/// This design provides:
25/// - Thread-safe mutation tracking via version numbers
26/// - Copy-on-Write (CoW) semantics via Arc for efficient cloning
27/// - Single point of control for all data state changes
28/// - Prevention of untracked mutations that could cause race conditions
29///
30/// # CoW Behavior
31///
32/// - Read operations are zero-cost (direct Arc dereference)
33/// - Clone operations are cheap (Arc reference counting)
34/// - First mutation triggers deep clone via Arc::make_mut
35/// - Subsequent mutations on exclusive owner are zero-cost
36pub struct EvalData {
37    instance_id: u64,
38    data: Arc<Value>,
39}
40
41impl EvalData {
42    /// Create a new tracked data wrapper
43    pub fn new(data: Value) -> Self {
44        Self {
45            instance_id: NEXT_INSTANCE_ID.fetch_add(1, Ordering::Relaxed),
46            data: Arc::new(data),
47        }
48    }
49
50    /// Initialize eval data with zero-copy references to evaluated_schema, input_data, and context_data
51    /// This avoids cloning by directly constructing the data structure with borrowed references
52    pub fn with_schema_data_context(
53        evaluated_schema: &Value,
54        input_data: &Value,
55        context_data: &Value,
56    ) -> Self {
57        let mut data_map = Map::new();
58
59        // Insert $params from evaluated_schema (clone only the reference, not deep clone)
60        if let Some(params) = evaluated_schema.get("$params") {
61            data_map.insert("$params".to_string(), params.clone());
62        }
63
64        // Merge input_data into the root level
65        if let Value::Object(input_obj) = input_data {
66            for (key, value) in input_obj {
67                data_map.insert(key.clone(), value.clone());
68            }
69        }
70
71        // Insert context
72        data_map.insert("$context".to_string(), context_data.clone());
73
74        Self::new(Value::Object(data_map))
75    }
76
77    /// Replace data and context in existing EvalData (for evaluation updates)
78    /// Uses CoW: replaces Arc, no clone needed if not shared
79    pub fn replace_data_and_context(&mut self, input_data: Value, context_data: Value) {
80        let data = Arc::make_mut(&mut self.data); // CoW: clone only if shared
81        input_data
82            .as_object()
83            .unwrap()
84            .iter()
85            .for_each(|(key, value)| {
86                Self::set_by_pointer(data, &format!("/{key}"), value.clone());
87            });
88        Self::set_by_pointer(data, "/$context", context_data);
89    }
90
91    /// Get the unique instance ID
92    #[inline(always)]
93    pub fn instance_id(&self) -> u64 {
94        self.instance_id
95    }
96
97    /// Get a reference to the underlying data (read-only)
98    /// Zero-cost access via Arc dereference
99    #[inline(always)]
100    pub fn data(&self) -> &Value {
101        &*self.data
102    }
103
104    /// Clone a Value without certain keys
105    #[inline(always)]
106    pub fn snapshot_data(&self) -> Arc<Value> {
107        Arc::clone(&self.data)
108    }
109
110    /// Set a field value and increment version
111    /// Accepts both dotted notation (user.name) and JSON pointer format (/user/name)
112    /// Uses CoW: clones data only if shared
113    pub fn set(&mut self, path: &str, value: Value) {
114        // Normalize to JSON pointer format internally
115        let pointer = path_utils::normalize_to_json_pointer(path);
116        let data = Arc::make_mut(&mut self.data); // CoW: clone only if shared
117        Self::set_by_pointer(data, &pointer, value);
118    }
119
120    /// Append to an array field without full clone (optimized for table building)
121    /// Accepts both dotted notation (items) and JSON pointer format (/items)
122    /// Uses CoW: clones data only if shared
123    pub fn push_to_array(&mut self, path: &str, value: Value) {
124        // Normalize to JSON pointer format internally
125        let pointer = path_utils::normalize_to_json_pointer(path);
126        let data = Arc::make_mut(&mut self.data); // CoW: clone only if shared
127        if let Some(arr) = data.pointer_mut(&pointer) {
128            if let Some(array) = arr.as_array_mut() {
129                array.push(value);
130            }
131        }
132    }
133
134    /// Get a field value
135    /// Accepts both dotted notation (user.name) and JSON pointer format (/user/name)
136    #[inline]
137    pub fn get(&self, path: &str) -> Option<&Value> {
138        // Normalize to JSON pointer format internally
139        let pointer = path_utils::normalize_to_json_pointer(path);
140        // Use native serde_json pointer access for best performance
141        path_utils::get_value_by_pointer(&self.data, &pointer)
142    }
143
144    #[inline]
145    pub fn get_without_properties(&self, path: &str) -> Option<&Value> {
146        // Normalize to JSON pointer format internally
147        let pointer = path_utils::normalize_to_json_pointer(path);
148        // Use native serde_json pointer access for best performance
149        path_utils::get_value_by_pointer_without_properties(&self.data, &pointer)
150    }
151
152    /// OPTIMIZED: Fast array element access
153    #[inline]
154    pub fn get_array_element(&self, array_path: &str, index: usize) -> Option<&Value> {
155        let pointer = path_utils::normalize_to_json_pointer(array_path);
156        path_utils::get_array_element_by_pointer(&self.data, &pointer, index)
157    }
158
159    /// Get a mutable reference to a field value
160    /// Accepts both dotted notation and JSON pointer format
161    /// Uses CoW: clones data only if shared
162    /// Note: Caller must manually increment version after mutation
163    pub fn get_mut(&mut self, path: &str) -> Option<&mut Value> {
164        // Normalize to JSON pointer format internally
165        let pointer = path_utils::normalize_to_json_pointer(path);
166        let data = Arc::make_mut(&mut self.data); // CoW: clone only if shared
167        if pointer.is_empty() {
168            Some(data)
169        } else {
170            data.pointer_mut(&pointer)
171        }
172    }
173
174    /// Get a mutable reference to a table row object at path[index]
175    /// Accepts both dotted notation and JSON pointer format
176    /// Uses CoW: clones data only if shared
177    /// Returns None if path is not an array or row is not an object
178    #[inline(always)]
179    pub fn get_table_row_mut(
180        &mut self,
181        path: &str,
182        index: usize,
183    ) -> Option<&mut Map<String, Value>> {
184        // Normalize to JSON pointer format internally
185        let pointer = path_utils::normalize_to_json_pointer(path);
186        let data = Arc::make_mut(&mut self.data); // CoW: clone only if shared
187        let array = if pointer.is_empty() {
188            data
189        } else {
190            data.pointer_mut(&pointer)?
191        };
192        array.as_array_mut()?.get_mut(index)?.as_object_mut()
193    }
194
195    /// Get multiple field values efficiently (for cache key generation)
196    /// OPTIMIZED: Use batch pointer resolution for better performance
197    pub fn get_values<'a>(&'a self, paths: &'a [String]) -> Vec<Cow<'a, Value>> {
198        // Convert all paths to JSON pointers for batch processing
199        let pointers: Vec<String> = paths
200            .iter()
201            .map(|path| path_utils::normalize_to_json_pointer(path).into_owned())
202            .collect();
203
204        // Batch pointer resolution
205        path_utils::get_values_by_pointers(&self.data, &pointers)
206            .into_iter()
207            .map(|opt_val| {
208                opt_val
209                    .map(Cow::Borrowed)
210                    .unwrap_or(Cow::Owned(Value::Null))
211            })
212            .collect()
213    }
214
215    /// Set a value by JSON pointer, creating intermediate structures as needed
216    fn set_by_pointer(data: &mut Value, pointer: &str, new_value: Value) {
217        if pointer.is_empty() {
218            return;
219        }
220
221        // Split pointer into segments (remove leading /)
222        let path = &pointer[1..];
223        let segments: Vec<&str> = path.split('/').collect();
224
225        if segments.is_empty() {
226            return;
227        }
228
229        // Navigate to parent, creating intermediate structures
230        let mut current = data;
231        for (i, segment) in segments.iter().enumerate() {
232            let is_last = i == segments.len() - 1;
233
234            // Try to parse as array index
235            if let Ok(index) = segment.parse::<usize>() {
236                // Current should be an array
237                if !current.is_array() {
238                    return; // Cannot index into non-array
239                }
240
241                let arr = current.as_array_mut().unwrap();
242
243                // Extend array if needed
244                while arr.len() <= index {
245                    arr.push(if is_last {
246                        Value::Null
247                    } else {
248                        Value::Object(Map::new())
249                    });
250                }
251
252                if is_last {
253                    arr[index] = new_value;
254                    return;
255                } else {
256                    current = &mut arr[index];
257                }
258            } else {
259                // Object key access
260                if !current.is_object() {
261                    return; // Cannot access key on non-object
262                }
263
264                let map = current.as_object_mut().unwrap();
265
266                if is_last {
267                    map.insert(segment.to_string(), new_value);
268                    return;
269                } else {
270                    current = map
271                        .entry(segment.to_string())
272                        .or_insert_with(|| Value::Object(Map::new()));
273                }
274            }
275        }
276    }
277}
278
279impl From<Value> for EvalData {
280    fn from(value: Value) -> Self {
281        Self::new(value)
282    }
283}
284
285impl Clone for EvalData {
286    fn clone(&self) -> Self {
287        Self {
288            instance_id: self.instance_id, // Keep same ID for clones
289            data: Arc::clone(&self.data),  // CoW: cheap Arc clone (ref count only)
290        }
291    }
292}