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 /// Wrap an existing `Arc<Value>` without any allocation or deep clone.
51 ///
52 /// Use this when a read-only view of already-Arc'd data is needed (e.g. a
53 /// batch snapshot in `evaluate_internal`). Mutations on the returned instance
54 /// will trigger `Arc::make_mut` copy-on-write only on the first write.
55 #[inline]
56 pub fn from_arc(data: Arc<Value>) -> Self {
57 Self {
58 instance_id: NEXT_INSTANCE_ID.fetch_add(1, Ordering::Relaxed),
59 data,
60 }
61 }
62
63 /// Initialize eval data with zero-copy references to evaluated_schema, input_data, and context_data
64 /// This avoids cloning by directly constructing the data structure with borrowed references
65 pub fn with_schema_data_context(
66 evaluated_schema: &Value,
67 input_data: &Value,
68 context_data: &Value,
69 ) -> Self {
70 let mut data_map = Map::new();
71
72 // Insert $params from evaluated_schema (clone only the reference, not deep clone)
73 if let Some(params) = evaluated_schema.get("$params") {
74 data_map.insert("$params".to_string(), params.clone());
75 }
76
77 // Merge input_data into the root level
78 if let Value::Object(input_obj) = input_data {
79 for (key, value) in input_obj {
80 data_map.insert(key.clone(), value.clone());
81 }
82 }
83
84 // Insert context
85 data_map.insert("$context".to_string(), context_data.clone());
86
87 Self::new(Value::Object(data_map))
88 }
89
90 /// Replace data and context in existing EvalData (for evaluation updates)
91 /// Uses CoW: replaces Arc, no clone needed if not shared
92 pub fn replace_data_and_context(&mut self, input_data: Value, context_data: Value) {
93 let data = Arc::make_mut(&mut self.data); // CoW: clone only if shared
94 input_data
95 .as_object()
96 .unwrap()
97 .iter()
98 .for_each(|(key, value)| {
99 Self::set_by_pointer(data, &format!("/{key}"), value.clone());
100 });
101 Self::set_by_pointer(data, "/$context", context_data);
102 }
103
104 /// Get the unique instance ID
105 #[inline(always)]
106 pub fn instance_id(&self) -> u64 {
107 self.instance_id
108 }
109
110 /// Get a reference to the underlying data (read-only)
111 /// Zero-cost access via Arc dereference
112 #[inline(always)]
113 pub fn data(&self) -> &Value {
114 &*self.data
115 }
116
117 /// Clone a Value without certain keys
118 #[inline(always)]
119 pub fn snapshot_data(&self) -> Arc<Value> {
120 Arc::clone(&self.data)
121 }
122
123 /// Returns a deep clone of the current data for diffing before it gets replaced
124 #[inline]
125 pub fn snapshot_data_clone(&self) -> Value {
126 (*self.data).clone()
127 }
128
129 /// Deep-clone into a new, exclusive EvalData (Arc strong count = 1).
130 ///
131 /// Unlike `clone()` which bumps the Arc reference count (causing `Arc::make_mut`
132 /// to reallocate on the first mutation), this copies the inner Value once and
133 /// wraps it in a fresh Arc. All subsequent `set()` / `push_to_array()` calls
134 /// on the returned instance are zero-cost because the Arc is always exclusive.
135 #[inline]
136 pub fn exclusive_clone(&self) -> Self {
137 Self::new((*self.data).clone())
138 }
139
140 /// Set a field value and increment version
141 /// Accepts both dotted notation (user.name) and JSON pointer format (/user/name)
142 /// Uses CoW: clones data only if shared
143 pub fn set(&mut self, path: &str, value: Value) {
144 // Normalize to JSON pointer format internally
145 let pointer = path_utils::normalize_to_json_pointer(path);
146 let data = Arc::make_mut(&mut self.data); // CoW: clone only if shared
147 Self::set_by_pointer(data, &pointer, value);
148 }
149
150 /// Append to an array field without full clone (optimized for table building)
151 /// Accepts both dotted notation (items) and JSON pointer format (/items)
152 /// Uses CoW: clones data only if shared
153 pub fn push_to_array(&mut self, path: &str, value: Value) {
154 // Normalize to JSON pointer format internally
155 let pointer = path_utils::normalize_to_json_pointer(path);
156 let data = Arc::make_mut(&mut self.data); // CoW: clone only if shared
157 if let Some(arr) = data.pointer_mut(&pointer) {
158 if let Some(array) = arr.as_array_mut() {
159 array.push(value);
160 }
161 }
162 }
163
164 /// Get a field value
165 /// Accepts both dotted notation (user.name) and JSON pointer format (/user/name)
166 #[inline]
167 pub fn get(&self, path: &str) -> Option<&Value> {
168 // Normalize to JSON pointer format internally
169 let pointer = path_utils::normalize_to_json_pointer(path);
170 // Use native serde_json pointer access for best performance
171 path_utils::get_value_by_pointer(&self.data, &pointer)
172 }
173
174 #[inline]
175 pub fn get_without_properties(&self, path: &str) -> Option<&Value> {
176 // Normalize to JSON pointer format internally
177 let pointer = path_utils::normalize_to_json_pointer(path);
178 // Use native serde_json pointer access for best performance
179 path_utils::get_value_by_pointer_without_properties(&self.data, &pointer)
180 }
181
182 /// OPTIMIZED: Fast array element access
183 #[inline]
184 pub fn get_array_element(&self, array_path: &str, index: usize) -> Option<&Value> {
185 let pointer = path_utils::normalize_to_json_pointer(array_path);
186 path_utils::get_array_element_by_pointer(&self.data, &pointer, index)
187 }
188
189 /// Get a mutable reference to a field value
190 /// Accepts both dotted notation and JSON pointer format
191 /// Uses CoW: clones data only if shared
192 /// Note: Caller must manually increment version after mutation
193 pub fn get_mut(&mut self, path: &str) -> Option<&mut Value> {
194 // Normalize to JSON pointer format internally
195 let pointer = path_utils::normalize_to_json_pointer(path);
196 let data = Arc::make_mut(&mut self.data); // CoW: clone only if shared
197 if pointer.is_empty() {
198 Some(data)
199 } else {
200 data.pointer_mut(&pointer)
201 }
202 }
203
204 /// Get a mutable reference to a table row object at path[index]
205 /// Accepts both dotted notation and JSON pointer format
206 /// Uses CoW: clones data only if shared
207 /// Returns None if path is not an array or row is not an object
208 #[inline(always)]
209 pub fn get_table_row_mut(
210 &mut self,
211 path: &str,
212 index: usize,
213 ) -> Option<&mut Map<String, Value>> {
214 // Normalize to JSON pointer format internally
215 let pointer = path_utils::normalize_to_json_pointer(path);
216 let data = Arc::make_mut(&mut self.data); // CoW: clone only if shared
217 let array = if pointer.is_empty() {
218 data
219 } else {
220 data.pointer_mut(&pointer)?
221 };
222 array.as_array_mut()?.get_mut(index)?.as_object_mut()
223 }
224
225 /// Get a mutable reference to a table row object using pre-parsed segments
226 /// This bypasses repetitive JSON pointer string parsing and allocation
227 #[inline(always)]
228 pub fn get_table_row_mut_by_segments(
229 &mut self,
230 segments: &[&str],
231 index: usize,
232 ) -> Option<&mut Map<String, Value>> {
233 let mut target = Arc::make_mut(&mut self.data);
234 for &segment in segments {
235 target = match target {
236 Value::Object(map) => map.get_mut(segment)?,
237 Value::Array(list) => {
238 let idx = segment.parse::<usize>().ok()?;
239 list.get_mut(idx)?
240 }
241 _ => return None,
242 };
243 }
244 target.as_array_mut()?.get_mut(index)?.as_object_mut()
245 }
246
247 /// Get multiple field values efficiently (for cache key generation)
248 /// OPTIMIZED: Use batch pointer resolution for better performance
249 pub fn get_values<'a>(&'a self, paths: &'a [String]) -> Vec<Cow<'a, Value>> {
250 // Convert all paths to JSON pointers for batch processing
251 let pointers: Vec<String> = paths
252 .iter()
253 .map(|path| path_utils::normalize_to_json_pointer(path).into_owned())
254 .collect();
255
256 // Batch pointer resolution
257 path_utils::get_values_by_pointers(&self.data, &pointers)
258 .into_iter()
259 .map(|opt_val| {
260 opt_val
261 .map(Cow::Borrowed)
262 .unwrap_or(Cow::Owned(Value::Null))
263 })
264 .collect()
265 }
266
267 /// Set a value by JSON pointer, creating intermediate structures as needed
268 fn set_by_pointer(data: &mut Value, pointer: &str, new_value: Value) {
269 if pointer.is_empty() {
270 return;
271 }
272
273 // Split pointer into segments (remove leading /)
274 let path = &pointer[1..];
275 let segments: Vec<&str> = path.split('/').collect();
276
277 if segments.is_empty() {
278 return;
279 }
280
281 // Navigate to parent, creating intermediate structures
282 let mut current = data;
283 for (i, segment) in segments.iter().enumerate() {
284 let is_last = i == segments.len() - 1;
285
286 // Try to parse as array index
287 if let Ok(index) = segment.parse::<usize>() {
288 // Current should be an array
289 if !current.is_array() {
290 return; // Cannot index into non-array
291 }
292
293 let arr = current.as_array_mut().unwrap();
294
295 // Extend array if needed
296 while arr.len() <= index {
297 arr.push(if is_last {
298 Value::Null
299 } else {
300 Value::Object(Map::new())
301 });
302 }
303
304 if is_last {
305 arr[index] = new_value;
306 return;
307 } else {
308 current = &mut arr[index];
309 }
310 } else {
311 // Object key access
312 if !current.is_object() {
313 return; // Cannot access key on non-object
314 }
315
316 let map = current.as_object_mut().unwrap();
317
318 if is_last {
319 map.insert(segment.to_string(), new_value);
320 return;
321 } else {
322 let next_segment = segments[i + 1];
323 let is_array_next = next_segment.parse::<usize>().is_ok();
324
325 current = map.entry(segment.to_string()).or_insert_with(|| {
326 if is_array_next {
327 Value::Array(Vec::new())
328 } else {
329 Value::Object(Map::new())
330 }
331 });
332 }
333 }
334 }
335 }
336}
337
338impl From<Value> for EvalData {
339 fn from(value: Value) -> Self {
340 Self::new(value)
341 }
342}
343
344impl Clone for EvalData {
345 fn clone(&self) -> Self {
346 Self {
347 instance_id: self.instance_id, // Keep same ID for clones
348 data: Arc::clone(&self.data), // CoW: cheap Arc clone (ref count only)
349 }
350 }
351}