1#[cfg(windows)]
11#[global_allocator]
12static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
13
14pub mod rlogic;
15pub mod table_evaluate;
16pub mod table_metadata;
17pub mod topo_sort;
18pub mod parse_schema;
19
20pub mod parsed_schema;
21pub mod parsed_schema_cache;
22pub mod json_parser;
23pub mod path_utils;
24pub mod eval_data;
25pub mod eval_cache;
26pub mod subform_methods;
27
28#[cfg(feature = "ffi")]
30pub mod ffi;
31
32#[cfg(feature = "wasm")]
34pub mod wasm;
35
36use indexmap::{IndexMap, IndexSet};
38pub use rlogic::{
39 CompiledLogic, CompiledLogicStore, Evaluator,
40 LogicId, RLogic, RLogicConfig,
41 CompiledLogicId, CompiledLogicStoreStats,
42};
43use serde::{Deserialize, Serialize};
44pub use table_metadata::TableMetadata;
45pub use path_utils::ArrayMetadata;
46pub use eval_data::EvalData;
47pub use eval_cache::{EvalCache, CacheKey, CacheStats};
48pub use parsed_schema::ParsedSchema;
49pub use parsed_schema_cache::{ParsedSchemaCache, ParsedSchemaCacheStats, PARSED_SCHEMA_CACHE};
50use serde::de::Error as _;
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
54pub enum ReturnFormat {
55 #[default]
58 Nested,
59 Flat,
62 Array,
65}
66use serde_json::{Value};
67
68#[cfg(feature = "parallel")]
69use rayon::prelude::*;
70
71use std::mem;
72use std::sync::{Arc, Mutex};
73use std::time::Instant;
74use std::cell::RefCell;
75
76thread_local! {
78 static TIMING_ENABLED: RefCell<bool> = RefCell::new(std::env::var("JSONEVAL_TIMING").is_ok());
79 static TIMING_DATA: RefCell<Vec<(String, std::time::Duration)>> = RefCell::new(Vec::new());
80}
81
82#[inline]
84fn is_timing_enabled() -> bool {
85 TIMING_ENABLED.with(|enabled| *enabled.borrow())
86}
87
88pub fn enable_timing() {
90 TIMING_ENABLED.with(|enabled| {
91 *enabled.borrow_mut() = true;
92 });
93}
94
95pub fn disable_timing() {
97 TIMING_ENABLED.with(|enabled| {
98 *enabled.borrow_mut() = false;
99 });
100}
101
102#[inline]
104fn record_timing(label: &str, duration: std::time::Duration) {
105 if is_timing_enabled() {
106 TIMING_DATA.with(|data| {
107 data.borrow_mut().push((label.to_string(), duration));
108 });
109 }
110}
111
112pub fn print_timing_summary() {
114 if !is_timing_enabled() {
115 return;
116 }
117
118 TIMING_DATA.with(|data| {
119 let timings = data.borrow();
120 if timings.is_empty() {
121 return;
122 }
123
124 eprintln!("\nš Timing Summary (JSONEVAL_TIMING enabled)");
125 eprintln!("{}", "=".repeat(60));
126
127 let mut total = std::time::Duration::ZERO;
128 for (label, duration) in timings.iter() {
129 eprintln!("{:40} {:>12?}", label, duration);
130 total += *duration;
131 }
132
133 eprintln!("{}", "=".repeat(60));
134 eprintln!("{:40} {:>12?}", "TOTAL", total);
135 eprintln!();
136 });
137}
138
139pub fn clear_timing_data() {
141 TIMING_DATA.with(|data| {
142 data.borrow_mut().clear();
143 });
144}
145
146macro_rules! time_block {
148 ($label:expr, $block:block) => {{
149 let _start = if is_timing_enabled() {
150 Some(Instant::now())
151 } else {
152 None
153 };
154 let result = $block;
155 if let Some(start) = _start {
156 record_timing($label, start.elapsed());
157 }
158 result
159 }};
160}
161
162pub fn version() -> &'static str {
164 env!("CARGO_PKG_VERSION")
165}
166
167fn clean_float_noise(value: Value) -> Value {
170 const EPSILON: f64 = 1e-10;
171
172 match value {
173 Value::Number(n) => {
174 if let Some(f) = n.as_f64() {
175 if f.abs() < EPSILON {
176 Value::Number(serde_json::Number::from(0))
178 } else if f.fract().abs() < EPSILON {
179 Value::Number(serde_json::Number::from(f.round() as i64))
181 } else {
182 Value::Number(n)
183 }
184 } else {
185 Value::Number(n)
186 }
187 }
188 Value::Array(arr) => {
189 Value::Array(arr.into_iter().map(clean_float_noise).collect())
190 }
191 Value::Object(obj) => {
192 Value::Object(obj.into_iter().map(|(k, v)| (k, clean_float_noise(v))).collect())
193 }
194 _ => value,
195 }
196}
197
198#[derive(Debug, Clone, Serialize, Deserialize)]
200pub struct DependentItem {
201 pub ref_path: String,
202 pub clear: Option<Value>, pub value: Option<Value>, }
205
206pub struct JSONEval {
207 pub schema: Arc<Value>,
208 pub engine: Arc<RLogic>,
209 pub evaluations: Arc<IndexMap<String, LogicId>>,
211 pub tables: Arc<IndexMap<String, Value>>,
212 pub table_metadata: Arc<IndexMap<String, TableMetadata>>,
214 pub dependencies: Arc<IndexMap<String, IndexSet<String>>>,
215 pub sorted_evaluations: Arc<Vec<Vec<String>>>,
218 pub dependents_evaluations: Arc<IndexMap<String, Vec<DependentItem>>>,
221 pub rules_evaluations: Arc<Vec<String>>,
223 pub fields_with_rules: Arc<Vec<String>>,
225 pub others_evaluations: Arc<Vec<String>>,
227 pub value_evaluations: Arc<Vec<String>>,
229 pub layout_paths: Arc<Vec<String>>,
231 pub options_templates: Arc<Vec<(String, String, String)>>,
233 pub subforms: IndexMap<String, Box<JSONEval>>,
236 pub context: Value,
237 pub data: Value,
238 pub evaluated_schema: Value,
239 pub eval_data: EvalData,
240 pub eval_cache: EvalCache,
242 pub cache_enabled: bool,
245 eval_lock: Mutex<()>,
247 cached_msgpack_schema: Option<Vec<u8>>,
250}
251
252impl Clone for JSONEval {
253 fn clone(&self) -> Self {
254 Self {
255 cache_enabled: self.cache_enabled,
256 schema: Arc::clone(&self.schema),
257 engine: Arc::clone(&self.engine),
258 evaluations: self.evaluations.clone(),
259 tables: self.tables.clone(),
260 table_metadata: self.table_metadata.clone(),
261 dependencies: self.dependencies.clone(),
262 sorted_evaluations: self.sorted_evaluations.clone(),
263 dependents_evaluations: self.dependents_evaluations.clone(),
264 rules_evaluations: self.rules_evaluations.clone(),
265 fields_with_rules: self.fields_with_rules.clone(),
266 others_evaluations: self.others_evaluations.clone(),
267 value_evaluations: self.value_evaluations.clone(),
268 layout_paths: self.layout_paths.clone(),
269 options_templates: self.options_templates.clone(),
270 subforms: self.subforms.clone(),
271 context: self.context.clone(),
272 data: self.data.clone(),
273 evaluated_schema: self.evaluated_schema.clone(),
274 eval_data: self.eval_data.clone(),
275 eval_cache: EvalCache::new(), eval_lock: Mutex::new(()), cached_msgpack_schema: self.cached_msgpack_schema.clone(),
278 }
279 }
280}
281
282impl JSONEval {
283 pub fn new(
284 schema: &str,
285 context: Option<&str>,
286 data: Option<&str>,
287 ) -> Result<Self, serde_json::Error> {
288 time_block!("JSONEval::new() [total]", {
289 let schema_val: Value = time_block!(" parse schema JSON", {
291 serde_json::from_str(schema)?
292 });
293 let context: Value = time_block!(" parse context JSON", {
294 json_parser::parse_json_str(context.unwrap_or("{}")).map_err(serde_json::Error::custom)?
295 });
296 let data: Value = time_block!(" parse data JSON", {
297 json_parser::parse_json_str(data.unwrap_or("{}")).map_err(serde_json::Error::custom)?
298 });
299 let evaluated_schema = schema_val.clone();
300 let engine_config = RLogicConfig::default();
302
303 let mut instance = time_block!(" create instance struct", {
304 Self {
305 schema: Arc::new(schema_val),
306 evaluations: Arc::new(IndexMap::new()),
307 tables: Arc::new(IndexMap::new()),
308 table_metadata: Arc::new(IndexMap::new()),
309 dependencies: Arc::new(IndexMap::new()),
310 sorted_evaluations: Arc::new(Vec::new()),
311 dependents_evaluations: Arc::new(IndexMap::new()),
312 rules_evaluations: Arc::new(Vec::new()),
313 fields_with_rules: Arc::new(Vec::new()),
314 others_evaluations: Arc::new(Vec::new()),
315 value_evaluations: Arc::new(Vec::new()),
316 layout_paths: Arc::new(Vec::new()),
317 options_templates: Arc::new(Vec::new()),
318 subforms: IndexMap::new(),
319 engine: Arc::new(RLogic::with_config(engine_config)),
320 context: context.clone(),
321 data: data.clone(),
322 evaluated_schema: evaluated_schema.clone(),
323 eval_data: EvalData::with_schema_data_context(&evaluated_schema, &data, &context),
324 eval_cache: EvalCache::new(),
325 cache_enabled: true, eval_lock: Mutex::new(()),
327 cached_msgpack_schema: None, }
329 });
330 time_block!(" parse_schema", {
331 parse_schema::legacy::parse_schema(&mut instance).map_err(serde_json::Error::custom)?
332 });
333 Ok(instance)
334 })
335 }
336
337 pub fn new_from_msgpack(
349 schema_msgpack: &[u8],
350 context: Option<&str>,
351 data: Option<&str>,
352 ) -> Result<Self, String> {
353 let cached_msgpack = schema_msgpack.to_vec();
355
356 let schema_val: Value = rmp_serde::from_slice(schema_msgpack)
358 .map_err(|e| format!("Failed to deserialize MessagePack schema: {}", e))?;
359
360 let context: Value = json_parser::parse_json_str(context.unwrap_or("{}"))
361 .map_err(|e| format!("Failed to parse context: {}", e))?;
362 let data: Value = json_parser::parse_json_str(data.unwrap_or("{}"))
363 .map_err(|e| format!("Failed to parse data: {}", e))?;
364 let evaluated_schema = schema_val.clone();
365 let engine_config = RLogicConfig::default();
366
367 let mut instance = Self {
368 schema: Arc::new(schema_val),
369 evaluations: Arc::new(IndexMap::new()),
370 tables: Arc::new(IndexMap::new()),
371 table_metadata: Arc::new(IndexMap::new()),
372 dependencies: Arc::new(IndexMap::new()),
373 sorted_evaluations: Arc::new(Vec::new()),
374 dependents_evaluations: Arc::new(IndexMap::new()),
375 rules_evaluations: Arc::new(Vec::new()),
376 fields_with_rules: Arc::new(Vec::new()),
377 others_evaluations: Arc::new(Vec::new()),
378 value_evaluations: Arc::new(Vec::new()),
379 layout_paths: Arc::new(Vec::new()),
380 options_templates: Arc::new(Vec::new()),
381 subforms: IndexMap::new(),
382 engine: Arc::new(RLogic::with_config(engine_config)),
383 context: context.clone(),
384 data: data.clone(),
385 evaluated_schema: evaluated_schema.clone(),
386 eval_data: EvalData::with_schema_data_context(&evaluated_schema, &data, &context),
387 eval_cache: EvalCache::new(),
388 cache_enabled: true, eval_lock: Mutex::new(()),
390 cached_msgpack_schema: Some(cached_msgpack), };
392 parse_schema::legacy::parse_schema(&mut instance)?;
393 Ok(instance)
394 }
395
396 pub fn with_parsed_schema(
424 parsed: Arc<ParsedSchema>,
425 context: Option<&str>,
426 data: Option<&str>,
427 ) -> Result<Self, String> {
428 let context: Value = json_parser::parse_json_str(context.unwrap_or("{}"))
429 .map_err(|e| format!("Failed to parse context: {}", e))?;
430 let data: Value = json_parser::parse_json_str(data.unwrap_or("{}"))
431 .map_err(|e| format!("Failed to parse data: {}", e))?;
432
433 let evaluated_schema = parsed.schema.clone();
434
435 let engine = parsed.engine.clone();
438
439 let mut subforms = IndexMap::new();
442 for (path, subform_parsed) in &parsed.subforms {
443 let subform_eval = JSONEval::with_parsed_schema(
445 subform_parsed.clone(),
446 Some("{}"),
447 None
448 )?;
449 subforms.insert(path.clone(), Box::new(subform_eval));
450 }
451
452 let instance = Self {
453 schema: Arc::clone(&parsed.schema),
454 evaluations: Arc::clone(&parsed.evaluations),
456 tables: Arc::clone(&parsed.tables),
457 table_metadata: Arc::clone(&parsed.table_metadata),
458 dependencies: Arc::clone(&parsed.dependencies),
459 sorted_evaluations: Arc::clone(&parsed.sorted_evaluations),
460 dependents_evaluations: Arc::clone(&parsed.dependents_evaluations),
461 rules_evaluations: Arc::clone(&parsed.rules_evaluations),
462 fields_with_rules: Arc::clone(&parsed.fields_with_rules),
463 others_evaluations: Arc::clone(&parsed.others_evaluations),
464 value_evaluations: Arc::clone(&parsed.value_evaluations),
465 layout_paths: Arc::clone(&parsed.layout_paths),
466 options_templates: Arc::clone(&parsed.options_templates),
467 subforms,
468 engine,
469 context: context.clone(),
470 data: data.clone(),
471 evaluated_schema: (*evaluated_schema).clone(),
472 eval_data: EvalData::with_schema_data_context(&evaluated_schema, &data, &context),
473 eval_cache: EvalCache::new(),
474 cache_enabled: true, eval_lock: Mutex::new(()),
476 cached_msgpack_schema: None, };
478
479 Ok(instance)
480 }
481
482 pub fn reload_schema(
483 &mut self,
484 schema: &str,
485 context: Option<&str>,
486 data: Option<&str>,
487 ) -> Result<(), String> {
488 let schema_val: Value = serde_json::from_str(schema).map_err(|e| format!("failed to parse schema: {e}"))?;
490 let context: Value = json_parser::parse_json_str(context.unwrap_or("{}"))?;
491 let data: Value = json_parser::parse_json_str(data.unwrap_or("{}"))?;
492 self.schema = Arc::new(schema_val);
493 self.context = context.clone();
494 self.data = data.clone();
495 self.evaluated_schema = (*self.schema).clone();
496 self.engine = Arc::new(RLogic::new());
497 self.dependents_evaluations = Arc::new(IndexMap::new());
498 self.rules_evaluations = Arc::new(Vec::new());
499 self.fields_with_rules = Arc::new(Vec::new());
500 self.others_evaluations = Arc::new(Vec::new());
501 self.value_evaluations = Arc::new(Vec::new());
502 self.layout_paths = Arc::new(Vec::new());
503 self.options_templates = Arc::new(Vec::new());
504 self.subforms.clear();
505 parse_schema::legacy::parse_schema(self)?;
506
507 self.eval_data = EvalData::with_schema_data_context(&self.evaluated_schema, &data, &context);
509
510 self.eval_cache.clear();
512
513 self.cached_msgpack_schema = None;
515
516 Ok(())
517 }
518
519 pub fn set_timezone_offset(&mut self, offset_minutes: Option<i32>) {
541 let mut config = RLogicConfig::default();
543 if let Some(offset) = offset_minutes {
544 config = config.with_timezone_offset(offset);
545 }
546
547 self.engine = Arc::new(RLogic::with_config(config));
550
551 let _ = parse_schema::legacy::parse_schema(self);
554
555 self.eval_cache.clear();
557 }
558
559 pub fn reload_schema_msgpack(
571 &mut self,
572 schema_msgpack: &[u8],
573 context: Option<&str>,
574 data: Option<&str>,
575 ) -> Result<(), String> {
576 let schema_val: Value = rmp_serde::from_slice(schema_msgpack)
578 .map_err(|e| format!("failed to deserialize MessagePack schema: {e}"))?;
579
580 let context: Value = json_parser::parse_json_str(context.unwrap_or("{}"))?;
581 let data: Value = json_parser::parse_json_str(data.unwrap_or("{}"))?;
582
583 self.schema = Arc::new(schema_val);
584 self.context = context.clone();
585 self.data = data.clone();
586 self.evaluated_schema = (*self.schema).clone();
587 self.engine = Arc::new(RLogic::new());
588 self.dependents_evaluations = Arc::new(IndexMap::new());
589 self.rules_evaluations = Arc::new(Vec::new());
590 self.fields_with_rules = Arc::new(Vec::new());
591 self.others_evaluations = Arc::new(Vec::new());
592 self.value_evaluations = Arc::new(Vec::new());
593 self.layout_paths = Arc::new(Vec::new());
594 self.options_templates = Arc::new(Vec::new());
595 self.subforms.clear();
596 parse_schema::legacy::parse_schema(self)?;
597
598 self.eval_data = EvalData::with_schema_data_context(&self.evaluated_schema, &data, &context);
600
601 self.eval_cache.clear();
603
604 self.cached_msgpack_schema = Some(schema_msgpack.to_vec());
606
607 Ok(())
608 }
609
610 pub fn reload_schema_parsed(
624 &mut self,
625 parsed: Arc<ParsedSchema>,
626 context: Option<&str>,
627 data: Option<&str>,
628 ) -> Result<(), String> {
629 let context: Value = json_parser::parse_json_str(context.unwrap_or("{}"))?;
630 let data: Value = json_parser::parse_json_str(data.unwrap_or("{}"))?;
631
632 self.schema = Arc::clone(&parsed.schema);
634 self.evaluations = parsed.evaluations.clone();
635 self.tables = parsed.tables.clone();
636 self.table_metadata = parsed.table_metadata.clone();
637 self.dependencies = parsed.dependencies.clone();
638 self.sorted_evaluations = parsed.sorted_evaluations.clone();
639 self.dependents_evaluations = parsed.dependents_evaluations.clone();
640 self.rules_evaluations = parsed.rules_evaluations.clone();
641 self.fields_with_rules = parsed.fields_with_rules.clone();
642 self.others_evaluations = parsed.others_evaluations.clone();
643 self.value_evaluations = parsed.value_evaluations.clone();
644 self.layout_paths = parsed.layout_paths.clone();
645 self.options_templates = parsed.options_templates.clone();
646
647 self.engine = parsed.engine.clone();
649
650 let mut subforms = IndexMap::new();
652 for (path, subform_parsed) in &parsed.subforms {
653 let subform_eval = JSONEval::with_parsed_schema(
654 subform_parsed.clone(),
655 Some("{}"),
656 None
657 )?;
658 subforms.insert(path.clone(), Box::new(subform_eval));
659 }
660 self.subforms = subforms;
661
662 self.context = context.clone();
663 self.data = data.clone();
664 self.evaluated_schema = (*self.schema).clone();
665
666 self.eval_data = EvalData::with_schema_data_context(&self.evaluated_schema, &data, &context);
668
669 self.eval_cache.clear();
671
672 self.cached_msgpack_schema = None;
674
675 Ok(())
676 }
677
678 pub fn reload_schema_from_cache(
692 &mut self,
693 cache_key: &str,
694 context: Option<&str>,
695 data: Option<&str>,
696 ) -> Result<(), String> {
697 let parsed = PARSED_SCHEMA_CACHE.get(cache_key)
699 .ok_or_else(|| format!("Schema '{}' not found in cache", cache_key))?;
700
701 self.reload_schema_parsed(parsed, context, data)
703 }
704
705 pub fn evaluate(&mut self, data: &str, context: Option<&str>, paths: Option<&[String]>) -> Result<(), String> {
716 time_block!("evaluate() [total]", {
717 let context_provided = context.is_some();
718
719 let data: Value = time_block!(" parse data", {
721 json_parser::parse_json_str(data)?
722 });
723 let context: Value = time_block!(" parse context", {
724 json_parser::parse_json_str(context.unwrap_or("{}"))?
725 });
726
727 self.data = data.clone();
728
729 let changed_data_paths: Vec<String> = if let Some(obj) = data.as_object() {
731 obj.keys().map(|k| k.clone()).collect()
732 } else {
733 Vec::new()
734 };
735
736 time_block!(" replace_data_and_context", {
738 self.eval_data.replace_data_and_context(data, context);
739 });
740
741 time_block!(" purge_cache", {
744 self.purge_cache_for_changed_data(&changed_data_paths);
745
746 if context_provided {
748 self.purge_cache_for_context_change();
749 }
750 });
751
752 self.evaluate_internal(paths)
754 })
755 }
756
757 fn evaluate_internal(&mut self, paths: Option<&[String]>) -> Result<(), String> {
760 time_block!(" evaluate_internal() [total]", {
761 let _lock = self.eval_lock.lock().unwrap();
763
764 let normalized_paths_storage; let normalized_paths = if let Some(p_list) = paths {
767 normalized_paths_storage = p_list.iter()
768 .flat_map(|p| {
769 let normalized = if p.starts_with("#/") {
770 p.to_string()
772 } else if p.starts_with('/') {
773 format!("#{}", p)
775 } else {
776 format!("#/{}", p.replace('.', "/"))
778 };
779
780 vec![normalized]
781 })
782 .collect::<Vec<_>>();
783 Some(normalized_paths_storage.as_slice())
784 } else {
785 None
786 };
787
788 let eval_batches: Vec<Vec<String>> = (*self.sorted_evaluations).clone();
790
791 let eval_data_values = self.eval_data.clone();
796 time_block!(" evaluate values", {
797 #[cfg(feature = "parallel")]
798 if self.value_evaluations.len() > 100 {
799 let value_results: Mutex<Vec<(String, Value)>> = Mutex::new(Vec::with_capacity(self.value_evaluations.len()));
800
801 self.value_evaluations.par_iter().for_each(|eval_key| {
802 if let Some(filter_paths) = normalized_paths {
804 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
805 return;
806 }
807 }
808
809 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
812
813 if let Some(_) = self.try_get_cached(eval_key, &eval_data_values) {
815 return;
816 }
817
818 if let Some(logic_id) = self.evaluations.get(eval_key) {
820 if let Ok(val) = self.engine.run(logic_id, eval_data_values.data()) {
821 let cleaned_val = clean_float_noise(val);
822 self.cache_result(eval_key, Value::Null, &eval_data_values);
824 value_results.lock().unwrap().push((pointer_path, cleaned_val));
825 }
826 }
827 });
828
829 for (result_path, value) in value_results.into_inner().unwrap() {
831 if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&result_path) {
832 *pointer_value = value;
833 }
834 }
835 }
836
837 #[cfg(feature = "parallel")]
839 let value_eval_items = if self.value_evaluations.len() > 100 { &self.value_evaluations[0..0] } else { &self.value_evaluations };
840
841 #[cfg(not(feature = "parallel"))]
842 let value_eval_items = &self.value_evaluations;
843
844 for eval_key in value_eval_items.iter() {
845 if let Some(filter_paths) = normalized_paths {
847 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
848 continue;
849 }
850 }
851
852 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
853
854 if let Some(_) = self.try_get_cached(eval_key, &eval_data_values) {
856 continue;
857 }
858
859 if let Some(logic_id) = self.evaluations.get(eval_key) {
861 if let Ok(val) = self.engine.run(logic_id, eval_data_values.data()) {
862 let cleaned_val = clean_float_noise(val);
863 println!("[DEBUG] Evaluated {} = {:?}", eval_key, cleaned_val);
864 self.cache_result(eval_key, Value::Null, &eval_data_values);
866
867 println!("[DEBUG] pointer_path: {}", pointer_path);
868 if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
869 println!("[DEBUG] Successfully updated pointer");
870 *pointer_value = cleaned_val;
871 } else {
872 println!("[DEBUG] Failed to find pointer in schema");
873 }
874 }
875 } else {
876 println!("[DEBUG] No logic_id found for {}", eval_key);
877 }
878 }
879 });
880
881 time_block!(" process batches", {
882 for batch in eval_batches {
883 if batch.is_empty() {
885 continue;
886 }
887
888 if let Some(filter_paths) = normalized_paths {
891 if !filter_paths.is_empty() {
892 let batch_has_match = batch.iter().any(|eval_key| {
893 filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str()))
894 });
895 if !batch_has_match {
896 continue;
897 }
898 }
899 }
900
901 let eval_data_snapshot = self.eval_data.clone();
908
909 #[cfg(feature = "parallel")]
913 if batch.len() > 1000 {
914 let results: Mutex<Vec<(String, String, Value)>> = Mutex::new(Vec::with_capacity(batch.len()));
915 batch.par_iter().for_each(|eval_key| {
916 if let Some(filter_paths) = normalized_paths {
918 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
919 return;
920 }
921 }
922
923 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
924
925 if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
927 return;
928 }
929
930 let is_table = self.table_metadata.contains_key(eval_key);
932
933 if is_table {
934 if let Ok(rows) = table_evaluate::evaluate_table(self, eval_key, &eval_data_snapshot) {
936 let value = Value::Array(rows);
937 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
939 results.lock().unwrap().push((eval_key.clone(), pointer_path, value));
940 }
941 } else {
942 if let Some(logic_id) = self.evaluations.get(eval_key) {
943 if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
945 let cleaned_val = clean_float_noise(val);
946 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
948 results.lock().unwrap().push((eval_key.clone(), pointer_path, cleaned_val));
949 }
950 }
951 }
952 });
953
954 for (_eval_key, path, value) in results.into_inner().unwrap() {
956 let cleaned_value = clean_float_noise(value);
957
958 self.eval_data.set(&path, cleaned_value.clone());
959 if let Some(schema_value) = self.evaluated_schema.pointer_mut(&path) {
961 *schema_value = cleaned_value;
962 }
963 }
964 continue;
965 }
966
967 #[cfg(not(feature = "parallel"))]
969 let batch_items = &batch;
970
971 #[cfg(feature = "parallel")]
972 let batch_items = if batch.len() > 1000 { &batch[0..0] } else { &batch }; for eval_key in batch_items {
975 if let Some(filter_paths) = normalized_paths {
977 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
978 continue;
979 }
980 }
981
982 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
983
984 if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
986 continue;
987 }
988
989 let is_table = self.table_metadata.contains_key(eval_key);
991
992 if is_table {
993 if let Ok(rows) = table_evaluate::evaluate_table(self, eval_key, &eval_data_snapshot) {
994 let value = Value::Array(rows);
995 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
997
998 let cleaned_value = clean_float_noise(value);
999 self.eval_data.set(&pointer_path, cleaned_value.clone());
1000 if let Some(schema_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
1001 *schema_value = cleaned_value;
1002 }
1003 }
1004 } else {
1005 if let Some(logic_id) = self.evaluations.get(eval_key) {
1006 if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
1007 let cleaned_val = clean_float_noise(val);
1008 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
1010
1011 self.eval_data.set(&pointer_path, cleaned_val.clone());
1012 if let Some(schema_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
1013 *schema_value = cleaned_val;
1014 }
1015 }
1016 }
1017 }
1018 }
1019 }
1020 });
1021
1022 drop(_lock);
1024
1025 self.evaluate_others(paths);
1026
1027 Ok(())
1028 })
1029 }
1030
1031 pub fn get_evaluated_schema(&mut self, skip_layout: bool) -> Value {
1041 time_block!("get_evaluated_schema()", {
1042 if !skip_layout {
1043 self.resolve_layout_internal();
1044 }
1045
1046 self.evaluated_schema.clone()
1047 })
1048 }
1049
1050 pub fn get_evaluated_schema_msgpack(&mut self, skip_layout: bool) -> Result<Vec<u8>, String> {
1067 if !skip_layout {
1068 self.resolve_layout_internal();
1069 }
1070
1071 rmp_serde::to_vec(&self.evaluated_schema)
1075 .map_err(|e| format!("Failed to serialize schema to MessagePack: {}", e))
1076 }
1077
1078 pub fn get_schema_value(&mut self) -> Value {
1082 if !self.data.is_object() {
1084 self.data = Value::Object(serde_json::Map::new());
1085 }
1086
1087 for eval_key in self.value_evaluations.iter() {
1089 let clean_key = eval_key.replace("#", "");
1090 let path = clean_key.replace("/properties", "").replace("/value", "");
1091
1092 let value = match self.evaluated_schema.pointer(&clean_key) {
1094 Some(v) => v.clone(),
1095 None => continue,
1096 };
1097
1098 let path_parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
1100
1101 if path_parts.is_empty() {
1102 continue;
1103 }
1104
1105 let mut current = &mut self.data;
1107 for (i, part) in path_parts.iter().enumerate() {
1108 let is_last = i == path_parts.len() - 1;
1109
1110 if is_last {
1111 if let Some(obj) = current.as_object_mut() {
1113 obj.insert(part.to_string(), clean_float_noise(value.clone()));
1114 }
1115 } else {
1116 if let Some(obj) = current.as_object_mut() {
1118 current = obj.entry(part.to_string())
1119 .or_insert_with(|| Value::Object(serde_json::Map::new()));
1120 } else {
1121 break;
1123 }
1124 }
1125 }
1126 }
1127
1128 clean_float_noise(self.data.clone())
1129 }
1130
1131 pub fn get_evaluated_schema_without_params(&mut self, skip_layout: bool) -> Value {
1142 if !skip_layout {
1143 self.resolve_layout_internal();
1144 }
1145
1146 if let Value::Object(mut map) = self.evaluated_schema.clone() {
1148 map.remove("$params");
1149 Value::Object(map)
1150 } else {
1151 self.evaluated_schema.clone()
1152 }
1153 }
1154
1155 pub fn get_evaluated_schema_by_path(&mut self, path: &str, skip_layout: bool) -> Option<Value> {
1167 if !skip_layout {
1168 self.resolve_layout_internal();
1169 }
1170
1171 let pointer = if path.is_empty() {
1173 "".to_string()
1174 } else {
1175 format!("/{}", path.replace(".", "/"))
1176 };
1177
1178 self.evaluated_schema.pointer(&pointer).cloned()
1179 }
1180
1181 pub fn get_evaluated_schema_by_paths(&mut self, paths: &[String], skip_layout: bool, format: Option<ReturnFormat>) -> Value {
1194 let format = format.unwrap_or_default();
1195 if !skip_layout {
1196 self.resolve_layout_internal();
1197 }
1198
1199 let mut result = serde_json::Map::new();
1200
1201 for path in paths {
1202 let pointer = if path.is_empty() {
1204 "".to_string()
1205 } else {
1206 format!("/{}", path.replace(".", "/"))
1207 };
1208
1209 if let Some(value) = self.evaluated_schema.pointer(&pointer) {
1211 self.insert_at_path(&mut result, path, value.clone());
1214 }
1215 }
1216
1217 self.convert_to_format(result, paths, format)
1218 }
1219
1220 fn insert_at_path(&self, obj: &mut serde_json::Map<String, Value>, path: &str, value: Value) {
1222 if path.is_empty() {
1223 if let Value::Object(map) = value {
1225 for (k, v) in map {
1226 obj.insert(k, v);
1227 }
1228 }
1229 return;
1230 }
1231
1232 let parts: Vec<&str> = path.split('.').collect();
1233 if parts.is_empty() {
1234 return;
1235 }
1236
1237 let mut current = obj;
1238 let last_index = parts.len() - 1;
1239
1240 for (i, part) in parts.iter().enumerate() {
1241 if i == last_index {
1242 current.insert(part.to_string(), value);
1244 break;
1245 } else {
1246 current = current
1248 .entry(part.to_string())
1249 .or_insert_with(|| Value::Object(serde_json::Map::new()))
1250 .as_object_mut()
1251 .unwrap();
1252 }
1253 }
1254 }
1255
1256 fn convert_to_format(&self, result: serde_json::Map<String, Value>, paths: &[String], format: ReturnFormat) -> Value {
1258 match format {
1259 ReturnFormat::Nested => Value::Object(result),
1260 ReturnFormat::Flat => {
1261 let mut flat = serde_json::Map::new();
1263 self.flatten_object(&result, String::new(), &mut flat);
1264 Value::Object(flat)
1265 }
1266 ReturnFormat::Array => {
1267 let values: Vec<Value> = paths.iter()
1269 .map(|path| {
1270 let pointer = if path.is_empty() {
1271 "".to_string()
1272 } else {
1273 format!("/{}", path.replace(".", "/"))
1274 };
1275 Value::Object(result.clone()).pointer(&pointer).cloned().unwrap_or(Value::Null)
1276 })
1277 .collect();
1278 Value::Array(values)
1279 }
1280 }
1281 }
1282
1283 fn flatten_object(&self, obj: &serde_json::Map<String, Value>, prefix: String, result: &mut serde_json::Map<String, Value>) {
1285 for (key, value) in obj {
1286 let new_key = if prefix.is_empty() {
1287 key.clone()
1288 } else {
1289 format!("{}.{}", prefix, key)
1290 };
1291
1292 if let Value::Object(nested) = value {
1293 self.flatten_object(nested, new_key, result);
1294 } else {
1295 result.insert(new_key, value.clone());
1296 }
1297 }
1298 }
1299
1300 pub fn get_schema_by_path(&self, path: &str) -> Option<Value> {
1311 let pointer = if path.is_empty() {
1313 "".to_string()
1314 } else {
1315 format!("/{}", path.replace(".", "/"))
1316 };
1317
1318 self.schema.pointer(&pointer).cloned()
1319 }
1320
1321 pub fn get_schema_by_paths(&self, paths: &[String], format: Option<ReturnFormat>) -> Value {
1333 let format = format.unwrap_or_default();
1334 let mut result = serde_json::Map::new();
1335
1336 for path in paths {
1337 let pointer = if path.is_empty() {
1339 "".to_string()
1340 } else {
1341 format!("/{}", path.replace(".", "/"))
1342 };
1343
1344 if let Some(value) = self.schema.pointer(&pointer) {
1346 self.insert_at_path(&mut result, path, value.clone());
1349 }
1350 }
1351
1352 self.convert_to_format(result, paths, format)
1353 }
1354
1355 #[inline]
1358 fn should_cache_dependency(key: &str) -> bool {
1359 if key.starts_with("/$") || key.starts_with('$') {
1360 key == "$context" || key.starts_with("$context.") || key.starts_with("/$context")
1362 } else {
1363 true
1364 }
1365 }
1366
1367 fn try_get_cached(&self, eval_key: &str, eval_data: &EvalData) -> Option<Value> {
1370 if !self.cache_enabled {
1372 return None;
1373 }
1374
1375 let deps = self.dependencies.get(eval_key)?;
1377
1378 let cache_key = if deps.is_empty() {
1380 CacheKey::simple(eval_key.to_string())
1381 } else {
1382 let filtered_deps: IndexSet<String> = deps
1384 .iter()
1385 .filter(|dep_key| JSONEval::should_cache_dependency(dep_key))
1386 .cloned()
1387 .collect();
1388
1389 let dep_values: Vec<(String, &Value)> = filtered_deps
1391 .iter()
1392 .filter_map(|dep_key| {
1393 eval_data.get(dep_key).map(|v| (dep_key.clone(), v))
1394 })
1395 .collect();
1396
1397 CacheKey::new(eval_key.to_string(), &filtered_deps, &dep_values)
1398 };
1399
1400 self.eval_cache.get(&cache_key).map(|arc_val| (*arc_val).clone())
1402 }
1403
1404 fn cache_result(&self, eval_key: &str, value: Value, eval_data: &EvalData) {
1406 if !self.cache_enabled {
1408 return;
1409 }
1410
1411 let deps = match self.dependencies.get(eval_key) {
1413 Some(d) => d,
1414 None => {
1415 let cache_key = CacheKey::simple(eval_key.to_string());
1417 self.eval_cache.insert(cache_key, value);
1418 return;
1419 }
1420 };
1421
1422 let filtered_deps: IndexSet<String> = deps
1424 .iter()
1425 .filter(|dep_key| JSONEval::should_cache_dependency(dep_key))
1426 .cloned()
1427 .collect();
1428
1429 let dep_values: Vec<(String, &Value)> = filtered_deps
1430 .iter()
1431 .filter_map(|dep_key| {
1432 eval_data.get(dep_key).map(|v| (dep_key.clone(), v))
1433 })
1434 .collect();
1435
1436 let cache_key = CacheKey::new(eval_key.to_string(), &filtered_deps, &dep_values);
1437 self.eval_cache.insert(cache_key, value);
1438 }
1439
1440 fn purge_cache_for_changed_data_with_comparison(
1444 &self,
1445 changed_data_paths: &[String],
1446 old_data: &Value,
1447 new_data: &Value
1448 ) {
1449 if changed_data_paths.is_empty() {
1450 return;
1451 }
1452
1453 let mut actually_changed_paths = Vec::new();
1455 for path in changed_data_paths {
1456 let old_val = old_data.pointer(path);
1457 let new_val = new_data.pointer(path);
1458
1459 if old_val != new_val {
1461 actually_changed_paths.push(path.clone());
1462 }
1463 }
1464
1465 if actually_changed_paths.is_empty() {
1467 return;
1468 }
1469
1470 let mut affected_eval_keys = IndexSet::new();
1472
1473 for (eval_key, deps) in self.dependencies.iter() {
1474 let is_affected = deps.iter().any(|dep| {
1476 actually_changed_paths.iter().any(|changed_path| {
1478 dep == changed_path ||
1480 dep.starts_with(&format!("{}/", changed_path)) ||
1481 changed_path.starts_with(&format!("{}/", dep))
1482 })
1483 });
1484
1485 if is_affected {
1486 affected_eval_keys.insert(eval_key.clone());
1487 }
1488 }
1489
1490 self.eval_cache.retain(|cache_key, _| {
1493 !affected_eval_keys.contains(&cache_key.eval_key)
1494 });
1495 }
1496
1497 fn purge_cache_for_changed_data(&self, changed_data_paths: &[String]) {
1500 if changed_data_paths.is_empty() {
1501 return;
1502 }
1503
1504 let mut affected_eval_keys = IndexSet::new();
1506
1507 for (eval_key, deps) in self.dependencies.iter() {
1508 let is_affected = deps.iter().any(|dep| {
1510 changed_data_paths.iter().any(|changed_path| {
1512 dep == changed_path ||
1514 dep.starts_with(&format!("{}/", changed_path)) ||
1515 changed_path.starts_with(&format!("{}/", dep))
1516 })
1517 });
1518
1519 if is_affected {
1520 affected_eval_keys.insert(eval_key.clone());
1521 }
1522 }
1523
1524 self.eval_cache.retain(|cache_key, _| {
1527 !affected_eval_keys.contains(&cache_key.eval_key)
1528 });
1529 }
1530
1531 fn purge_cache_for_context_change(&self) {
1533 let mut affected_eval_keys = IndexSet::new();
1535
1536 for (eval_key, deps) in self.dependencies.iter() {
1537 let is_affected = deps.iter().any(|dep| {
1538 dep == "$context" || dep.starts_with("$context.") || dep.starts_with("/$context")
1539 });
1540
1541 if is_affected {
1542 affected_eval_keys.insert(eval_key.clone());
1543 }
1544 }
1545
1546 self.eval_cache.retain(|cache_key, _| {
1547 !affected_eval_keys.contains(&cache_key.eval_key)
1548 });
1549 }
1550
1551 pub fn cache_stats(&self) -> CacheStats {
1553 self.eval_cache.stats()
1554 }
1555
1556 pub fn clear_cache(&mut self) {
1558 self.eval_cache.clear();
1559 for subform in self.subforms.values_mut() {
1560 subform.clear_cache();
1561 }
1562 }
1563
1564 pub fn cache_len(&self) -> usize {
1566 self.eval_cache.len()
1567 }
1568
1569 pub fn enable_cache(&mut self) {
1572 self.cache_enabled = true;
1573 for subform in self.subforms.values_mut() {
1574 subform.enable_cache();
1575 }
1576 }
1577
1578 pub fn disable_cache(&mut self) {
1582 self.cache_enabled = false;
1583 self.eval_cache.clear(); for subform in self.subforms.values_mut() {
1585 subform.disable_cache();
1586 }
1587 }
1588
1589 pub fn is_cache_enabled(&self) -> bool {
1591 self.cache_enabled
1592 }
1593
1594 fn evaluate_others(&mut self, paths: Option<&[String]>) {
1595 time_block!(" evaluate_others()", {
1596 time_block!(" evaluate_options_templates", {
1598 self.evaluate_options_templates(paths);
1599 });
1600
1601 let combined_count = self.rules_evaluations.len() + self.others_evaluations.len();
1604 if combined_count == 0 {
1605 return;
1606 }
1607
1608 time_block!(" evaluate rules+others", {
1609 let eval_data_snapshot = self.eval_data.clone();
1610
1611 let normalized_paths: Option<Vec<String>> = paths.map(|p_list| {
1612 p_list.iter()
1613 .flat_map(|p| {
1614 let ptr = path_utils::dot_notation_to_schema_pointer(p);
1615 let with_props = if ptr.starts_with("#/") {
1617 format!("#/properties/{}", &ptr[2..])
1618 } else {
1619 ptr.clone()
1620 };
1621 vec![ptr, with_props]
1622 })
1623 .collect()
1624 });
1625
1626 #[cfg(feature = "parallel")]
1627 {
1628 let combined_results: Mutex<Vec<(String, Value)>> = Mutex::new(Vec::with_capacity(combined_count));
1629
1630 self.rules_evaluations
1631 .par_iter()
1632 .chain(self.others_evaluations.par_iter())
1633 .for_each(|eval_key| {
1634 if let Some(filter_paths) = normalized_paths.as_ref() {
1636 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
1637 return;
1638 }
1639 }
1640
1641 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
1642
1643 if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
1645 return;
1646 }
1647
1648 if let Some(logic_id) = self.evaluations.get(eval_key) {
1650 if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
1651 let cleaned_val = clean_float_noise(val);
1652 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
1654 combined_results.lock().unwrap().push((pointer_path, cleaned_val));
1655 }
1656 }
1657 });
1658
1659 for (result_path, value) in combined_results.into_inner().unwrap() {
1661 if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&result_path) {
1662 if !result_path.starts_with("$") && result_path.contains("/rules/") && !result_path.ends_with("/value") {
1665 match pointer_value.as_object_mut() {
1666 Some(pointer_obj) => {
1667 pointer_obj.remove("$evaluation");
1668 pointer_obj.insert("value".to_string(), value);
1669 },
1670 None => continue,
1671 }
1672 } else {
1673 *pointer_value = value;
1674 }
1675 }
1676 }
1677 }
1678
1679 #[cfg(not(feature = "parallel"))]
1680 {
1681 let combined_evals: Vec<&String> = self.rules_evaluations.iter()
1683 .chain(self.others_evaluations.iter())
1684 .collect();
1685
1686 for eval_key in combined_evals {
1687 if let Some(filter_paths) = normalized_paths.as_ref() {
1689 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
1690 continue;
1691 }
1692 }
1693
1694 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
1695
1696 if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
1698 continue;
1699 }
1700
1701 if let Some(logic_id) = self.evaluations.get(eval_key) {
1703 if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
1704 let cleaned_val = clean_float_noise(val);
1705 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
1707
1708 if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
1709 if !pointer_path.starts_with("$") && pointer_path.contains("/rules/") && !pointer_path.ends_with("/value") {
1710 match pointer_value.as_object_mut() {
1711 Some(pointer_obj) => {
1712 pointer_obj.remove("$evaluation");
1713 pointer_obj.insert("value".to_string(), cleaned_val);
1714 },
1715 None => continue,
1716 }
1717 } else {
1718 *pointer_value = cleaned_val;
1719 }
1720 }
1721 }
1722 }
1723 }
1724 }
1725 });
1726 });
1727 }
1728
1729 fn evaluate_options_templates(&mut self, paths: Option<&[String]>) {
1731 let templates_to_eval = self.options_templates.clone();
1733
1734 for (path, template_str, params_path) in templates_to_eval.iter() {
1736 if let Some(filter_paths) = paths {
1740 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| path.starts_with(p.as_str()) || p.starts_with(path.as_str())) {
1741 continue;
1742 }
1743 }
1744
1745 if let Some(params) = self.evaluated_schema.pointer(¶ms_path) {
1746 if let Ok(evaluated) = self.evaluate_template(&template_str, params) {
1747 if let Some(target) = self.evaluated_schema.pointer_mut(&path) {
1748 *target = Value::String(evaluated);
1749 }
1750 }
1751 }
1752 }
1753 }
1754
1755 fn evaluate_template(&self, template: &str, params: &Value) -> Result<String, String> {
1757 let mut result = template.to_string();
1758
1759 if let Value::Object(params_map) = params {
1761 for (key, value) in params_map {
1762 let placeholder = format!("{{{}}}", key);
1763 if let Some(str_val) = value.as_str() {
1764 result = result.replace(&placeholder, str_val);
1765 } else {
1766 result = result.replace(&placeholder, &value.to_string());
1768 }
1769 }
1770 }
1771
1772 Ok(result)
1773 }
1774
1775 pub fn compile_logic(&self, logic_str: &str) -> Result<CompiledLogicId, String> {
1791 rlogic::compiled_logic_store::compile_logic(logic_str)
1792 }
1793
1794 pub fn compile_logic_value(&self, logic: &Value) -> Result<CompiledLogicId, String> {
1811 rlogic::compiled_logic_store::compile_logic_value(logic)
1812 }
1813
1814 pub fn run_logic(&mut self, logic_id: CompiledLogicId, data: Option<&Value>, context: Option<&Value>) -> Result<Value, String> {
1831 let compiled_logic = rlogic::compiled_logic_store::get_compiled_logic(logic_id)
1833 .ok_or_else(|| format!("Compiled logic ID {:?} not found in store", logic_id))?;
1834
1835 let eval_data_value = if let Some(input_data) = data {
1839 let context_value = context.unwrap_or(&self.context);
1840
1841 self.eval_data.replace_data_and_context(input_data.clone(), context_value.clone());
1842 self.eval_data.data()
1843 } else {
1844 self.eval_data.data()
1845 };
1846
1847 let evaluator = Evaluator::new();
1849 let result = evaluator.evaluate(&compiled_logic, &eval_data_value)?;
1850
1851 Ok(clean_float_noise(result))
1852 }
1853
1854 pub fn compile_and_run_logic(&mut self, logic_str: &str, data: Option<&str>, context: Option<&str>) -> Result<Value, String> {
1870 let compiled_logic = self.compile_logic(logic_str)?;
1872
1873 let data_value = if let Some(data_str) = data {
1875 Some(json_parser::parse_json_str(data_str)?)
1876 } else {
1877 None
1878 };
1879
1880 let context_value = if let Some(ctx_str) = context {
1881 Some(json_parser::parse_json_str(ctx_str)?)
1882 } else {
1883 None
1884 };
1885
1886 self.run_logic(compiled_logic, data_value.as_ref(), context_value.as_ref())
1888 }
1889
1890 pub fn resolve_layout(&mut self, evaluate: bool) -> Result<(), String> {
1900 if evaluate {
1901 let data_str = serde_json::to_string(&self.data)
1903 .map_err(|e| format!("Failed to serialize data: {}", e))?;
1904 self.evaluate(&data_str, None, None)?;
1905 }
1906
1907 self.resolve_layout_internal();
1908 Ok(())
1909 }
1910
1911 fn resolve_layout_internal(&mut self) {
1912 time_block!(" resolve_layout_internal()", {
1913 let layout_paths = self.layout_paths.clone();
1916
1917 time_block!(" resolve_layout_elements", {
1918 for layout_path in layout_paths.iter() {
1919 self.resolve_layout_elements(layout_path);
1920 }
1921 });
1922
1923 time_block!(" propagate_parent_conditions", {
1925 for layout_path in layout_paths.iter() {
1926 self.propagate_parent_conditions(layout_path);
1927 }
1928 });
1929 });
1930 }
1931
1932 fn propagate_parent_conditions(&mut self, layout_elements_path: &str) {
1934 let normalized_path = path_utils::normalize_to_json_pointer(layout_elements_path);
1936
1937 let elements = if let Some(Value::Array(arr)) = self.evaluated_schema.pointer_mut(&normalized_path) {
1939 mem::take(arr)
1940 } else {
1941 return;
1942 };
1943
1944 let mut updated_elements = Vec::with_capacity(elements.len());
1946 for element in elements {
1947 updated_elements.push(self.apply_parent_conditions(element, false, false));
1948 }
1949
1950 if let Some(target) = self.evaluated_schema.pointer_mut(&normalized_path) {
1952 *target = Value::Array(updated_elements);
1953 }
1954 }
1955
1956 fn apply_parent_conditions(&self, element: Value, parent_hidden: bool, parent_disabled: bool) -> Value {
1958 if let Value::Object(mut map) = element {
1959 let mut element_hidden = parent_hidden;
1961 let mut element_disabled = parent_disabled;
1962
1963 if let Some(Value::Object(condition)) = map.get("condition") {
1965 if let Some(Value::Bool(hidden)) = condition.get("hidden") {
1966 element_hidden = element_hidden || *hidden;
1967 }
1968 if let Some(Value::Bool(disabled)) = condition.get("disabled") {
1969 element_disabled = element_disabled || *disabled;
1970 }
1971 }
1972
1973 if let Some(Value::Object(hide_layout)) = map.get("hideLayout") {
1975 if let Some(Value::Bool(all_hidden)) = hide_layout.get("all") {
1977 if *all_hidden {
1978 element_hidden = true;
1979 }
1980 }
1981 }
1982
1983 if parent_hidden || parent_disabled {
1985 if map.contains_key("condition") || map.contains_key("$ref") || map.contains_key("$fullpath") {
1987 let mut condition = if let Some(Value::Object(c)) = map.get("condition") {
1988 c.clone()
1989 } else {
1990 serde_json::Map::new()
1991 };
1992
1993 if parent_hidden {
1994 condition.insert("hidden".to_string(), Value::Bool(true));
1995 }
1996 if parent_disabled {
1997 condition.insert("disabled".to_string(), Value::Bool(true));
1998 }
1999
2000 map.insert("condition".to_string(), Value::Object(condition));
2001 }
2002
2003 if parent_hidden && (map.contains_key("hideLayout") || map.contains_key("type")) {
2005 let mut hide_layout = if let Some(Value::Object(h)) = map.get("hideLayout") {
2006 h.clone()
2007 } else {
2008 serde_json::Map::new()
2009 };
2010
2011 hide_layout.insert("all".to_string(), Value::Bool(true));
2013 map.insert("hideLayout".to_string(), Value::Object(hide_layout));
2014 }
2015 }
2016
2017 if map.contains_key("$parentHide") {
2020 map.insert("$parentHide".to_string(), Value::Bool(parent_hidden));
2021 }
2022
2023 if let Some(Value::Array(elements)) = map.get("elements") {
2025 let mut updated_children = Vec::with_capacity(elements.len());
2026 for child in elements {
2027 updated_children.push(self.apply_parent_conditions(
2028 child.clone(),
2029 element_hidden,
2030 element_disabled,
2031 ));
2032 }
2033 map.insert("elements".to_string(), Value::Array(updated_children));
2034 }
2035
2036 return Value::Object(map);
2037 }
2038
2039 element
2040 }
2041
2042 fn resolve_layout_elements(&mut self, layout_elements_path: &str) {
2044 let normalized_path = path_utils::normalize_to_json_pointer(layout_elements_path);
2046
2047 let elements = if let Some(Value::Array(arr)) = self.schema.pointer(&normalized_path) {
2051 arr.clone()
2052 } else {
2053 return;
2054 };
2055
2056 let parent_path = normalized_path
2058 .trim_start_matches('/')
2059 .replace("/elements", "")
2060 .replace('/', ".");
2061
2062 let mut resolved_elements = Vec::with_capacity(elements.len());
2064 for (index, element) in elements.iter().enumerate() {
2065 let element_path = if parent_path.is_empty() {
2066 format!("elements.{}", index)
2067 } else {
2068 format!("{}.elements.{}", parent_path, index)
2069 };
2070 let resolved = self.resolve_element_ref_recursive(element.clone(), &element_path);
2071 resolved_elements.push(resolved);
2072 }
2073
2074 if let Some(target) = self.evaluated_schema.pointer_mut(&normalized_path) {
2076 *target = Value::Array(resolved_elements);
2077 }
2078 }
2079
2080 fn resolve_element_ref_recursive(&self, element: Value, path_context: &str) -> Value {
2083 let resolved = self.resolve_element_ref(element);
2085
2086 if let Value::Object(mut map) = resolved {
2088 if !map.contains_key("$parentHide") {
2092 map.insert("$parentHide".to_string(), Value::Bool(false));
2093 }
2094
2095 if !map.contains_key("$fullpath") {
2097 map.insert("$fullpath".to_string(), Value::String(path_context.to_string()));
2098 }
2099
2100 if !map.contains_key("$path") {
2101 let last_segment = path_context.split('.').last().unwrap_or(path_context);
2103 map.insert("$path".to_string(), Value::String(last_segment.to_string()));
2104 }
2105
2106 if let Some(Value::Array(elements)) = map.get("elements") {
2108 let mut resolved_nested = Vec::with_capacity(elements.len());
2109 for (index, nested_element) in elements.iter().enumerate() {
2110 let nested_path = format!("{}.elements.{}", path_context, index);
2111 resolved_nested.push(self.resolve_element_ref_recursive(nested_element.clone(), &nested_path));
2112 }
2113 map.insert("elements".to_string(), Value::Array(resolved_nested));
2114 }
2115
2116 return Value::Object(map);
2117 }
2118
2119 resolved
2120 }
2121
2122 fn resolve_element_ref(&self, element: Value) -> Value {
2124 match element {
2125 Value::Object(mut map) => {
2126 if let Some(Value::String(ref_path)) = map.get("$ref").cloned() {
2128 let dotted_path = path_utils::pointer_to_dot_notation(&ref_path);
2130
2131 let last_segment = dotted_path.split('.').last().unwrap_or(&dotted_path);
2133
2134 map.insert("$fullpath".to_string(), Value::String(dotted_path.clone()));
2136 map.insert("$path".to_string(), Value::String(last_segment.to_string()));
2137 map.insert("$parentHide".to_string(), Value::Bool(false));
2138
2139 let normalized_path = if ref_path.starts_with('#') || ref_path.starts_with('/') {
2142 path_utils::normalize_to_json_pointer(&ref_path)
2144 } else {
2145 let schema_pointer = path_utils::dot_notation_to_schema_pointer(&ref_path);
2147 let schema_path = path_utils::normalize_to_json_pointer(&schema_pointer);
2148
2149 if self.evaluated_schema.pointer(&schema_path).is_some() {
2151 schema_path
2152 } else {
2153 let with_properties = format!("/properties/{}", ref_path.replace('.', "/properties/"));
2155 with_properties
2156 }
2157 };
2158
2159 if let Some(referenced_value) = self.evaluated_schema.pointer(&normalized_path) {
2161 let resolved = referenced_value.clone();
2163
2164 if let Value::Object(mut resolved_map) = resolved {
2166 map.remove("$ref");
2168
2169 if let Some(Value::Object(layout_obj)) = resolved_map.remove("$layout") {
2172 let mut result = layout_obj.clone();
2174
2175 resolved_map.remove("properties");
2177
2178 for (key, value) in resolved_map {
2180 if key != "type" || !result.contains_key("type") {
2181 result.insert(key, value);
2182 }
2183 }
2184
2185 for (key, value) in map {
2187 result.insert(key, value);
2188 }
2189
2190 return Value::Object(result);
2191 } else {
2192 for (key, value) in map {
2194 resolved_map.insert(key, value);
2195 }
2196
2197 return Value::Object(resolved_map);
2198 }
2199 } else {
2200 return resolved;
2202 }
2203 }
2204 }
2205
2206 Value::Object(map)
2208 }
2209 _ => element,
2210 }
2211 }
2212
2213 pub fn evaluate_dependents(
2222 &mut self,
2223 changed_paths: &[String],
2224 data: Option<&str>,
2225 context: Option<&str>,
2226 re_evaluate: bool,
2227 ) -> Result<Value, String> {
2228 let _lock = self.eval_lock.lock().unwrap();
2230
2231 if let Some(data_str) = data {
2233 let old_data = self.eval_data.clone_data_without(&["$params"]);
2235
2236 let data_value = json_parser::parse_json_str(data_str)?;
2237 let context_value = if let Some(ctx) = context {
2238 json_parser::parse_json_str(ctx)?
2239 } else {
2240 Value::Object(serde_json::Map::new())
2241 };
2242 self.eval_data.replace_data_and_context(data_value.clone(), context_value);
2243
2244 let data_paths: Vec<String> = changed_paths
2248 .iter()
2249 .map(|path| {
2250 let schema_ptr = path_utils::dot_notation_to_schema_pointer(path);
2253
2254 let normalized = schema_ptr.trim_start_matches('#')
2256 .replace("/properties/", "/");
2257
2258 if normalized.starts_with('/') {
2260 normalized
2261 } else {
2262 format!("/{}", normalized)
2263 }
2264 })
2265 .collect();
2266 self.purge_cache_for_changed_data_with_comparison(&data_paths, &old_data, &data_value);
2267 }
2268
2269 let mut result = Vec::new();
2270 let mut processed = IndexSet::new();
2271
2272 let mut to_process: Vec<(String, bool)> = changed_paths
2275 .iter()
2276 .map(|path| (path_utils::dot_notation_to_schema_pointer(path), false))
2277 .collect(); while let Some((current_path, is_transitive)) = to_process.pop() {
2281 if processed.contains(¤t_path) {
2282 continue;
2283 }
2284 processed.insert(current_path.clone());
2285
2286 let current_data_path = path_utils::normalize_to_json_pointer(¤t_path)
2288 .replace("/properties/", "/")
2289 .trim_start_matches('#')
2290 .to_string();
2291 let mut current_value = self.eval_data.data().pointer(¤t_data_path)
2292 .cloned()
2293 .unwrap_or(Value::Null);
2294
2295 if let Some(dependent_items) = self.dependents_evaluations.get(¤t_path) {
2297 for dep_item in dependent_items {
2298 let ref_path = &dep_item.ref_path;
2299 let pointer_path = path_utils::normalize_to_json_pointer(ref_path);
2300 let data_path = pointer_path.replace("/properties/", "/");
2302
2303 let current_ref_value = self.eval_data.data().pointer(&data_path)
2304 .cloned()
2305 .unwrap_or(Value::Null);
2306
2307 let field = self.evaluated_schema.pointer(&pointer_path).cloned();
2309
2310 let parent_path = if let Some(last_slash) = pointer_path.rfind("/properties") {
2312 &pointer_path[..last_slash]
2313 } else {
2314 "/"
2315 };
2316 let mut parent_field = if parent_path.is_empty() || parent_path == "/" {
2317 self.evaluated_schema.clone()
2318 } else {
2319 self.evaluated_schema.pointer(parent_path).cloned()
2320 .unwrap_or_else(|| Value::Object(serde_json::Map::new()))
2321 };
2322
2323 if let Value::Object(ref mut map) = parent_field {
2325 map.remove("properties");
2326 map.remove("$layout");
2327 }
2328
2329 let mut change_obj = serde_json::Map::new();
2330 change_obj.insert("$ref".to_string(), Value::String(path_utils::pointer_to_dot_notation(&data_path)));
2331 if let Some(f) = field {
2332 change_obj.insert("$field".to_string(), f);
2333 }
2334 change_obj.insert("$parentField".to_string(), parent_field);
2335 change_obj.insert("transitive".to_string(), Value::Bool(is_transitive));
2336
2337 let mut add_transitive = false;
2338 let mut add_deps = false;
2339 if let Some(clear_val) = &dep_item.clear {
2341 let clear_val_clone = clear_val.clone();
2342 let should_clear = Self::evaluate_dependent_value_static(&self.engine, &self.evaluations, &self.eval_data, &clear_val_clone, ¤t_value, ¤t_ref_value)?;
2343 let clear_bool = match should_clear {
2344 Value::Bool(b) => b,
2345 _ => false,
2346 };
2347
2348 if clear_bool {
2349 if data_path == current_data_path {
2351 current_value = Value::Null;
2352 }
2353 self.eval_data.set(&data_path, Value::Null);
2354 change_obj.insert("clear".to_string(), Value::Bool(true));
2355 add_transitive = true;
2356 add_deps = true;
2357 }
2358 }
2359
2360 if let Some(value_val) = &dep_item.value {
2362 let value_val_clone = value_val.clone();
2363 let computed_value = Self::evaluate_dependent_value_static(&self.engine, &self.evaluations, &self.eval_data, &value_val_clone, ¤t_value, ¤t_ref_value)?;
2364 let cleaned_val = clean_float_noise(computed_value.clone());
2365
2366 if cleaned_val != current_ref_value && cleaned_val != Value::Null {
2367 if data_path == current_data_path {
2369 current_value = cleaned_val.clone();
2370 }
2371 self.eval_data.set(&data_path, cleaned_val.clone());
2372 change_obj.insert("value".to_string(), cleaned_val);
2373 add_transitive = true;
2374 add_deps = true;
2375 }
2376 }
2377
2378 if add_deps {
2380 result.push(Value::Object(change_obj));
2381 }
2382
2383 if add_transitive {
2385 to_process.push((ref_path.clone(), true));
2386 }
2387 }
2388 }
2389 }
2390
2391 if re_evaluate {
2395 drop(_lock); self.evaluate_internal(None)?;
2397 }
2398
2399 Ok(Value::Array(result))
2400 }
2401
2402 fn evaluate_dependent_value_static(
2404 engine: &RLogic,
2405 evaluations: &IndexMap<String, LogicId>,
2406 eval_data: &EvalData,
2407 value: &Value,
2408 changed_field_value: &Value,
2409 changed_field_ref_value: &Value
2410 ) -> Result<Value, String> {
2411 match value {
2412 Value::String(eval_key) => {
2414 if let Some(logic_id) = evaluations.get(eval_key) {
2415 let mut internal_context = serde_json::Map::new();
2418 internal_context.insert("$value".to_string(), changed_field_value.clone());
2419 internal_context.insert("$refValue".to_string(), changed_field_ref_value.clone());
2420 let context_value = Value::Object(internal_context);
2421
2422 let result = engine.run_with_context(logic_id, eval_data.data(), &context_value)
2423 .map_err(|e| format!("Failed to evaluate dependent logic '{}': {}", eval_key, e))?;
2424 Ok(result)
2425 } else {
2426 Ok(value.clone())
2428 }
2429 }
2430 Value::Object(map) if map.contains_key("$evaluation") => {
2433 Err("Dependent evaluation contains unparsed $evaluation - schema was not properly parsed".to_string())
2434 }
2435 _ => Ok(value.clone()),
2437 }
2438 }
2439
2440 pub fn validate(
2443 &mut self,
2444 data: &str,
2445 context: Option<&str>,
2446 paths: Option<&[String]>
2447 ) -> Result<ValidationResult, String> {
2448 let _lock = self.eval_lock.lock().unwrap();
2450
2451 let old_data = self.eval_data.clone_data_without(&["$params"]);
2453
2454 let data_value = json_parser::parse_json_str(data)?;
2456 let context_value = if let Some(ctx) = context {
2457 json_parser::parse_json_str(ctx)?
2458 } else {
2459 Value::Object(serde_json::Map::new())
2460 };
2461
2462 self.eval_data.replace_data_and_context(data_value.clone(), context_value);
2464
2465 let changed_data_paths: Vec<String> = if let Some(obj) = data_value.as_object() {
2468 obj.keys().map(|k| format!("/{}", k)).collect()
2469 } else {
2470 Vec::new()
2471 };
2472 self.purge_cache_for_changed_data_with_comparison(&changed_data_paths, &old_data, &data_value);
2473
2474 drop(_lock);
2476
2477 self.evaluate_others(paths);
2482
2483 self.evaluated_schema = self.get_evaluated_schema(false);
2485
2486 let mut errors: IndexMap<String, ValidationError> = IndexMap::new();
2487
2488 for field_path in self.fields_with_rules.iter() {
2491 if let Some(filter_paths) = paths {
2493 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| field_path.starts_with(p.as_str()) || p.starts_with(field_path.as_str())) {
2494 continue;
2495 }
2496 }
2497
2498 self.validate_field(field_path, &data_value, &mut errors);
2499 }
2500
2501 let has_error = !errors.is_empty();
2502
2503 Ok(ValidationResult {
2504 has_error,
2505 errors,
2506 })
2507 }
2508
2509 fn validate_field(
2511 &self,
2512 field_path: &str,
2513 data: &Value,
2514 errors: &mut IndexMap<String, ValidationError>
2515 ) {
2516 if errors.contains_key(field_path) {
2518 return;
2519 }
2520
2521 let schema_path = path_utils::dot_notation_to_schema_pointer(field_path);
2523
2524 let pointer_path = schema_path.trim_start_matches('#');
2526
2527 let field_schema = match self.evaluated_schema.pointer(pointer_path) {
2529 Some(s) => s,
2530 None => {
2531 let alt_path = format!("/properties{}", pointer_path);
2533 match self.evaluated_schema.pointer(&alt_path) {
2534 Some(s) => s,
2535 None => return,
2536 }
2537 }
2538 };
2539
2540 if let Value::Object(schema_map) = field_schema {
2542 if let Some(Value::Object(condition)) = schema_map.get("condition") {
2543 if let Some(Value::Bool(true)) = condition.get("hidden") {
2544 return;
2545 }
2546 }
2547
2548 let rules = match schema_map.get("rules") {
2550 Some(Value::Object(r)) => r,
2551 _ => return,
2552 };
2553
2554 let field_data = self.get_field_data(field_path, data);
2556
2557 for (rule_name, rule_value) in rules {
2559 self.validate_rule(
2560 field_path,
2561 rule_name,
2562 rule_value,
2563 &field_data,
2564 schema_map,
2565 field_schema,
2566 errors
2567 );
2568 }
2569 }
2570 }
2571
2572 fn get_field_data(&self, field_path: &str, data: &Value) -> Value {
2574 let parts: Vec<&str> = field_path.split('.').collect();
2575 let mut current = data;
2576
2577 for part in parts {
2578 match current {
2579 Value::Object(map) => {
2580 current = map.get(part).unwrap_or(&Value::Null);
2581 }
2582 _ => return Value::Null,
2583 }
2584 }
2585
2586 current.clone()
2587 }
2588
2589 fn validate_rule(
2591 &self,
2592 field_path: &str,
2593 rule_name: &str,
2594 rule_value: &Value,
2595 field_data: &Value,
2596 schema_map: &serde_json::Map<String, Value>,
2597 _schema: &Value,
2598 errors: &mut IndexMap<String, ValidationError>
2599 ) {
2600 if errors.contains_key(field_path) {
2602 return;
2603 }
2604
2605 let mut disabled_field = false;
2606 if let Some(Value::Object(condition)) = schema_map.get("condition") {
2608 if let Some(Value::Bool(true)) = condition.get("disabled") {
2609 disabled_field = true;
2610 }
2611 }
2612
2613 let schema_path = path_utils::dot_notation_to_schema_pointer(field_path);
2616 let rule_path = format!("{}/rules/{}", schema_path.trim_start_matches('#'), rule_name);
2617
2618 let evaluated_rule = if let Some(eval_rule) = self.evaluated_schema.pointer(&rule_path) {
2620 eval_rule.clone()
2621 } else {
2622 rule_value.clone()
2623 };
2624
2625 let (rule_active, rule_message, rule_code, rule_data) = match &evaluated_rule {
2627 Value::Object(rule_obj) => {
2628 let active = rule_obj.get("value").unwrap_or(&Value::Bool(false));
2629
2630 let message = match rule_obj.get("message") {
2632 Some(Value::String(s)) => s.clone(),
2633 Some(Value::Object(msg_obj)) if msg_obj.contains_key("value") => {
2634 msg_obj.get("value")
2635 .and_then(|v| v.as_str())
2636 .unwrap_or("Validation failed")
2637 .to_string()
2638 }
2639 Some(msg_val) => msg_val.as_str().unwrap_or("Validation failed").to_string(),
2640 None => "Validation failed".to_string()
2641 };
2642
2643 let code = rule_obj.get("code")
2644 .and_then(|c| c.as_str())
2645 .map(|s| s.to_string());
2646
2647 let data = rule_obj.get("data").map(|d| {
2649 if let Value::Object(data_obj) = d {
2650 let mut cleaned_data = serde_json::Map::new();
2651 for (key, value) in data_obj {
2652 if let Value::Object(val_obj) = value {
2654 if val_obj.len() == 1 && val_obj.contains_key("value") {
2655 cleaned_data.insert(key.clone(), val_obj["value"].clone());
2656 } else {
2657 cleaned_data.insert(key.clone(), value.clone());
2658 }
2659 } else {
2660 cleaned_data.insert(key.clone(), value.clone());
2661 }
2662 }
2663 Value::Object(cleaned_data)
2664 } else {
2665 d.clone()
2666 }
2667 });
2668
2669 (active.clone(), message, code, data)
2670 }
2671 _ => (evaluated_rule.clone(), "Validation failed".to_string(), None, None)
2672 };
2673
2674 let error_code = rule_code.or_else(|| Some(format!("{}.{}", field_path, rule_name)));
2676
2677 let is_empty = matches!(field_data, Value::Null) ||
2678 (field_data.is_string() && field_data.as_str().unwrap_or("").is_empty()) ||
2679 (field_data.is_array() && field_data.as_array().unwrap().is_empty());
2680
2681 match rule_name {
2682 "required" => {
2683 if !disabled_field && rule_active == Value::Bool(true) {
2684 if is_empty {
2685 errors.insert(field_path.to_string(), ValidationError {
2686 rule_type: "required".to_string(),
2687 message: rule_message,
2688 code: error_code.clone(),
2689 pattern: None,
2690 field_value: None,
2691 data: None,
2692 });
2693 }
2694 }
2695 }
2696 "minLength" => {
2697 if !is_empty {
2698 if let Some(min) = rule_active.as_u64() {
2699 let len = match field_data {
2700 Value::String(s) => s.len(),
2701 Value::Array(a) => a.len(),
2702 _ => 0
2703 };
2704 if len < min as usize {
2705 errors.insert(field_path.to_string(), ValidationError {
2706 rule_type: "minLength".to_string(),
2707 message: rule_message,
2708 code: error_code.clone(),
2709 pattern: None,
2710 field_value: None,
2711 data: None,
2712 });
2713 }
2714 }
2715 }
2716 }
2717 "maxLength" => {
2718 if !is_empty {
2719 if let Some(max) = rule_active.as_u64() {
2720 let len = match field_data {
2721 Value::String(s) => s.len(),
2722 Value::Array(a) => a.len(),
2723 _ => 0
2724 };
2725 if len > max as usize {
2726 errors.insert(field_path.to_string(), ValidationError {
2727 rule_type: "maxLength".to_string(),
2728 message: rule_message,
2729 code: error_code.clone(),
2730 pattern: None,
2731 field_value: None,
2732 data: None,
2733 });
2734 }
2735 }
2736 }
2737 }
2738 "minValue" => {
2739 if !is_empty {
2740 if let Some(min) = rule_active.as_f64() {
2741 if let Some(val) = field_data.as_f64() {
2742 if val < min {
2743 errors.insert(field_path.to_string(), ValidationError {
2744 rule_type: "minValue".to_string(),
2745 message: rule_message,
2746 code: error_code.clone(),
2747 pattern: None,
2748 field_value: None,
2749 data: None,
2750 });
2751 }
2752 }
2753 }
2754 }
2755 }
2756 "maxValue" => {
2757 if !is_empty {
2758 if let Some(max) = rule_active.as_f64() {
2759 if let Some(val) = field_data.as_f64() {
2760 if val > max {
2761 errors.insert(field_path.to_string(), ValidationError {
2762 rule_type: "maxValue".to_string(),
2763 message: rule_message,
2764 code: error_code.clone(),
2765 pattern: None,
2766 field_value: None,
2767 data: None,
2768 });
2769 }
2770 }
2771 }
2772 }
2773 }
2774 "pattern" => {
2775 if !is_empty {
2776 if let Some(pattern) = rule_active.as_str() {
2777 if let Some(text) = field_data.as_str() {
2778 if let Ok(regex) = regex::Regex::new(pattern) {
2779 if !regex.is_match(text) {
2780 errors.insert(field_path.to_string(), ValidationError {
2781 rule_type: "pattern".to_string(),
2782 message: rule_message,
2783 code: error_code.clone(),
2784 pattern: Some(pattern.to_string()),
2785 field_value: Some(text.to_string()),
2786 data: None,
2787 });
2788 }
2789 }
2790 }
2791 }
2792 }
2793 }
2794 "evaluation" => {
2795 if let Value::Array(eval_array) = &evaluated_rule {
2798 for (idx, eval_item) in eval_array.iter().enumerate() {
2799 if let Value::Object(eval_obj) = eval_item {
2800 let eval_result = eval_obj.get("value").unwrap_or(&Value::Bool(true));
2802
2803 let is_falsy = match eval_result {
2805 Value::Bool(false) => true,
2806 Value::Null => true,
2807 Value::Number(n) => n.as_f64() == Some(0.0),
2808 Value::String(s) => s.is_empty(),
2809 Value::Array(a) => a.is_empty(),
2810 _ => false,
2811 };
2812
2813 if is_falsy {
2814 let eval_code = eval_obj.get("code")
2815 .and_then(|c| c.as_str())
2816 .map(|s| s.to_string())
2817 .or_else(|| Some(format!("{}.evaluation.{}", field_path, idx)));
2818
2819 let eval_message = eval_obj.get("message")
2820 .and_then(|m| m.as_str())
2821 .unwrap_or("Validation failed")
2822 .to_string();
2823
2824 let eval_data = eval_obj.get("data").cloned();
2825
2826 errors.insert(field_path.to_string(), ValidationError {
2827 rule_type: "evaluation".to_string(),
2828 message: eval_message,
2829 code: eval_code,
2830 pattern: None,
2831 field_value: None,
2832 data: eval_data,
2833 });
2834
2835 break;
2837 }
2838 }
2839 }
2840 }
2841 }
2842 _ => {
2843 if !is_empty {
2847 let is_falsy = match &rule_active {
2849 Value::Bool(false) => true,
2850 Value::Null => true,
2851 Value::Number(n) => n.as_f64() == Some(0.0),
2852 Value::String(s) => s.is_empty(),
2853 Value::Array(a) => a.is_empty(),
2854 _ => false,
2855 };
2856
2857 if is_falsy {
2858 errors.insert(field_path.to_string(), ValidationError {
2859 rule_type: "evaluation".to_string(),
2860 message: rule_message,
2861 code: error_code.clone(),
2862 pattern: None,
2863 field_value: None,
2864 data: rule_data,
2865 });
2866 }
2867 }
2868 }
2869 }
2870 }
2871}
2872
2873#[derive(Debug, Clone, Serialize, Deserialize)]
2875pub struct ValidationError {
2876 #[serde(rename = "type")]
2877 pub rule_type: String,
2878 pub message: String,
2879 #[serde(skip_serializing_if = "Option::is_none")]
2880 pub code: Option<String>,
2881 #[serde(skip_serializing_if = "Option::is_none")]
2882 pub pattern: Option<String>,
2883 #[serde(skip_serializing_if = "Option::is_none")]
2884 pub field_value: Option<String>,
2885 #[serde(skip_serializing_if = "Option::is_none")]
2886 pub data: Option<Value>,
2887}
2888
2889#[derive(Debug, Clone, Serialize, Deserialize)]
2891pub struct ValidationResult {
2892 pub has_error: bool,
2893 pub errors: IndexMap<String, ValidationError>,
2894}
2895