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 self.cache_result(eval_key, Value::Null, &eval_data_values);
865
866 if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
867 *pointer_value = cleaned_val;
868 }
869 }
870 }
871 }
872 });
873
874 time_block!(" process batches", {
875 for batch in eval_batches {
876 if batch.is_empty() {
878 continue;
879 }
880
881 if let Some(filter_paths) = normalized_paths {
884 if !filter_paths.is_empty() {
885 let batch_has_match = batch.iter().any(|eval_key| {
886 filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str()))
887 });
888 if !batch_has_match {
889 continue;
890 }
891 }
892 }
893
894 let eval_data_snapshot = self.eval_data.clone();
901
902 #[cfg(feature = "parallel")]
906 if batch.len() > 1000 {
907 let results: Mutex<Vec<(String, String, Value)>> = Mutex::new(Vec::with_capacity(batch.len()));
908 batch.par_iter().for_each(|eval_key| {
909 if let Some(filter_paths) = normalized_paths {
911 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
912 return;
913 }
914 }
915
916 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
917
918 if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
920 return;
921 }
922
923 let is_table = self.table_metadata.contains_key(eval_key);
925
926 if is_table {
927 if let Ok(rows) = table_evaluate::evaluate_table(self, eval_key, &eval_data_snapshot) {
929 let value = Value::Array(rows);
930 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
932 results.lock().unwrap().push((eval_key.clone(), pointer_path, value));
933 }
934 } else {
935 if let Some(logic_id) = self.evaluations.get(eval_key) {
936 if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
938 let cleaned_val = clean_float_noise(val);
939 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
941 results.lock().unwrap().push((eval_key.clone(), pointer_path, cleaned_val));
942 }
943 }
944 }
945 });
946
947 for (_eval_key, path, value) in results.into_inner().unwrap() {
949 let cleaned_value = clean_float_noise(value);
950
951 self.eval_data.set(&path, cleaned_value.clone());
952 if let Some(schema_value) = self.evaluated_schema.pointer_mut(&path) {
954 *schema_value = cleaned_value;
955 }
956 }
957 continue;
958 }
959
960 #[cfg(not(feature = "parallel"))]
962 let batch_items = &batch;
963
964 #[cfg(feature = "parallel")]
965 let batch_items = if batch.len() > 1000 { &batch[0..0] } else { &batch }; for eval_key in batch_items {
968 if let Some(filter_paths) = normalized_paths {
970 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
971 continue;
972 }
973 }
974
975 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
976
977 if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
979 continue;
980 }
981
982 let is_table = self.table_metadata.contains_key(eval_key);
984
985 if is_table {
986 if let Ok(rows) = table_evaluate::evaluate_table(self, eval_key, &eval_data_snapshot) {
987 let value = Value::Array(rows);
988 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
990
991 let cleaned_value = clean_float_noise(value);
992 self.eval_data.set(&pointer_path, cleaned_value.clone());
993 if let Some(schema_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
994 *schema_value = cleaned_value;
995 }
996 }
997 } else {
998 if let Some(logic_id) = self.evaluations.get(eval_key) {
999 if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
1000 let cleaned_val = clean_float_noise(val);
1001 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
1003
1004 self.eval_data.set(&pointer_path, cleaned_val.clone());
1005 if let Some(schema_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
1006 *schema_value = cleaned_val;
1007 }
1008 }
1009 }
1010 }
1011 }
1012 }
1013 });
1014
1015 drop(_lock);
1017
1018 self.evaluate_others(paths);
1019
1020 Ok(())
1021 })
1022 }
1023
1024 pub fn get_evaluated_schema(&mut self, skip_layout: bool) -> Value {
1034 time_block!("get_evaluated_schema()", {
1035 if !skip_layout {
1036 self.resolve_layout_internal();
1037 }
1038
1039 self.evaluated_schema.clone()
1040 })
1041 }
1042
1043 pub fn get_evaluated_schema_msgpack(&mut self, skip_layout: bool) -> Result<Vec<u8>, String> {
1060 if !skip_layout {
1061 self.resolve_layout_internal();
1062 }
1063
1064 rmp_serde::to_vec(&self.evaluated_schema)
1068 .map_err(|e| format!("Failed to serialize schema to MessagePack: {}", e))
1069 }
1070
1071 pub fn get_schema_value(&mut self) -> Value {
1075 if !self.data.is_object() {
1077 self.data = Value::Object(serde_json::Map::new());
1078 }
1079
1080 for eval_key in self.value_evaluations.iter() {
1082 let clean_key = eval_key.replace("#", "");
1083 let path = clean_key.replace("/properties", "").replace("/value", "");
1084
1085 let value = match self.evaluated_schema.pointer(&clean_key) {
1087 Some(v) => v.clone(),
1088 None => continue,
1089 };
1090
1091 let path_parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
1093
1094 if path_parts.is_empty() {
1095 continue;
1096 }
1097
1098 let mut current = &mut self.data;
1100 for (i, part) in path_parts.iter().enumerate() {
1101 let is_last = i == path_parts.len() - 1;
1102
1103 if is_last {
1104 if let Some(obj) = current.as_object_mut() {
1106 obj.insert(part.to_string(), clean_float_noise(value.clone()));
1107 }
1108 } else {
1109 if let Some(obj) = current.as_object_mut() {
1111 current = obj.entry(part.to_string())
1112 .or_insert_with(|| Value::Object(serde_json::Map::new()));
1113 } else {
1114 break;
1116 }
1117 }
1118 }
1119 }
1120
1121 clean_float_noise(self.data.clone())
1122 }
1123
1124 pub fn get_evaluated_schema_without_params(&mut self, skip_layout: bool) -> Value {
1135 if !skip_layout {
1136 self.resolve_layout_internal();
1137 }
1138
1139 if let Value::Object(mut map) = self.evaluated_schema.clone() {
1141 map.remove("$params");
1142 Value::Object(map)
1143 } else {
1144 self.evaluated_schema.clone()
1145 }
1146 }
1147
1148 pub fn get_evaluated_schema_by_path(&mut self, path: &str, skip_layout: bool) -> Option<Value> {
1160 if !skip_layout {
1161 self.resolve_layout_internal();
1162 }
1163
1164 let pointer = if path.is_empty() {
1166 "".to_string()
1167 } else {
1168 format!("/{}", path.replace(".", "/"))
1169 };
1170
1171 self.evaluated_schema.pointer(&pointer).cloned()
1172 }
1173
1174 pub fn get_evaluated_schema_by_paths(&mut self, paths: &[String], skip_layout: bool, format: Option<ReturnFormat>) -> Value {
1187 let format = format.unwrap_or_default();
1188 if !skip_layout {
1189 self.resolve_layout_internal();
1190 }
1191
1192 let mut result = serde_json::Map::new();
1193
1194 for path in paths {
1195 let pointer = if path.is_empty() {
1197 "".to_string()
1198 } else {
1199 format!("/{}", path.replace(".", "/"))
1200 };
1201
1202 if let Some(value) = self.evaluated_schema.pointer(&pointer) {
1204 self.insert_at_path(&mut result, path, value.clone());
1207 }
1208 }
1209
1210 self.convert_to_format(result, paths, format)
1211 }
1212
1213 fn insert_at_path(&self, obj: &mut serde_json::Map<String, Value>, path: &str, value: Value) {
1215 if path.is_empty() {
1216 if let Value::Object(map) = value {
1218 for (k, v) in map {
1219 obj.insert(k, v);
1220 }
1221 }
1222 return;
1223 }
1224
1225 let parts: Vec<&str> = path.split('.').collect();
1226 if parts.is_empty() {
1227 return;
1228 }
1229
1230 let mut current = obj;
1231 let last_index = parts.len() - 1;
1232
1233 for (i, part) in parts.iter().enumerate() {
1234 if i == last_index {
1235 current.insert(part.to_string(), value);
1237 break;
1238 } else {
1239 current = current
1241 .entry(part.to_string())
1242 .or_insert_with(|| Value::Object(serde_json::Map::new()))
1243 .as_object_mut()
1244 .unwrap();
1245 }
1246 }
1247 }
1248
1249 fn convert_to_format(&self, result: serde_json::Map<String, Value>, paths: &[String], format: ReturnFormat) -> Value {
1251 match format {
1252 ReturnFormat::Nested => Value::Object(result),
1253 ReturnFormat::Flat => {
1254 let mut flat = serde_json::Map::new();
1256 self.flatten_object(&result, String::new(), &mut flat);
1257 Value::Object(flat)
1258 }
1259 ReturnFormat::Array => {
1260 let values: Vec<Value> = paths.iter()
1262 .map(|path| {
1263 let pointer = if path.is_empty() {
1264 "".to_string()
1265 } else {
1266 format!("/{}", path.replace(".", "/"))
1267 };
1268 Value::Object(result.clone()).pointer(&pointer).cloned().unwrap_or(Value::Null)
1269 })
1270 .collect();
1271 Value::Array(values)
1272 }
1273 }
1274 }
1275
1276 fn flatten_object(&self, obj: &serde_json::Map<String, Value>, prefix: String, result: &mut serde_json::Map<String, Value>) {
1278 for (key, value) in obj {
1279 let new_key = if prefix.is_empty() {
1280 key.clone()
1281 } else {
1282 format!("{}.{}", prefix, key)
1283 };
1284
1285 if let Value::Object(nested) = value {
1286 self.flatten_object(nested, new_key, result);
1287 } else {
1288 result.insert(new_key, value.clone());
1289 }
1290 }
1291 }
1292
1293 pub fn get_schema_by_path(&self, path: &str) -> Option<Value> {
1304 let pointer = if path.is_empty() {
1306 "".to_string()
1307 } else {
1308 format!("/{}", path.replace(".", "/"))
1309 };
1310
1311 self.schema.pointer(&pointer).cloned()
1312 }
1313
1314 pub fn get_schema_by_paths(&self, paths: &[String], format: Option<ReturnFormat>) -> Value {
1326 let format = format.unwrap_or_default();
1327 let mut result = serde_json::Map::new();
1328
1329 for path in paths {
1330 let pointer = if path.is_empty() {
1332 "".to_string()
1333 } else {
1334 format!("/{}", path.replace(".", "/"))
1335 };
1336
1337 if let Some(value) = self.schema.pointer(&pointer) {
1339 self.insert_at_path(&mut result, path, value.clone());
1342 }
1343 }
1344
1345 self.convert_to_format(result, paths, format)
1346 }
1347
1348 #[inline]
1351 fn should_cache_dependency(key: &str) -> bool {
1352 if key.starts_with("/$") || key.starts_with('$') {
1353 key == "$context" || key.starts_with("$context.") || key.starts_with("/$context")
1355 } else {
1356 true
1357 }
1358 }
1359
1360 fn try_get_cached(&self, eval_key: &str, eval_data: &EvalData) -> Option<Value> {
1363 if !self.cache_enabled {
1365 return None;
1366 }
1367
1368 let deps = self.dependencies.get(eval_key)?;
1370
1371 let cache_key = if deps.is_empty() {
1373 CacheKey::simple(eval_key.to_string())
1374 } else {
1375 let filtered_deps: IndexSet<String> = deps
1377 .iter()
1378 .filter(|dep_key| JSONEval::should_cache_dependency(dep_key))
1379 .cloned()
1380 .collect();
1381
1382 let dep_values: Vec<(String, &Value)> = filtered_deps
1384 .iter()
1385 .filter_map(|dep_key| {
1386 eval_data.get(dep_key).map(|v| (dep_key.clone(), v))
1387 })
1388 .collect();
1389
1390 CacheKey::new(eval_key.to_string(), &filtered_deps, &dep_values)
1391 };
1392
1393 self.eval_cache.get(&cache_key).map(|arc_val| (*arc_val).clone())
1395 }
1396
1397 fn cache_result(&self, eval_key: &str, value: Value, eval_data: &EvalData) {
1399 if !self.cache_enabled {
1401 return;
1402 }
1403
1404 let deps = match self.dependencies.get(eval_key) {
1406 Some(d) => d,
1407 None => {
1408 let cache_key = CacheKey::simple(eval_key.to_string());
1410 self.eval_cache.insert(cache_key, value);
1411 return;
1412 }
1413 };
1414
1415 let filtered_deps: IndexSet<String> = deps
1417 .iter()
1418 .filter(|dep_key| JSONEval::should_cache_dependency(dep_key))
1419 .cloned()
1420 .collect();
1421
1422 let dep_values: Vec<(String, &Value)> = filtered_deps
1423 .iter()
1424 .filter_map(|dep_key| {
1425 eval_data.get(dep_key).map(|v| (dep_key.clone(), v))
1426 })
1427 .collect();
1428
1429 let cache_key = CacheKey::new(eval_key.to_string(), &filtered_deps, &dep_values);
1430 self.eval_cache.insert(cache_key, value);
1431 }
1432
1433 fn purge_cache_for_changed_data_with_comparison(
1437 &self,
1438 changed_data_paths: &[String],
1439 old_data: &Value,
1440 new_data: &Value
1441 ) {
1442 if changed_data_paths.is_empty() {
1443 return;
1444 }
1445
1446 let mut actually_changed_paths = Vec::new();
1448 for path in changed_data_paths {
1449 let old_val = old_data.pointer(path);
1450 let new_val = new_data.pointer(path);
1451
1452 if old_val != new_val {
1454 actually_changed_paths.push(path.clone());
1455 }
1456 }
1457
1458 if actually_changed_paths.is_empty() {
1460 return;
1461 }
1462
1463 let mut affected_eval_keys = IndexSet::new();
1465
1466 for (eval_key, deps) in self.dependencies.iter() {
1467 let is_affected = deps.iter().any(|dep| {
1469 actually_changed_paths.iter().any(|changed_path| {
1471 dep == changed_path ||
1473 dep.starts_with(&format!("{}/", changed_path)) ||
1474 changed_path.starts_with(&format!("{}/", dep))
1475 })
1476 });
1477
1478 if is_affected {
1479 affected_eval_keys.insert(eval_key.clone());
1480 }
1481 }
1482
1483 self.eval_cache.retain(|cache_key, _| {
1486 !affected_eval_keys.contains(&cache_key.eval_key)
1487 });
1488 }
1489
1490 fn purge_cache_for_changed_data(&self, changed_data_paths: &[String]) {
1493 if changed_data_paths.is_empty() {
1494 return;
1495 }
1496
1497 let mut affected_eval_keys = IndexSet::new();
1499
1500 for (eval_key, deps) in self.dependencies.iter() {
1501 let is_affected = deps.iter().any(|dep| {
1503 changed_data_paths.iter().any(|changed_path| {
1505 dep == changed_path ||
1507 dep.starts_with(&format!("{}/", changed_path)) ||
1508 changed_path.starts_with(&format!("{}/", dep))
1509 })
1510 });
1511
1512 if is_affected {
1513 affected_eval_keys.insert(eval_key.clone());
1514 }
1515 }
1516
1517 self.eval_cache.retain(|cache_key, _| {
1520 !affected_eval_keys.contains(&cache_key.eval_key)
1521 });
1522 }
1523
1524 fn purge_cache_for_context_change(&self) {
1526 let mut affected_eval_keys = IndexSet::new();
1528
1529 for (eval_key, deps) in self.dependencies.iter() {
1530 let is_affected = deps.iter().any(|dep| {
1531 dep == "$context" || dep.starts_with("$context.") || dep.starts_with("/$context")
1532 });
1533
1534 if is_affected {
1535 affected_eval_keys.insert(eval_key.clone());
1536 }
1537 }
1538
1539 self.eval_cache.retain(|cache_key, _| {
1540 !affected_eval_keys.contains(&cache_key.eval_key)
1541 });
1542 }
1543
1544 pub fn cache_stats(&self) -> CacheStats {
1546 self.eval_cache.stats()
1547 }
1548
1549 pub fn clear_cache(&mut self) {
1551 self.eval_cache.clear();
1552 for subform in self.subforms.values_mut() {
1553 subform.clear_cache();
1554 }
1555 }
1556
1557 pub fn cache_len(&self) -> usize {
1559 self.eval_cache.len()
1560 }
1561
1562 pub fn enable_cache(&mut self) {
1565 self.cache_enabled = true;
1566 for subform in self.subforms.values_mut() {
1567 subform.enable_cache();
1568 }
1569 }
1570
1571 pub fn disable_cache(&mut self) {
1575 self.cache_enabled = false;
1576 self.eval_cache.clear(); for subform in self.subforms.values_mut() {
1578 subform.disable_cache();
1579 }
1580 }
1581
1582 pub fn is_cache_enabled(&self) -> bool {
1584 self.cache_enabled
1585 }
1586
1587 fn evaluate_others(&mut self, paths: Option<&[String]>) {
1588 time_block!(" evaluate_others()", {
1589 time_block!(" evaluate_options_templates", {
1591 self.evaluate_options_templates(paths);
1592 });
1593
1594 let combined_count = self.rules_evaluations.len() + self.others_evaluations.len();
1597 if combined_count == 0 {
1598 return;
1599 }
1600
1601 time_block!(" evaluate rules+others", {
1602 let eval_data_snapshot = self.eval_data.clone();
1603
1604 let normalized_paths: Option<Vec<String>> = paths.map(|p_list| {
1605 p_list.iter()
1606 .flat_map(|p| {
1607 let ptr = path_utils::dot_notation_to_schema_pointer(p);
1608 let with_props = if ptr.starts_with("#/") {
1610 format!("#/properties/{}", &ptr[2..])
1611 } else {
1612 ptr.clone()
1613 };
1614 vec![ptr, with_props]
1615 })
1616 .collect()
1617 });
1618
1619 #[cfg(feature = "parallel")]
1620 {
1621 let combined_results: Mutex<Vec<(String, Value)>> = Mutex::new(Vec::with_capacity(combined_count));
1622
1623 self.rules_evaluations
1624 .par_iter()
1625 .chain(self.others_evaluations.par_iter())
1626 .for_each(|eval_key| {
1627 if let Some(filter_paths) = normalized_paths.as_ref() {
1629 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
1630 return;
1631 }
1632 }
1633
1634 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
1635
1636 if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
1638 return;
1639 }
1640
1641 if let Some(logic_id) = self.evaluations.get(eval_key) {
1643 if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
1644 let cleaned_val = clean_float_noise(val);
1645 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
1647 combined_results.lock().unwrap().push((pointer_path, cleaned_val));
1648 }
1649 }
1650 });
1651
1652 for (result_path, value) in combined_results.into_inner().unwrap() {
1654 if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&result_path) {
1655 if !result_path.starts_with("$") && result_path.contains("/rules/") && !result_path.ends_with("/value") {
1658 match pointer_value.as_object_mut() {
1659 Some(pointer_obj) => {
1660 pointer_obj.remove("$evaluation");
1661 pointer_obj.insert("value".to_string(), value);
1662 },
1663 None => continue,
1664 }
1665 } else {
1666 *pointer_value = value;
1667 }
1668 }
1669 }
1670 }
1671
1672 #[cfg(not(feature = "parallel"))]
1673 {
1674 let combined_evals: Vec<&String> = self.rules_evaluations.iter()
1676 .chain(self.others_evaluations.iter())
1677 .collect();
1678
1679 for eval_key in combined_evals {
1680 if let Some(filter_paths) = normalized_paths.as_ref() {
1682 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
1683 continue;
1684 }
1685 }
1686
1687 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
1688
1689 if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
1691 continue;
1692 }
1693
1694 if let Some(logic_id) = self.evaluations.get(eval_key) {
1696 if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
1697 let cleaned_val = clean_float_noise(val);
1698 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
1700
1701 if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
1702 if !pointer_path.starts_with("$") && pointer_path.contains("/rules/") && !pointer_path.ends_with("/value") {
1703 match pointer_value.as_object_mut() {
1704 Some(pointer_obj) => {
1705 pointer_obj.remove("$evaluation");
1706 pointer_obj.insert("value".to_string(), cleaned_val);
1707 },
1708 None => continue,
1709 }
1710 } else {
1711 *pointer_value = cleaned_val;
1712 }
1713 }
1714 }
1715 }
1716 }
1717 }
1718 });
1719 });
1720 }
1721
1722 fn evaluate_options_templates(&mut self, paths: Option<&[String]>) {
1724 let templates_to_eval = self.options_templates.clone();
1726
1727 for (path, template_str, params_path) in templates_to_eval.iter() {
1729 if let Some(filter_paths) = paths {
1733 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| path.starts_with(p.as_str()) || p.starts_with(path.as_str())) {
1734 continue;
1735 }
1736 }
1737
1738 if let Some(params) = self.evaluated_schema.pointer(¶ms_path) {
1739 if let Ok(evaluated) = self.evaluate_template(&template_str, params) {
1740 if let Some(target) = self.evaluated_schema.pointer_mut(&path) {
1741 *target = Value::String(evaluated);
1742 }
1743 }
1744 }
1745 }
1746 }
1747
1748 fn evaluate_template(&self, template: &str, params: &Value) -> Result<String, String> {
1750 let mut result = template.to_string();
1751
1752 if let Value::Object(params_map) = params {
1754 for (key, value) in params_map {
1755 let placeholder = format!("{{{}}}", key);
1756 if let Some(str_val) = value.as_str() {
1757 result = result.replace(&placeholder, str_val);
1758 } else {
1759 result = result.replace(&placeholder, &value.to_string());
1761 }
1762 }
1763 }
1764
1765 Ok(result)
1766 }
1767
1768 pub fn compile_logic(&self, logic_str: &str) -> Result<CompiledLogicId, String> {
1784 rlogic::compiled_logic_store::compile_logic(logic_str)
1785 }
1786
1787 pub fn compile_logic_value(&self, logic: &Value) -> Result<CompiledLogicId, String> {
1804 rlogic::compiled_logic_store::compile_logic_value(logic)
1805 }
1806
1807 pub fn run_logic(&mut self, logic_id: CompiledLogicId, data: Option<&Value>, context: Option<&Value>) -> Result<Value, String> {
1824 let compiled_logic = rlogic::compiled_logic_store::get_compiled_logic(logic_id)
1826 .ok_or_else(|| format!("Compiled logic ID {:?} not found in store", logic_id))?;
1827
1828 let eval_data_value = if let Some(input_data) = data {
1832 let context_value = context.unwrap_or(&self.context);
1833
1834 self.eval_data.replace_data_and_context(input_data.clone(), context_value.clone());
1835 self.eval_data.data()
1836 } else {
1837 self.eval_data.data()
1838 };
1839
1840 let evaluator = Evaluator::new();
1842 let result = evaluator.evaluate(&compiled_logic, &eval_data_value)?;
1843
1844 Ok(clean_float_noise(result))
1845 }
1846
1847 pub fn compile_and_run_logic(&mut self, logic_str: &str, data: Option<&str>, context: Option<&str>) -> Result<Value, String> {
1863 let compiled_logic = self.compile_logic(logic_str)?;
1865
1866 let data_value = if let Some(data_str) = data {
1868 Some(json_parser::parse_json_str(data_str)?)
1869 } else {
1870 None
1871 };
1872
1873 let context_value = if let Some(ctx_str) = context {
1874 Some(json_parser::parse_json_str(ctx_str)?)
1875 } else {
1876 None
1877 };
1878
1879 self.run_logic(compiled_logic, data_value.as_ref(), context_value.as_ref())
1881 }
1882
1883 pub fn resolve_layout(&mut self, evaluate: bool) -> Result<(), String> {
1893 if evaluate {
1894 let data_str = serde_json::to_string(&self.data)
1896 .map_err(|e| format!("Failed to serialize data: {}", e))?;
1897 self.evaluate(&data_str, None, None)?;
1898 }
1899
1900 self.resolve_layout_internal();
1901 Ok(())
1902 }
1903
1904 fn resolve_layout_internal(&mut self) {
1905 time_block!(" resolve_layout_internal()", {
1906 let layout_paths = self.layout_paths.clone();
1909
1910 time_block!(" resolve_layout_elements", {
1911 for layout_path in layout_paths.iter() {
1912 self.resolve_layout_elements(layout_path);
1913 }
1914 });
1915
1916 time_block!(" propagate_parent_conditions", {
1918 for layout_path in layout_paths.iter() {
1919 self.propagate_parent_conditions(layout_path);
1920 }
1921 });
1922 });
1923 }
1924
1925 fn propagate_parent_conditions(&mut self, layout_elements_path: &str) {
1927 let normalized_path = path_utils::normalize_to_json_pointer(layout_elements_path);
1929
1930 let elements = if let Some(Value::Array(arr)) = self.evaluated_schema.pointer_mut(&normalized_path) {
1932 mem::take(arr)
1933 } else {
1934 return;
1935 };
1936
1937 let mut updated_elements = Vec::with_capacity(elements.len());
1939 for element in elements {
1940 updated_elements.push(self.apply_parent_conditions(element, false, false));
1941 }
1942
1943 if let Some(target) = self.evaluated_schema.pointer_mut(&normalized_path) {
1945 *target = Value::Array(updated_elements);
1946 }
1947 }
1948
1949 fn apply_parent_conditions(&self, element: Value, parent_hidden: bool, parent_disabled: bool) -> Value {
1951 if let Value::Object(mut map) = element {
1952 let mut element_hidden = parent_hidden;
1954 let mut element_disabled = parent_disabled;
1955
1956 if let Some(Value::Object(condition)) = map.get("condition") {
1958 if let Some(Value::Bool(hidden)) = condition.get("hidden") {
1959 element_hidden = element_hidden || *hidden;
1960 }
1961 if let Some(Value::Bool(disabled)) = condition.get("disabled") {
1962 element_disabled = element_disabled || *disabled;
1963 }
1964 }
1965
1966 if let Some(Value::Object(hide_layout)) = map.get("hideLayout") {
1968 if let Some(Value::Bool(all_hidden)) = hide_layout.get("all") {
1970 if *all_hidden {
1971 element_hidden = true;
1972 }
1973 }
1974 }
1975
1976 if parent_hidden || parent_disabled {
1978 if map.contains_key("condition") || map.contains_key("$ref") || map.contains_key("$fullpath") {
1980 let mut condition = if let Some(Value::Object(c)) = map.get("condition") {
1981 c.clone()
1982 } else {
1983 serde_json::Map::new()
1984 };
1985
1986 if parent_hidden {
1987 condition.insert("hidden".to_string(), Value::Bool(true));
1988 }
1989 if parent_disabled {
1990 condition.insert("disabled".to_string(), Value::Bool(true));
1991 }
1992
1993 map.insert("condition".to_string(), Value::Object(condition));
1994 }
1995
1996 if parent_hidden && (map.contains_key("hideLayout") || map.contains_key("type")) {
1998 let mut hide_layout = if let Some(Value::Object(h)) = map.get("hideLayout") {
1999 h.clone()
2000 } else {
2001 serde_json::Map::new()
2002 };
2003
2004 hide_layout.insert("all".to_string(), Value::Bool(true));
2006 map.insert("hideLayout".to_string(), Value::Object(hide_layout));
2007 }
2008 }
2009
2010 if map.contains_key("$parentHide") {
2013 map.insert("$parentHide".to_string(), Value::Bool(parent_hidden));
2014 }
2015
2016 if let Some(Value::Array(elements)) = map.get("elements") {
2018 let mut updated_children = Vec::with_capacity(elements.len());
2019 for child in elements {
2020 updated_children.push(self.apply_parent_conditions(
2021 child.clone(),
2022 element_hidden,
2023 element_disabled,
2024 ));
2025 }
2026 map.insert("elements".to_string(), Value::Array(updated_children));
2027 }
2028
2029 return Value::Object(map);
2030 }
2031
2032 element
2033 }
2034
2035 fn resolve_layout_elements(&mut self, layout_elements_path: &str) {
2037 let normalized_path = path_utils::normalize_to_json_pointer(layout_elements_path);
2039
2040 let elements = if let Some(Value::Array(arr)) = self.schema.pointer(&normalized_path) {
2044 arr.clone()
2045 } else {
2046 return;
2047 };
2048
2049 let parent_path = normalized_path
2051 .trim_start_matches('/')
2052 .replace("/elements", "")
2053 .replace('/', ".");
2054
2055 let mut resolved_elements = Vec::with_capacity(elements.len());
2057 for (index, element) in elements.iter().enumerate() {
2058 let element_path = if parent_path.is_empty() {
2059 format!("elements.{}", index)
2060 } else {
2061 format!("{}.elements.{}", parent_path, index)
2062 };
2063 let resolved = self.resolve_element_ref_recursive(element.clone(), &element_path);
2064 resolved_elements.push(resolved);
2065 }
2066
2067 if let Some(target) = self.evaluated_schema.pointer_mut(&normalized_path) {
2069 *target = Value::Array(resolved_elements);
2070 }
2071 }
2072
2073 fn resolve_element_ref_recursive(&self, element: Value, path_context: &str) -> Value {
2076 let resolved = self.resolve_element_ref(element);
2078
2079 if let Value::Object(mut map) = resolved {
2081 if !map.contains_key("$parentHide") {
2085 map.insert("$parentHide".to_string(), Value::Bool(false));
2086 }
2087
2088 if !map.contains_key("$fullpath") {
2090 map.insert("$fullpath".to_string(), Value::String(path_context.to_string()));
2091 }
2092
2093 if !map.contains_key("$path") {
2094 let last_segment = path_context.split('.').last().unwrap_or(path_context);
2096 map.insert("$path".to_string(), Value::String(last_segment.to_string()));
2097 }
2098
2099 if let Some(Value::Array(elements)) = map.get("elements") {
2101 let mut resolved_nested = Vec::with_capacity(elements.len());
2102 for (index, nested_element) in elements.iter().enumerate() {
2103 let nested_path = format!("{}.elements.{}", path_context, index);
2104 resolved_nested.push(self.resolve_element_ref_recursive(nested_element.clone(), &nested_path));
2105 }
2106 map.insert("elements".to_string(), Value::Array(resolved_nested));
2107 }
2108
2109 return Value::Object(map);
2110 }
2111
2112 resolved
2113 }
2114
2115 fn resolve_element_ref(&self, element: Value) -> Value {
2117 match element {
2118 Value::Object(mut map) => {
2119 if let Some(Value::String(ref_path)) = map.get("$ref").cloned() {
2121 let dotted_path = path_utils::pointer_to_dot_notation(&ref_path);
2123
2124 let last_segment = dotted_path.split('.').last().unwrap_or(&dotted_path);
2126
2127 map.insert("$fullpath".to_string(), Value::String(dotted_path.clone()));
2129 map.insert("$path".to_string(), Value::String(last_segment.to_string()));
2130 map.insert("$parentHide".to_string(), Value::Bool(false));
2131
2132 let normalized_path = if ref_path.starts_with('#') || ref_path.starts_with('/') {
2135 path_utils::normalize_to_json_pointer(&ref_path)
2137 } else {
2138 let schema_pointer = path_utils::dot_notation_to_schema_pointer(&ref_path);
2140 let schema_path = path_utils::normalize_to_json_pointer(&schema_pointer);
2141
2142 if self.evaluated_schema.pointer(&schema_path).is_some() {
2144 schema_path
2145 } else {
2146 let with_properties = format!("/properties/{}", ref_path.replace('.', "/properties/"));
2148 with_properties
2149 }
2150 };
2151
2152 if let Some(referenced_value) = self.evaluated_schema.pointer(&normalized_path) {
2154 let resolved = referenced_value.clone();
2156
2157 if let Value::Object(mut resolved_map) = resolved {
2159 map.remove("$ref");
2161
2162 if let Some(Value::Object(layout_obj)) = resolved_map.remove("$layout") {
2165 let mut result = layout_obj.clone();
2167
2168 resolved_map.remove("properties");
2170
2171 for (key, value) in resolved_map {
2173 if key != "type" || !result.contains_key("type") {
2174 result.insert(key, value);
2175 }
2176 }
2177
2178 for (key, value) in map {
2180 result.insert(key, value);
2181 }
2182
2183 return Value::Object(result);
2184 } else {
2185 for (key, value) in map {
2187 resolved_map.insert(key, value);
2188 }
2189
2190 return Value::Object(resolved_map);
2191 }
2192 } else {
2193 return resolved;
2195 }
2196 }
2197 }
2198
2199 Value::Object(map)
2201 }
2202 _ => element,
2203 }
2204 }
2205
2206 pub fn evaluate_dependents(
2215 &mut self,
2216 changed_paths: &[String],
2217 data: Option<&str>,
2218 context: Option<&str>,
2219 re_evaluate: bool,
2220 ) -> Result<Value, String> {
2221 let _lock = self.eval_lock.lock().unwrap();
2223
2224 if let Some(data_str) = data {
2226 let old_data = self.eval_data.clone_data_without(&["$params"]);
2228
2229 let data_value = json_parser::parse_json_str(data_str)?;
2230 let context_value = if let Some(ctx) = context {
2231 json_parser::parse_json_str(ctx)?
2232 } else {
2233 Value::Object(serde_json::Map::new())
2234 };
2235 self.eval_data.replace_data_and_context(data_value.clone(), context_value);
2236
2237 let data_paths: Vec<String> = changed_paths
2241 .iter()
2242 .map(|path| {
2243 let schema_ptr = path_utils::dot_notation_to_schema_pointer(path);
2246
2247 let normalized = schema_ptr.trim_start_matches('#')
2249 .replace("/properties/", "/");
2250
2251 if normalized.starts_with('/') {
2253 normalized
2254 } else {
2255 format!("/{}", normalized)
2256 }
2257 })
2258 .collect();
2259 self.purge_cache_for_changed_data_with_comparison(&data_paths, &old_data, &data_value);
2260 }
2261
2262 let mut result = Vec::new();
2263 let mut processed = IndexSet::new();
2264
2265 let mut to_process: Vec<(String, bool)> = changed_paths
2268 .iter()
2269 .map(|path| (path_utils::dot_notation_to_schema_pointer(path), false))
2270 .collect(); while let Some((current_path, is_transitive)) = to_process.pop() {
2274 if processed.contains(¤t_path) {
2275 continue;
2276 }
2277 processed.insert(current_path.clone());
2278
2279 let current_data_path = path_utils::normalize_to_json_pointer(¤t_path)
2281 .replace("/properties/", "/")
2282 .trim_start_matches('#')
2283 .to_string();
2284 let mut current_value = self.eval_data.data().pointer(¤t_data_path)
2285 .cloned()
2286 .unwrap_or(Value::Null);
2287
2288 if let Some(dependent_items) = self.dependents_evaluations.get(¤t_path) {
2290 for dep_item in dependent_items {
2291 let ref_path = &dep_item.ref_path;
2292 let pointer_path = path_utils::normalize_to_json_pointer(ref_path);
2293 let data_path = pointer_path.replace("/properties/", "/");
2295
2296 let current_ref_value = self.eval_data.data().pointer(&data_path)
2297 .cloned()
2298 .unwrap_or(Value::Null);
2299
2300 let field = self.evaluated_schema.pointer(&pointer_path).cloned();
2302
2303 let parent_path = if let Some(last_slash) = pointer_path.rfind("/properties") {
2305 &pointer_path[..last_slash]
2306 } else {
2307 "/"
2308 };
2309 let mut parent_field = if parent_path.is_empty() || parent_path == "/" {
2310 self.evaluated_schema.clone()
2311 } else {
2312 self.evaluated_schema.pointer(parent_path).cloned()
2313 .unwrap_or_else(|| Value::Object(serde_json::Map::new()))
2314 };
2315
2316 if let Value::Object(ref mut map) = parent_field {
2318 map.remove("properties");
2319 map.remove("$layout");
2320 }
2321
2322 let mut change_obj = serde_json::Map::new();
2323 change_obj.insert("$ref".to_string(), Value::String(path_utils::pointer_to_dot_notation(&data_path)));
2324 if let Some(f) = field {
2325 change_obj.insert("$field".to_string(), f);
2326 }
2327 change_obj.insert("$parentField".to_string(), parent_field);
2328 change_obj.insert("transitive".to_string(), Value::Bool(is_transitive));
2329
2330 let mut add_transitive = false;
2331 let mut add_deps = false;
2332 if let Some(clear_val) = &dep_item.clear {
2334 let clear_val_clone = clear_val.clone();
2335 let should_clear = Self::evaluate_dependent_value_static(&self.engine, &self.evaluations, &self.eval_data, &clear_val_clone, ¤t_value, ¤t_ref_value)?;
2336 let clear_bool = match should_clear {
2337 Value::Bool(b) => b,
2338 _ => false,
2339 };
2340
2341 if clear_bool {
2342 if data_path == current_data_path {
2344 current_value = Value::Null;
2345 }
2346 self.eval_data.set(&data_path, Value::Null);
2347 change_obj.insert("clear".to_string(), Value::Bool(true));
2348 add_transitive = true;
2349 add_deps = true;
2350 }
2351 }
2352
2353 if let Some(value_val) = &dep_item.value {
2355 let value_val_clone = value_val.clone();
2356 let computed_value = Self::evaluate_dependent_value_static(&self.engine, &self.evaluations, &self.eval_data, &value_val_clone, ¤t_value, ¤t_ref_value)?;
2357 let cleaned_val = clean_float_noise(computed_value.clone());
2358
2359 if cleaned_val != current_ref_value && cleaned_val != Value::Null {
2360 if data_path == current_data_path {
2362 current_value = cleaned_val.clone();
2363 }
2364 self.eval_data.set(&data_path, cleaned_val.clone());
2365 change_obj.insert("value".to_string(), cleaned_val);
2366 add_transitive = true;
2367 add_deps = true;
2368 }
2369 }
2370
2371 if add_deps {
2373 result.push(Value::Object(change_obj));
2374 }
2375
2376 if add_transitive {
2378 to_process.push((ref_path.clone(), true));
2379 }
2380 }
2381 }
2382 }
2383
2384 if re_evaluate {
2388 drop(_lock); self.evaluate_internal(None)?;
2390 }
2391
2392 Ok(Value::Array(result))
2393 }
2394
2395 fn evaluate_dependent_value_static(
2397 engine: &RLogic,
2398 evaluations: &IndexMap<String, LogicId>,
2399 eval_data: &EvalData,
2400 value: &Value,
2401 changed_field_value: &Value,
2402 changed_field_ref_value: &Value
2403 ) -> Result<Value, String> {
2404 match value {
2405 Value::String(eval_key) => {
2407 if let Some(logic_id) = evaluations.get(eval_key) {
2408 let mut internal_context = serde_json::Map::new();
2411 internal_context.insert("$value".to_string(), changed_field_value.clone());
2412 internal_context.insert("$refValue".to_string(), changed_field_ref_value.clone());
2413 let context_value = Value::Object(internal_context);
2414
2415 let result = engine.run_with_context(logic_id, eval_data.data(), &context_value)
2416 .map_err(|e| format!("Failed to evaluate dependent logic '{}': {}", eval_key, e))?;
2417 Ok(result)
2418 } else {
2419 Ok(value.clone())
2421 }
2422 }
2423 Value::Object(map) if map.contains_key("$evaluation") => {
2426 Err("Dependent evaluation contains unparsed $evaluation - schema was not properly parsed".to_string())
2427 }
2428 _ => Ok(value.clone()),
2430 }
2431 }
2432
2433 pub fn validate(
2436 &mut self,
2437 data: &str,
2438 context: Option<&str>,
2439 paths: Option<&[String]>
2440 ) -> Result<ValidationResult, String> {
2441 let _lock = self.eval_lock.lock().unwrap();
2443
2444 let old_data = self.eval_data.clone_data_without(&["$params"]);
2446
2447 let data_value = json_parser::parse_json_str(data)?;
2449 let context_value = if let Some(ctx) = context {
2450 json_parser::parse_json_str(ctx)?
2451 } else {
2452 Value::Object(serde_json::Map::new())
2453 };
2454
2455 self.eval_data.replace_data_and_context(data_value.clone(), context_value);
2457
2458 let changed_data_paths: Vec<String> = if let Some(obj) = data_value.as_object() {
2461 obj.keys().map(|k| format!("/{}", k)).collect()
2462 } else {
2463 Vec::new()
2464 };
2465 self.purge_cache_for_changed_data_with_comparison(&changed_data_paths, &old_data, &data_value);
2466
2467 drop(_lock);
2469
2470 self.evaluate_others(paths);
2475
2476 self.evaluated_schema = self.get_evaluated_schema(false);
2478
2479 let mut errors: IndexMap<String, ValidationError> = IndexMap::new();
2480
2481 for field_path in self.fields_with_rules.iter() {
2484 if let Some(filter_paths) = paths {
2486 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| field_path.starts_with(p.as_str()) || p.starts_with(field_path.as_str())) {
2487 continue;
2488 }
2489 }
2490
2491 self.validate_field(field_path, &data_value, &mut errors);
2492 }
2493
2494 let has_error = !errors.is_empty();
2495
2496 Ok(ValidationResult {
2497 has_error,
2498 errors,
2499 })
2500 }
2501
2502 fn validate_field(
2504 &self,
2505 field_path: &str,
2506 data: &Value,
2507 errors: &mut IndexMap<String, ValidationError>
2508 ) {
2509 if errors.contains_key(field_path) {
2511 return;
2512 }
2513
2514 let schema_path = path_utils::dot_notation_to_schema_pointer(field_path);
2516
2517 let pointer_path = schema_path.trim_start_matches('#');
2519
2520 let field_schema = match self.evaluated_schema.pointer(pointer_path) {
2522 Some(s) => s,
2523 None => {
2524 let alt_path = format!("/properties{}", pointer_path);
2526 match self.evaluated_schema.pointer(&alt_path) {
2527 Some(s) => s,
2528 None => return,
2529 }
2530 }
2531 };
2532
2533 if let Value::Object(schema_map) = field_schema {
2535 if let Some(Value::Object(condition)) = schema_map.get("condition") {
2536 if let Some(Value::Bool(true)) = condition.get("hidden") {
2537 return;
2538 }
2539 }
2540
2541 let rules = match schema_map.get("rules") {
2543 Some(Value::Object(r)) => r,
2544 _ => return,
2545 };
2546
2547 let field_data = self.get_field_data(field_path, data);
2549
2550 for (rule_name, rule_value) in rules {
2552 self.validate_rule(
2553 field_path,
2554 rule_name,
2555 rule_value,
2556 &field_data,
2557 schema_map,
2558 field_schema,
2559 errors
2560 );
2561 }
2562 }
2563 }
2564
2565 fn get_field_data(&self, field_path: &str, data: &Value) -> Value {
2567 let parts: Vec<&str> = field_path.split('.').collect();
2568 let mut current = data;
2569
2570 for part in parts {
2571 match current {
2572 Value::Object(map) => {
2573 current = map.get(part).unwrap_or(&Value::Null);
2574 }
2575 _ => return Value::Null,
2576 }
2577 }
2578
2579 current.clone()
2580 }
2581
2582 fn validate_rule(
2584 &self,
2585 field_path: &str,
2586 rule_name: &str,
2587 rule_value: &Value,
2588 field_data: &Value,
2589 schema_map: &serde_json::Map<String, Value>,
2590 _schema: &Value,
2591 errors: &mut IndexMap<String, ValidationError>
2592 ) {
2593 if errors.contains_key(field_path) {
2595 return;
2596 }
2597
2598 let mut disabled_field = false;
2599 if let Some(Value::Object(condition)) = schema_map.get("condition") {
2601 if let Some(Value::Bool(true)) = condition.get("disabled") {
2602 disabled_field = true;
2603 }
2604 }
2605
2606 let schema_path = path_utils::dot_notation_to_schema_pointer(field_path);
2609 let rule_path = format!("{}/rules/{}", schema_path.trim_start_matches('#'), rule_name);
2610
2611 let evaluated_rule = if let Some(eval_rule) = self.evaluated_schema.pointer(&rule_path) {
2613 eval_rule.clone()
2614 } else {
2615 rule_value.clone()
2616 };
2617
2618 let (rule_active, rule_message, rule_code, rule_data) = match &evaluated_rule {
2620 Value::Object(rule_obj) => {
2621 let active = rule_obj.get("value").unwrap_or(&Value::Bool(false));
2622
2623 let message = match rule_obj.get("message") {
2625 Some(Value::String(s)) => s.clone(),
2626 Some(Value::Object(msg_obj)) if msg_obj.contains_key("value") => {
2627 msg_obj.get("value")
2628 .and_then(|v| v.as_str())
2629 .unwrap_or("Validation failed")
2630 .to_string()
2631 }
2632 Some(msg_val) => msg_val.as_str().unwrap_or("Validation failed").to_string(),
2633 None => "Validation failed".to_string()
2634 };
2635
2636 let code = rule_obj.get("code")
2637 .and_then(|c| c.as_str())
2638 .map(|s| s.to_string());
2639
2640 let data = rule_obj.get("data").map(|d| {
2642 if let Value::Object(data_obj) = d {
2643 let mut cleaned_data = serde_json::Map::new();
2644 for (key, value) in data_obj {
2645 if let Value::Object(val_obj) = value {
2647 if val_obj.len() == 1 && val_obj.contains_key("value") {
2648 cleaned_data.insert(key.clone(), val_obj["value"].clone());
2649 } else {
2650 cleaned_data.insert(key.clone(), value.clone());
2651 }
2652 } else {
2653 cleaned_data.insert(key.clone(), value.clone());
2654 }
2655 }
2656 Value::Object(cleaned_data)
2657 } else {
2658 d.clone()
2659 }
2660 });
2661
2662 (active.clone(), message, code, data)
2663 }
2664 _ => (evaluated_rule.clone(), "Validation failed".to_string(), None, None)
2665 };
2666
2667 let error_code = rule_code.or_else(|| Some(format!("{}.{}", field_path, rule_name)));
2669
2670 let is_empty = matches!(field_data, Value::Null) ||
2671 (field_data.is_string() && field_data.as_str().unwrap_or("").is_empty()) ||
2672 (field_data.is_array() && field_data.as_array().unwrap().is_empty());
2673
2674 match rule_name {
2675 "required" => {
2676 if !disabled_field && rule_active == Value::Bool(true) {
2677 if is_empty {
2678 errors.insert(field_path.to_string(), ValidationError {
2679 rule_type: "required".to_string(),
2680 message: rule_message,
2681 code: error_code.clone(),
2682 pattern: None,
2683 field_value: None,
2684 data: None,
2685 });
2686 }
2687 }
2688 }
2689 "minLength" => {
2690 if !is_empty {
2691 if let Some(min) = rule_active.as_u64() {
2692 let len = match field_data {
2693 Value::String(s) => s.len(),
2694 Value::Array(a) => a.len(),
2695 _ => 0
2696 };
2697 if len < min as usize {
2698 errors.insert(field_path.to_string(), ValidationError {
2699 rule_type: "minLength".to_string(),
2700 message: rule_message,
2701 code: error_code.clone(),
2702 pattern: None,
2703 field_value: None,
2704 data: None,
2705 });
2706 }
2707 }
2708 }
2709 }
2710 "maxLength" => {
2711 if !is_empty {
2712 if let Some(max) = rule_active.as_u64() {
2713 let len = match field_data {
2714 Value::String(s) => s.len(),
2715 Value::Array(a) => a.len(),
2716 _ => 0
2717 };
2718 if len > max as usize {
2719 errors.insert(field_path.to_string(), ValidationError {
2720 rule_type: "maxLength".to_string(),
2721 message: rule_message,
2722 code: error_code.clone(),
2723 pattern: None,
2724 field_value: None,
2725 data: None,
2726 });
2727 }
2728 }
2729 }
2730 }
2731 "minValue" => {
2732 if !is_empty {
2733 if let Some(min) = rule_active.as_f64() {
2734 if let Some(val) = field_data.as_f64() {
2735 if val < min {
2736 errors.insert(field_path.to_string(), ValidationError {
2737 rule_type: "minValue".to_string(),
2738 message: rule_message,
2739 code: error_code.clone(),
2740 pattern: None,
2741 field_value: None,
2742 data: None,
2743 });
2744 }
2745 }
2746 }
2747 }
2748 }
2749 "maxValue" => {
2750 if !is_empty {
2751 if let Some(max) = rule_active.as_f64() {
2752 if let Some(val) = field_data.as_f64() {
2753 if val > max {
2754 errors.insert(field_path.to_string(), ValidationError {
2755 rule_type: "maxValue".to_string(),
2756 message: rule_message,
2757 code: error_code.clone(),
2758 pattern: None,
2759 field_value: None,
2760 data: None,
2761 });
2762 }
2763 }
2764 }
2765 }
2766 }
2767 "pattern" => {
2768 if !is_empty {
2769 if let Some(pattern) = rule_active.as_str() {
2770 if let Some(text) = field_data.as_str() {
2771 if let Ok(regex) = regex::Regex::new(pattern) {
2772 if !regex.is_match(text) {
2773 errors.insert(field_path.to_string(), ValidationError {
2774 rule_type: "pattern".to_string(),
2775 message: rule_message,
2776 code: error_code.clone(),
2777 pattern: Some(pattern.to_string()),
2778 field_value: Some(text.to_string()),
2779 data: None,
2780 });
2781 }
2782 }
2783 }
2784 }
2785 }
2786 }
2787 "evaluation" => {
2788 if let Value::Array(eval_array) = &evaluated_rule {
2791 for (idx, eval_item) in eval_array.iter().enumerate() {
2792 if let Value::Object(eval_obj) = eval_item {
2793 let eval_result = eval_obj.get("value").unwrap_or(&Value::Bool(true));
2795
2796 let is_falsy = match eval_result {
2798 Value::Bool(false) => true,
2799 Value::Null => true,
2800 Value::Number(n) => n.as_f64() == Some(0.0),
2801 Value::String(s) => s.is_empty(),
2802 Value::Array(a) => a.is_empty(),
2803 _ => false,
2804 };
2805
2806 if is_falsy {
2807 let eval_code = eval_obj.get("code")
2808 .and_then(|c| c.as_str())
2809 .map(|s| s.to_string())
2810 .or_else(|| Some(format!("{}.evaluation.{}", field_path, idx)));
2811
2812 let eval_message = eval_obj.get("message")
2813 .and_then(|m| m.as_str())
2814 .unwrap_or("Validation failed")
2815 .to_string();
2816
2817 let eval_data = eval_obj.get("data").cloned();
2818
2819 errors.insert(field_path.to_string(), ValidationError {
2820 rule_type: "evaluation".to_string(),
2821 message: eval_message,
2822 code: eval_code,
2823 pattern: None,
2824 field_value: None,
2825 data: eval_data,
2826 });
2827
2828 break;
2830 }
2831 }
2832 }
2833 }
2834 }
2835 _ => {
2836 if !is_empty {
2840 let is_falsy = match &rule_active {
2842 Value::Bool(false) => true,
2843 Value::Null => true,
2844 Value::Number(n) => n.as_f64() == Some(0.0),
2845 Value::String(s) => s.is_empty(),
2846 Value::Array(a) => a.is_empty(),
2847 _ => false,
2848 };
2849
2850 if is_falsy {
2851 errors.insert(field_path.to_string(), ValidationError {
2852 rule_type: "evaluation".to_string(),
2853 message: rule_message,
2854 code: error_code.clone(),
2855 pattern: None,
2856 field_value: None,
2857 data: rule_data,
2858 });
2859 }
2860 }
2861 }
2862 }
2863 }
2864}
2865
2866#[derive(Debug, Clone, Serialize, Deserialize)]
2868pub struct ValidationError {
2869 #[serde(rename = "type")]
2870 pub rule_type: String,
2871 pub message: String,
2872 #[serde(skip_serializing_if = "Option::is_none")]
2873 pub code: Option<String>,
2874 #[serde(skip_serializing_if = "Option::is_none")]
2875 pub pattern: Option<String>,
2876 #[serde(skip_serializing_if = "Option::is_none")]
2877 pub field_value: Option<String>,
2878 #[serde(skip_serializing_if = "Option::is_none")]
2879 pub data: Option<Value>,
2880}
2881
2882#[derive(Debug, Clone, Serialize, Deserialize)]
2884pub struct ValidationResult {
2885 pub has_error: bool,
2886 pub errors: IndexMap<String, ValidationError>,
2887}
2888