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(deps) = self.dependencies.get(eval_key) {
804 if !deps.is_empty() {
805 return;
806 }
807 }
808
809 if let Some(filter_paths) = normalized_paths {
811 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
812 return;
813 }
814 }
815
816 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
819
820 if let Some(_) = self.try_get_cached(eval_key, &eval_data_values) {
822 return;
823 }
824
825 if let Some(logic_id) = self.evaluations.get(eval_key) {
827 if let Ok(val) = self.engine.run(logic_id, eval_data_values.data()) {
828 let cleaned_val = clean_float_noise(val);
829 self.cache_result(eval_key, Value::Null, &eval_data_values);
831 value_results.lock().unwrap().push((pointer_path, cleaned_val));
832 }
833 }
834 });
835
836 for (result_path, value) in value_results.into_inner().unwrap() {
838 if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&result_path) {
839 *pointer_value = value;
840 }
841 }
842 }
843
844 #[cfg(feature = "parallel")]
846 let value_eval_items = if self.value_evaluations.len() > 100 { &self.value_evaluations[0..0] } else { &self.value_evaluations };
847
848 #[cfg(not(feature = "parallel"))]
849 let value_eval_items = &self.value_evaluations;
850
851 for eval_key in value_eval_items.iter() {
852 if let Some(deps) = self.dependencies.get(eval_key) {
854 if !deps.is_empty() {
855 continue;
856 }
857 }
858
859 if let Some(filter_paths) = normalized_paths {
861 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
862 continue;
863 }
864 }
865
866 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
867
868 if let Some(_) = self.try_get_cached(eval_key, &eval_data_values) {
870 continue;
871 }
872
873 if let Some(logic_id) = self.evaluations.get(eval_key) {
875 if let Ok(val) = self.engine.run(logic_id, eval_data_values.data()) {
876 let cleaned_val = clean_float_noise(val);
877 self.cache_result(eval_key, Value::Null, &eval_data_values);
879
880 if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
881 *pointer_value = cleaned_val;
882 }
883 }
884 }
885 }
886 });
887
888 time_block!(" process batches", {
889 for batch in eval_batches {
890 if batch.is_empty() {
892 continue;
893 }
894
895 if let Some(filter_paths) = normalized_paths {
898 if !filter_paths.is_empty() {
899 let batch_has_match = batch.iter().any(|eval_key| {
900 filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str()))
901 });
902 if !batch_has_match {
903 continue;
904 }
905 }
906 }
907
908 let eval_data_snapshot = self.eval_data.clone();
915
916 #[cfg(feature = "parallel")]
920 if batch.len() > 1000 {
921 let results: Mutex<Vec<(String, String, Value)>> = Mutex::new(Vec::with_capacity(batch.len()));
922 batch.par_iter().for_each(|eval_key| {
923 if let Some(filter_paths) = normalized_paths {
925 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
926 return;
927 }
928 }
929
930 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
931
932 if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
934 return;
935 }
936
937 let is_table = self.table_metadata.contains_key(eval_key);
939
940 if is_table {
941 if let Ok(rows) = table_evaluate::evaluate_table(self, eval_key, &eval_data_snapshot) {
943 let value = Value::Array(rows);
944 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
946 results.lock().unwrap().push((eval_key.clone(), pointer_path, value));
947 }
948 } else {
949 if let Some(logic_id) = self.evaluations.get(eval_key) {
950 if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
952 let cleaned_val = clean_float_noise(val);
953 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
955 results.lock().unwrap().push((eval_key.clone(), pointer_path, cleaned_val));
956 }
957 }
958 }
959 });
960
961 for (_eval_key, path, value) in results.into_inner().unwrap() {
963 let cleaned_value = clean_float_noise(value);
964
965 self.eval_data.set(&path, cleaned_value.clone());
966 if let Some(schema_value) = self.evaluated_schema.pointer_mut(&path) {
968 *schema_value = cleaned_value;
969 }
970 }
971 continue;
972 }
973
974 #[cfg(not(feature = "parallel"))]
976 let batch_items = &batch;
977
978 #[cfg(feature = "parallel")]
979 let batch_items = if batch.len() > 1000 { &batch[0..0] } else { &batch }; for eval_key in batch_items {
982 if let Some(filter_paths) = normalized_paths {
984 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
985 continue;
986 }
987 }
988
989 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
990
991 if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
993 continue;
994 }
995
996 let is_table = self.table_metadata.contains_key(eval_key);
998
999 if is_table {
1000 if let Ok(rows) = table_evaluate::evaluate_table(self, eval_key, &eval_data_snapshot) {
1001 let value = Value::Array(rows);
1002 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
1004
1005 let cleaned_value = clean_float_noise(value);
1006 self.eval_data.set(&pointer_path, cleaned_value.clone());
1007 if let Some(schema_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
1008 *schema_value = cleaned_value;
1009 }
1010 }
1011 } else {
1012 if let Some(logic_id) = self.evaluations.get(eval_key) {
1013 if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
1014 let cleaned_val = clean_float_noise(val);
1015 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
1017
1018 self.eval_data.set(&pointer_path, cleaned_val.clone());
1019 if let Some(schema_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
1020 *schema_value = cleaned_val;
1021 }
1022 }
1023 }
1024 }
1025 }
1026 }
1027 });
1028
1029 drop(_lock);
1031
1032 self.evaluate_others(paths);
1033
1034 Ok(())
1035 })
1036 }
1037
1038 pub fn get_evaluated_schema(&mut self, skip_layout: bool) -> Value {
1048 time_block!("get_evaluated_schema()", {
1049 if !skip_layout {
1050 self.resolve_layout_internal();
1051 }
1052
1053 self.evaluated_schema.clone()
1054 })
1055 }
1056
1057 pub fn get_evaluated_schema_msgpack(&mut self, skip_layout: bool) -> Result<Vec<u8>, String> {
1074 if !skip_layout {
1075 self.resolve_layout_internal();
1076 }
1077
1078 rmp_serde::to_vec(&self.evaluated_schema)
1082 .map_err(|e| format!("Failed to serialize schema to MessagePack: {}", e))
1083 }
1084
1085 pub fn get_schema_value(&mut self) -> Value {
1089 if !self.data.is_object() {
1091 self.data = Value::Object(serde_json::Map::new());
1092 }
1093
1094 for eval_key in self.value_evaluations.iter() {
1096 let clean_key = eval_key.replace("#", "");
1097
1098 if clean_key.ends_with("/value") && (clean_key.contains("/rules/") || clean_key.contains("/options/")) {
1100 continue;
1101 }
1102
1103 let path = clean_key.replace("/properties", "").replace("/value", "");
1104
1105 let value = match self.evaluated_schema.pointer(&clean_key) {
1107 Some(v) => v.clone(),
1108 None => continue,
1109 };
1110
1111 let path_parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
1113
1114 if path_parts.is_empty() {
1115 continue;
1116 }
1117
1118 let mut current = &mut self.data;
1120 for (i, part) in path_parts.iter().enumerate() {
1121 let is_last = i == path_parts.len() - 1;
1122
1123 if is_last {
1124 if let Some(obj) = current.as_object_mut() {
1126 obj.insert(part.to_string(), clean_float_noise(value.clone()));
1127 }
1128 } else {
1129 if let Some(obj) = current.as_object_mut() {
1131 current = obj.entry(part.to_string())
1132 .or_insert_with(|| Value::Object(serde_json::Map::new()));
1133 } else {
1134 break;
1136 }
1137 }
1138 }
1139 }
1140
1141 clean_float_noise(self.data.clone())
1142 }
1143
1144 pub fn get_evaluated_schema_without_params(&mut self, skip_layout: bool) -> Value {
1155 if !skip_layout {
1156 self.resolve_layout_internal();
1157 }
1158
1159 if let Value::Object(mut map) = self.evaluated_schema.clone() {
1161 map.remove("$params");
1162 Value::Object(map)
1163 } else {
1164 self.evaluated_schema.clone()
1165 }
1166 }
1167
1168 pub fn get_evaluated_schema_by_path(&mut self, path: &str, skip_layout: bool) -> Option<Value> {
1180 if !skip_layout {
1181 self.resolve_layout_internal();
1182 }
1183
1184 let pointer = if path.is_empty() {
1186 "".to_string()
1187 } else {
1188 format!("/{}", path.replace(".", "/"))
1189 };
1190
1191 self.evaluated_schema.pointer(&pointer).cloned()
1192 }
1193
1194 pub fn get_evaluated_schema_by_paths(&mut self, paths: &[String], skip_layout: bool, format: Option<ReturnFormat>) -> Value {
1207 let format = format.unwrap_or_default();
1208 if !skip_layout {
1209 self.resolve_layout_internal();
1210 }
1211
1212 let mut result = serde_json::Map::new();
1213
1214 for path in paths {
1215 let pointer = if path.is_empty() {
1217 "".to_string()
1218 } else {
1219 format!("/{}", path.replace(".", "/"))
1220 };
1221
1222 if let Some(value) = self.evaluated_schema.pointer(&pointer) {
1224 self.insert_at_path(&mut result, path, value.clone());
1227 }
1228 }
1229
1230 self.convert_to_format(result, paths, format)
1231 }
1232
1233 fn insert_at_path(&self, obj: &mut serde_json::Map<String, Value>, path: &str, value: Value) {
1235 if path.is_empty() {
1236 if let Value::Object(map) = value {
1238 for (k, v) in map {
1239 obj.insert(k, v);
1240 }
1241 }
1242 return;
1243 }
1244
1245 let parts: Vec<&str> = path.split('.').collect();
1246 if parts.is_empty() {
1247 return;
1248 }
1249
1250 let mut current = obj;
1251 let last_index = parts.len() - 1;
1252
1253 for (i, part) in parts.iter().enumerate() {
1254 if i == last_index {
1255 current.insert(part.to_string(), value);
1257 break;
1258 } else {
1259 current = current
1261 .entry(part.to_string())
1262 .or_insert_with(|| Value::Object(serde_json::Map::new()))
1263 .as_object_mut()
1264 .unwrap();
1265 }
1266 }
1267 }
1268
1269 fn convert_to_format(&self, result: serde_json::Map<String, Value>, paths: &[String], format: ReturnFormat) -> Value {
1271 match format {
1272 ReturnFormat::Nested => Value::Object(result),
1273 ReturnFormat::Flat => {
1274 let mut flat = serde_json::Map::new();
1276 self.flatten_object(&result, String::new(), &mut flat);
1277 Value::Object(flat)
1278 }
1279 ReturnFormat::Array => {
1280 let values: Vec<Value> = paths.iter()
1282 .map(|path| {
1283 let pointer = if path.is_empty() {
1284 "".to_string()
1285 } else {
1286 format!("/{}", path.replace(".", "/"))
1287 };
1288 Value::Object(result.clone()).pointer(&pointer).cloned().unwrap_or(Value::Null)
1289 })
1290 .collect();
1291 Value::Array(values)
1292 }
1293 }
1294 }
1295
1296 fn flatten_object(&self, obj: &serde_json::Map<String, Value>, prefix: String, result: &mut serde_json::Map<String, Value>) {
1298 for (key, value) in obj {
1299 let new_key = if prefix.is_empty() {
1300 key.clone()
1301 } else {
1302 format!("{}.{}", prefix, key)
1303 };
1304
1305 if let Value::Object(nested) = value {
1306 self.flatten_object(nested, new_key, result);
1307 } else {
1308 result.insert(new_key, value.clone());
1309 }
1310 }
1311 }
1312
1313 pub fn get_schema_by_path(&self, path: &str) -> Option<Value> {
1324 let pointer = if path.is_empty() {
1326 "".to_string()
1327 } else {
1328 format!("/{}", path.replace(".", "/"))
1329 };
1330
1331 self.schema.pointer(&pointer).cloned()
1332 }
1333
1334 pub fn get_schema_by_paths(&self, paths: &[String], format: Option<ReturnFormat>) -> Value {
1346 let format = format.unwrap_or_default();
1347 let mut result = serde_json::Map::new();
1348
1349 for path in paths {
1350 let pointer = if path.is_empty() {
1352 "".to_string()
1353 } else {
1354 format!("/{}", path.replace(".", "/"))
1355 };
1356
1357 if let Some(value) = self.schema.pointer(&pointer) {
1359 self.insert_at_path(&mut result, path, value.clone());
1362 }
1363 }
1364
1365 self.convert_to_format(result, paths, format)
1366 }
1367
1368 #[inline]
1371 fn should_cache_dependency(key: &str) -> bool {
1372 if key.starts_with("/$") || key.starts_with('$') {
1373 key == "$context" || key.starts_with("$context.") || key.starts_with("/$context")
1375 } else {
1376 true
1377 }
1378 }
1379
1380 fn try_get_cached(&self, eval_key: &str, eval_data: &EvalData) -> Option<Value> {
1383 if !self.cache_enabled {
1385 return None;
1386 }
1387
1388 let deps = self.dependencies.get(eval_key)?;
1390
1391 let cache_key = if deps.is_empty() {
1393 CacheKey::simple(eval_key.to_string())
1394 } else {
1395 let filtered_deps: IndexSet<String> = deps
1397 .iter()
1398 .filter(|dep_key| JSONEval::should_cache_dependency(dep_key))
1399 .cloned()
1400 .collect();
1401
1402 let dep_values: Vec<(String, &Value)> = filtered_deps
1404 .iter()
1405 .filter_map(|dep_key| {
1406 eval_data.get(dep_key).map(|v| (dep_key.clone(), v))
1407 })
1408 .collect();
1409
1410 CacheKey::new(eval_key.to_string(), &filtered_deps, &dep_values)
1411 };
1412
1413 self.eval_cache.get(&cache_key).map(|arc_val| (*arc_val).clone())
1415 }
1416
1417 fn cache_result(&self, eval_key: &str, value: Value, eval_data: &EvalData) {
1419 if !self.cache_enabled {
1421 return;
1422 }
1423
1424 let deps = match self.dependencies.get(eval_key) {
1426 Some(d) => d,
1427 None => {
1428 let cache_key = CacheKey::simple(eval_key.to_string());
1430 self.eval_cache.insert(cache_key, value);
1431 return;
1432 }
1433 };
1434
1435 let filtered_deps: IndexSet<String> = deps
1437 .iter()
1438 .filter(|dep_key| JSONEval::should_cache_dependency(dep_key))
1439 .cloned()
1440 .collect();
1441
1442 let dep_values: Vec<(String, &Value)> = filtered_deps
1443 .iter()
1444 .filter_map(|dep_key| {
1445 eval_data.get(dep_key).map(|v| (dep_key.clone(), v))
1446 })
1447 .collect();
1448
1449 let cache_key = CacheKey::new(eval_key.to_string(), &filtered_deps, &dep_values);
1450 self.eval_cache.insert(cache_key, value);
1451 }
1452
1453 fn purge_cache_for_changed_data_with_comparison(
1457 &self,
1458 changed_data_paths: &[String],
1459 old_data: &Value,
1460 new_data: &Value
1461 ) {
1462 if changed_data_paths.is_empty() {
1463 return;
1464 }
1465
1466 let mut actually_changed_paths = Vec::new();
1468 for path in changed_data_paths {
1469 let old_val = old_data.pointer(path);
1470 let new_val = new_data.pointer(path);
1471
1472 if old_val != new_val {
1474 actually_changed_paths.push(path.clone());
1475 }
1476 }
1477
1478 if actually_changed_paths.is_empty() {
1480 return;
1481 }
1482
1483 let mut affected_eval_keys = IndexSet::new();
1485
1486 for (eval_key, deps) in self.dependencies.iter() {
1487 let is_affected = deps.iter().any(|dep| {
1489 actually_changed_paths.iter().any(|changed_path| {
1491 dep == changed_path ||
1493 dep.starts_with(&format!("{}/", changed_path)) ||
1494 changed_path.starts_with(&format!("{}/", dep))
1495 })
1496 });
1497
1498 if is_affected {
1499 affected_eval_keys.insert(eval_key.clone());
1500 }
1501 }
1502
1503 self.eval_cache.retain(|cache_key, _| {
1506 !affected_eval_keys.contains(&cache_key.eval_key)
1507 });
1508 }
1509
1510 fn purge_cache_for_changed_data(&self, changed_data_paths: &[String]) {
1513 if changed_data_paths.is_empty() {
1514 return;
1515 }
1516
1517 let mut affected_eval_keys = IndexSet::new();
1519
1520 for (eval_key, deps) in self.dependencies.iter() {
1521 let is_affected = deps.iter().any(|dep| {
1523 changed_data_paths.iter().any(|changed_path| {
1525 dep == changed_path ||
1527 dep.starts_with(&format!("{}/", changed_path)) ||
1528 changed_path.starts_with(&format!("{}/", dep))
1529 })
1530 });
1531
1532 if is_affected {
1533 affected_eval_keys.insert(eval_key.clone());
1534 }
1535 }
1536
1537 self.eval_cache.retain(|cache_key, _| {
1540 !affected_eval_keys.contains(&cache_key.eval_key)
1541 });
1542 }
1543
1544 fn purge_cache_for_context_change(&self) {
1546 let mut affected_eval_keys = IndexSet::new();
1548
1549 for (eval_key, deps) in self.dependencies.iter() {
1550 let is_affected = deps.iter().any(|dep| {
1551 dep == "$context" || dep.starts_with("$context.") || dep.starts_with("/$context")
1552 });
1553
1554 if is_affected {
1555 affected_eval_keys.insert(eval_key.clone());
1556 }
1557 }
1558
1559 self.eval_cache.retain(|cache_key, _| {
1560 !affected_eval_keys.contains(&cache_key.eval_key)
1561 });
1562 }
1563
1564 pub fn cache_stats(&self) -> CacheStats {
1566 self.eval_cache.stats()
1567 }
1568
1569 pub fn clear_cache(&mut self) {
1571 self.eval_cache.clear();
1572 for subform in self.subforms.values_mut() {
1573 subform.clear_cache();
1574 }
1575 }
1576
1577 pub fn cache_len(&self) -> usize {
1579 self.eval_cache.len()
1580 }
1581
1582 pub fn enable_cache(&mut self) {
1585 self.cache_enabled = true;
1586 for subform in self.subforms.values_mut() {
1587 subform.enable_cache();
1588 }
1589 }
1590
1591 pub fn disable_cache(&mut self) {
1595 self.cache_enabled = false;
1596 self.eval_cache.clear(); for subform in self.subforms.values_mut() {
1598 subform.disable_cache();
1599 }
1600 }
1601
1602 pub fn is_cache_enabled(&self) -> bool {
1604 self.cache_enabled
1605 }
1606
1607 fn evaluate_others(&mut self, paths: Option<&[String]>) {
1608 time_block!(" evaluate_others()", {
1609 time_block!(" evaluate_options_templates", {
1611 self.evaluate_options_templates(paths);
1612 });
1613
1614 let combined_count = self.rules_evaluations.len() + self.others_evaluations.len();
1617 if combined_count == 0 {
1618 return;
1619 }
1620
1621 time_block!(" evaluate rules+others", {
1622 let eval_data_snapshot = self.eval_data.clone();
1623
1624 let normalized_paths: Option<Vec<String>> = paths.map(|p_list| {
1625 p_list.iter()
1626 .flat_map(|p| {
1627 let ptr = path_utils::dot_notation_to_schema_pointer(p);
1628 let with_props = if ptr.starts_with("#/") {
1630 format!("#/properties/{}", &ptr[2..])
1631 } else {
1632 ptr.clone()
1633 };
1634 vec![ptr, with_props]
1635 })
1636 .collect()
1637 });
1638
1639 #[cfg(feature = "parallel")]
1640 {
1641 let combined_results: Mutex<Vec<(String, Value)>> = Mutex::new(Vec::with_capacity(combined_count));
1642
1643 self.rules_evaluations
1644 .par_iter()
1645 .chain(self.others_evaluations.par_iter())
1646 .for_each(|eval_key| {
1647 if let Some(filter_paths) = normalized_paths.as_ref() {
1649 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
1650 return;
1651 }
1652 }
1653
1654 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
1655
1656 if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
1658 return;
1659 }
1660
1661 if let Some(logic_id) = self.evaluations.get(eval_key) {
1663 if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
1664 let cleaned_val = clean_float_noise(val);
1665 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
1667 combined_results.lock().unwrap().push((pointer_path, cleaned_val));
1668 }
1669 }
1670 });
1671
1672 for (result_path, value) in combined_results.into_inner().unwrap() {
1674 if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&result_path) {
1675 if !result_path.starts_with("$") && result_path.contains("/rules/") && !result_path.ends_with("/value") {
1678 match pointer_value.as_object_mut() {
1679 Some(pointer_obj) => {
1680 pointer_obj.remove("$evaluation");
1681 pointer_obj.insert("value".to_string(), value);
1682 },
1683 None => continue,
1684 }
1685 } else {
1686 *pointer_value = value;
1687 }
1688 }
1689 }
1690 }
1691
1692 #[cfg(not(feature = "parallel"))]
1693 {
1694 let combined_evals: Vec<&String> = self.rules_evaluations.iter()
1696 .chain(self.others_evaluations.iter())
1697 .collect();
1698
1699 for eval_key in combined_evals {
1700 if let Some(filter_paths) = normalized_paths.as_ref() {
1702 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
1703 continue;
1704 }
1705 }
1706
1707 let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
1708
1709 if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
1711 continue;
1712 }
1713
1714 if let Some(logic_id) = self.evaluations.get(eval_key) {
1716 if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
1717 let cleaned_val = clean_float_noise(val);
1718 self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
1720
1721 if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
1722 if !pointer_path.starts_with("$") && pointer_path.contains("/rules/") && !pointer_path.ends_with("/value") {
1723 match pointer_value.as_object_mut() {
1724 Some(pointer_obj) => {
1725 pointer_obj.remove("$evaluation");
1726 pointer_obj.insert("value".to_string(), cleaned_val);
1727 },
1728 None => continue,
1729 }
1730 } else {
1731 *pointer_value = cleaned_val;
1732 }
1733 }
1734 }
1735 }
1736 }
1737 }
1738 });
1739 });
1740 }
1741
1742 fn evaluate_options_templates(&mut self, paths: Option<&[String]>) {
1744 let templates_to_eval = self.options_templates.clone();
1746
1747 for (path, template_str, params_path) in templates_to_eval.iter() {
1749 if let Some(filter_paths) = paths {
1753 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| path.starts_with(p.as_str()) || p.starts_with(path.as_str())) {
1754 continue;
1755 }
1756 }
1757
1758 if let Some(params) = self.evaluated_schema.pointer(¶ms_path) {
1759 if let Ok(evaluated) = self.evaluate_template(&template_str, params) {
1760 if let Some(target) = self.evaluated_schema.pointer_mut(&path) {
1761 *target = Value::String(evaluated);
1762 }
1763 }
1764 }
1765 }
1766 }
1767
1768 fn evaluate_template(&self, template: &str, params: &Value) -> Result<String, String> {
1770 let mut result = template.to_string();
1771
1772 if let Value::Object(params_map) = params {
1774 for (key, value) in params_map {
1775 let placeholder = format!("{{{}}}", key);
1776 if let Some(str_val) = value.as_str() {
1777 result = result.replace(&placeholder, str_val);
1778 } else {
1779 result = result.replace(&placeholder, &value.to_string());
1781 }
1782 }
1783 }
1784
1785 Ok(result)
1786 }
1787
1788 pub fn compile_logic(&self, logic_str: &str) -> Result<CompiledLogicId, String> {
1804 rlogic::compiled_logic_store::compile_logic(logic_str)
1805 }
1806
1807 pub fn compile_logic_value(&self, logic: &Value) -> Result<CompiledLogicId, String> {
1824 rlogic::compiled_logic_store::compile_logic_value(logic)
1825 }
1826
1827 pub fn run_logic(&mut self, logic_id: CompiledLogicId, data: Option<&Value>, context: Option<&Value>) -> Result<Value, String> {
1844 let compiled_logic = rlogic::compiled_logic_store::get_compiled_logic(logic_id)
1846 .ok_or_else(|| format!("Compiled logic ID {:?} not found in store", logic_id))?;
1847
1848 let eval_data_value = if let Some(input_data) = data {
1852 let context_value = context.unwrap_or(&self.context);
1853
1854 self.eval_data.replace_data_and_context(input_data.clone(), context_value.clone());
1855 self.eval_data.data()
1856 } else {
1857 self.eval_data.data()
1858 };
1859
1860 let evaluator = Evaluator::new();
1862 let result = evaluator.evaluate(&compiled_logic, &eval_data_value)?;
1863
1864 Ok(clean_float_noise(result))
1865 }
1866
1867 pub fn compile_and_run_logic(&mut self, logic_str: &str, data: Option<&str>, context: Option<&str>) -> Result<Value, String> {
1883 let compiled_logic = self.compile_logic(logic_str)?;
1885
1886 let data_value = if let Some(data_str) = data {
1888 Some(json_parser::parse_json_str(data_str)?)
1889 } else {
1890 None
1891 };
1892
1893 let context_value = if let Some(ctx_str) = context {
1894 Some(json_parser::parse_json_str(ctx_str)?)
1895 } else {
1896 None
1897 };
1898
1899 self.run_logic(compiled_logic, data_value.as_ref(), context_value.as_ref())
1901 }
1902
1903 pub fn resolve_layout(&mut self, evaluate: bool) -> Result<(), String> {
1913 if evaluate {
1914 let data_str = serde_json::to_string(&self.data)
1916 .map_err(|e| format!("Failed to serialize data: {}", e))?;
1917 self.evaluate(&data_str, None, None)?;
1918 }
1919
1920 self.resolve_layout_internal();
1921 Ok(())
1922 }
1923
1924 fn resolve_layout_internal(&mut self) {
1925 time_block!(" resolve_layout_internal()", {
1926 let layout_paths = self.layout_paths.clone();
1929
1930 time_block!(" resolve_layout_elements", {
1931 for layout_path in layout_paths.iter() {
1932 self.resolve_layout_elements(layout_path);
1933 }
1934 });
1935
1936 time_block!(" propagate_parent_conditions", {
1938 for layout_path in layout_paths.iter() {
1939 self.propagate_parent_conditions(layout_path);
1940 }
1941 });
1942 });
1943 }
1944
1945 fn propagate_parent_conditions(&mut self, layout_elements_path: &str) {
1947 let normalized_path = path_utils::normalize_to_json_pointer(layout_elements_path);
1949
1950 let elements = if let Some(Value::Array(arr)) = self.evaluated_schema.pointer_mut(&normalized_path) {
1952 mem::take(arr)
1953 } else {
1954 return;
1955 };
1956
1957 let mut updated_elements = Vec::with_capacity(elements.len());
1959 for element in elements {
1960 updated_elements.push(self.apply_parent_conditions(element, false, false));
1961 }
1962
1963 if let Some(target) = self.evaluated_schema.pointer_mut(&normalized_path) {
1965 *target = Value::Array(updated_elements);
1966 }
1967 }
1968
1969 fn apply_parent_conditions(&self, element: Value, parent_hidden: bool, parent_disabled: bool) -> Value {
1971 if let Value::Object(mut map) = element {
1972 let mut element_hidden = parent_hidden;
1974 let mut element_disabled = parent_disabled;
1975
1976 if let Some(Value::Object(condition)) = map.get("condition") {
1978 if let Some(Value::Bool(hidden)) = condition.get("hidden") {
1979 element_hidden = element_hidden || *hidden;
1980 }
1981 if let Some(Value::Bool(disabled)) = condition.get("disabled") {
1982 element_disabled = element_disabled || *disabled;
1983 }
1984 }
1985
1986 if let Some(Value::Object(hide_layout)) = map.get("hideLayout") {
1988 if let Some(Value::Bool(all_hidden)) = hide_layout.get("all") {
1990 if *all_hidden {
1991 element_hidden = true;
1992 }
1993 }
1994 }
1995
1996 if parent_hidden || parent_disabled {
1998 if map.contains_key("condition") || map.contains_key("$ref") || map.contains_key("$fullpath") {
2000 let mut condition = if let Some(Value::Object(c)) = map.get("condition") {
2001 c.clone()
2002 } else {
2003 serde_json::Map::new()
2004 };
2005
2006 if parent_hidden {
2007 condition.insert("hidden".to_string(), Value::Bool(true));
2008 }
2009 if parent_disabled {
2010 condition.insert("disabled".to_string(), Value::Bool(true));
2011 }
2012
2013 map.insert("condition".to_string(), Value::Object(condition));
2014 }
2015
2016 if parent_hidden && (map.contains_key("hideLayout") || map.contains_key("type")) {
2018 let mut hide_layout = if let Some(Value::Object(h)) = map.get("hideLayout") {
2019 h.clone()
2020 } else {
2021 serde_json::Map::new()
2022 };
2023
2024 hide_layout.insert("all".to_string(), Value::Bool(true));
2026 map.insert("hideLayout".to_string(), Value::Object(hide_layout));
2027 }
2028 }
2029
2030 if map.contains_key("$parentHide") {
2033 map.insert("$parentHide".to_string(), Value::Bool(parent_hidden));
2034 }
2035
2036 if let Some(Value::Array(elements)) = map.get("elements") {
2038 let mut updated_children = Vec::with_capacity(elements.len());
2039 for child in elements {
2040 updated_children.push(self.apply_parent_conditions(
2041 child.clone(),
2042 element_hidden,
2043 element_disabled,
2044 ));
2045 }
2046 map.insert("elements".to_string(), Value::Array(updated_children));
2047 }
2048
2049 return Value::Object(map);
2050 }
2051
2052 element
2053 }
2054
2055 fn resolve_layout_elements(&mut self, layout_elements_path: &str) {
2057 let normalized_path = path_utils::normalize_to_json_pointer(layout_elements_path);
2059
2060 let elements = if let Some(Value::Array(arr)) = self.schema.pointer(&normalized_path) {
2064 arr.clone()
2065 } else {
2066 return;
2067 };
2068
2069 let parent_path = normalized_path
2071 .trim_start_matches('/')
2072 .replace("/elements", "")
2073 .replace('/', ".");
2074
2075 let mut resolved_elements = Vec::with_capacity(elements.len());
2077 for (index, element) in elements.iter().enumerate() {
2078 let element_path = if parent_path.is_empty() {
2079 format!("elements.{}", index)
2080 } else {
2081 format!("{}.elements.{}", parent_path, index)
2082 };
2083 let resolved = self.resolve_element_ref_recursive(element.clone(), &element_path);
2084 resolved_elements.push(resolved);
2085 }
2086
2087 if let Some(target) = self.evaluated_schema.pointer_mut(&normalized_path) {
2089 *target = Value::Array(resolved_elements);
2090 }
2091 }
2092
2093 fn resolve_element_ref_recursive(&self, element: Value, path_context: &str) -> Value {
2096 let resolved = self.resolve_element_ref(element);
2098
2099 if let Value::Object(mut map) = resolved {
2101 if !map.contains_key("$parentHide") {
2105 map.insert("$parentHide".to_string(), Value::Bool(false));
2106 }
2107
2108 if !map.contains_key("$fullpath") {
2110 map.insert("$fullpath".to_string(), Value::String(path_context.to_string()));
2111 }
2112
2113 if !map.contains_key("$path") {
2114 let last_segment = path_context.split('.').last().unwrap_or(path_context);
2116 map.insert("$path".to_string(), Value::String(last_segment.to_string()));
2117 }
2118
2119 if let Some(Value::Array(elements)) = map.get("elements") {
2121 let mut resolved_nested = Vec::with_capacity(elements.len());
2122 for (index, nested_element) in elements.iter().enumerate() {
2123 let nested_path = format!("{}.elements.{}", path_context, index);
2124 resolved_nested.push(self.resolve_element_ref_recursive(nested_element.clone(), &nested_path));
2125 }
2126 map.insert("elements".to_string(), Value::Array(resolved_nested));
2127 }
2128
2129 return Value::Object(map);
2130 }
2131
2132 resolved
2133 }
2134
2135 fn resolve_element_ref(&self, element: Value) -> Value {
2137 match element {
2138 Value::Object(mut map) => {
2139 if let Some(Value::String(ref_path)) = map.get("$ref").cloned() {
2141 let dotted_path = path_utils::pointer_to_dot_notation(&ref_path);
2143
2144 let last_segment = dotted_path.split('.').last().unwrap_or(&dotted_path);
2146
2147 map.insert("$fullpath".to_string(), Value::String(dotted_path.clone()));
2149 map.insert("$path".to_string(), Value::String(last_segment.to_string()));
2150 map.insert("$parentHide".to_string(), Value::Bool(false));
2151
2152 let normalized_path = if ref_path.starts_with('#') || ref_path.starts_with('/') {
2155 path_utils::normalize_to_json_pointer(&ref_path)
2157 } else {
2158 let schema_pointer = path_utils::dot_notation_to_schema_pointer(&ref_path);
2160 let schema_path = path_utils::normalize_to_json_pointer(&schema_pointer);
2161
2162 if self.evaluated_schema.pointer(&schema_path).is_some() {
2164 schema_path
2165 } else {
2166 let with_properties = format!("/properties/{}", ref_path.replace('.', "/properties/"));
2168 with_properties
2169 }
2170 };
2171
2172 if let Some(referenced_value) = self.evaluated_schema.pointer(&normalized_path) {
2174 let resolved = referenced_value.clone();
2176
2177 if let Value::Object(mut resolved_map) = resolved {
2179 map.remove("$ref");
2181
2182 if let Some(Value::Object(layout_obj)) = resolved_map.remove("$layout") {
2185 let mut result = layout_obj.clone();
2187
2188 resolved_map.remove("properties");
2190
2191 for (key, value) in resolved_map {
2193 if key != "type" || !result.contains_key("type") {
2194 result.insert(key, value);
2195 }
2196 }
2197
2198 for (key, value) in map {
2200 result.insert(key, value);
2201 }
2202
2203 return Value::Object(result);
2204 } else {
2205 for (key, value) in map {
2207 resolved_map.insert(key, value);
2208 }
2209
2210 return Value::Object(resolved_map);
2211 }
2212 } else {
2213 return resolved;
2215 }
2216 }
2217 }
2218
2219 Value::Object(map)
2221 }
2222 _ => element,
2223 }
2224 }
2225
2226 pub fn evaluate_dependents(
2235 &mut self,
2236 changed_paths: &[String],
2237 data: Option<&str>,
2238 context: Option<&str>,
2239 re_evaluate: bool,
2240 ) -> Result<Value, String> {
2241 let _lock = self.eval_lock.lock().unwrap();
2243
2244 if let Some(data_str) = data {
2246 let old_data = self.eval_data.clone_data_without(&["$params"]);
2248
2249 let data_value = json_parser::parse_json_str(data_str)?;
2250 let context_value = if let Some(ctx) = context {
2251 json_parser::parse_json_str(ctx)?
2252 } else {
2253 Value::Object(serde_json::Map::new())
2254 };
2255 self.eval_data.replace_data_and_context(data_value.clone(), context_value);
2256
2257 let data_paths: Vec<String> = changed_paths
2261 .iter()
2262 .map(|path| {
2263 let schema_ptr = path_utils::dot_notation_to_schema_pointer(path);
2266
2267 let normalized = schema_ptr.trim_start_matches('#')
2269 .replace("/properties/", "/");
2270
2271 if normalized.starts_with('/') {
2273 normalized
2274 } else {
2275 format!("/{}", normalized)
2276 }
2277 })
2278 .collect();
2279 self.purge_cache_for_changed_data_with_comparison(&data_paths, &old_data, &data_value);
2280 }
2281
2282 let mut result = Vec::new();
2283 let mut processed = IndexSet::new();
2284
2285 let mut to_process: Vec<(String, bool)> = changed_paths
2288 .iter()
2289 .map(|path| (path_utils::dot_notation_to_schema_pointer(path), false))
2290 .collect(); while let Some((current_path, is_transitive)) = to_process.pop() {
2294 if processed.contains(¤t_path) {
2295 continue;
2296 }
2297 processed.insert(current_path.clone());
2298
2299 let current_data_path = path_utils::normalize_to_json_pointer(¤t_path)
2301 .replace("/properties/", "/")
2302 .trim_start_matches('#')
2303 .to_string();
2304 let mut current_value = self.eval_data.data().pointer(¤t_data_path)
2305 .cloned()
2306 .unwrap_or(Value::Null);
2307
2308 if let Some(dependent_items) = self.dependents_evaluations.get(¤t_path) {
2310 for dep_item in dependent_items {
2311 let ref_path = &dep_item.ref_path;
2312 let pointer_path = path_utils::normalize_to_json_pointer(ref_path);
2313 let data_path = pointer_path.replace("/properties/", "/");
2315
2316 let current_ref_value = self.eval_data.data().pointer(&data_path)
2317 .cloned()
2318 .unwrap_or(Value::Null);
2319
2320 let field = self.evaluated_schema.pointer(&pointer_path).cloned();
2322
2323 let parent_path = if let Some(last_slash) = pointer_path.rfind("/properties") {
2325 &pointer_path[..last_slash]
2326 } else {
2327 "/"
2328 };
2329 let mut parent_field = if parent_path.is_empty() || parent_path == "/" {
2330 self.evaluated_schema.clone()
2331 } else {
2332 self.evaluated_schema.pointer(parent_path).cloned()
2333 .unwrap_or_else(|| Value::Object(serde_json::Map::new()))
2334 };
2335
2336 if let Value::Object(ref mut map) = parent_field {
2338 map.remove("properties");
2339 map.remove("$layout");
2340 }
2341
2342 let mut change_obj = serde_json::Map::new();
2343 change_obj.insert("$ref".to_string(), Value::String(path_utils::pointer_to_dot_notation(&data_path)));
2344 if let Some(f) = field {
2345 change_obj.insert("$field".to_string(), f);
2346 }
2347 change_obj.insert("$parentField".to_string(), parent_field);
2348 change_obj.insert("transitive".to_string(), Value::Bool(is_transitive));
2349
2350 let mut add_transitive = false;
2351 let mut add_deps = false;
2352 if let Some(clear_val) = &dep_item.clear {
2354 let clear_val_clone = clear_val.clone();
2355 let should_clear = Self::evaluate_dependent_value_static(&self.engine, &self.evaluations, &self.eval_data, &clear_val_clone, ¤t_value, ¤t_ref_value)?;
2356 let clear_bool = match should_clear {
2357 Value::Bool(b) => b,
2358 _ => false,
2359 };
2360
2361 if clear_bool {
2362 if data_path == current_data_path {
2364 current_value = Value::Null;
2365 }
2366 self.eval_data.set(&data_path, Value::Null);
2367 change_obj.insert("clear".to_string(), Value::Bool(true));
2368 add_transitive = true;
2369 add_deps = true;
2370 }
2371 }
2372
2373 if let Some(value_val) = &dep_item.value {
2375 let value_val_clone = value_val.clone();
2376 let computed_value = Self::evaluate_dependent_value_static(&self.engine, &self.evaluations, &self.eval_data, &value_val_clone, ¤t_value, ¤t_ref_value)?;
2377 let cleaned_val = clean_float_noise(computed_value.clone());
2378
2379 if cleaned_val != current_ref_value && cleaned_val != Value::Null {
2380 if data_path == current_data_path {
2382 current_value = cleaned_val.clone();
2383 }
2384 self.eval_data.set(&data_path, cleaned_val.clone());
2385 change_obj.insert("value".to_string(), cleaned_val);
2386 add_transitive = true;
2387 add_deps = true;
2388 }
2389 }
2390
2391 if add_deps {
2393 result.push(Value::Object(change_obj));
2394 }
2395
2396 if add_transitive {
2398 to_process.push((ref_path.clone(), true));
2399 }
2400 }
2401 }
2402 }
2403
2404 if re_evaluate {
2408 drop(_lock); self.evaluate_internal(None)?;
2410 }
2411
2412 Ok(Value::Array(result))
2413 }
2414
2415 fn evaluate_dependent_value_static(
2417 engine: &RLogic,
2418 evaluations: &IndexMap<String, LogicId>,
2419 eval_data: &EvalData,
2420 value: &Value,
2421 changed_field_value: &Value,
2422 changed_field_ref_value: &Value
2423 ) -> Result<Value, String> {
2424 match value {
2425 Value::String(eval_key) => {
2427 if let Some(logic_id) = evaluations.get(eval_key) {
2428 let mut internal_context = serde_json::Map::new();
2431 internal_context.insert("$value".to_string(), changed_field_value.clone());
2432 internal_context.insert("$refValue".to_string(), changed_field_ref_value.clone());
2433 let context_value = Value::Object(internal_context);
2434
2435 let result = engine.run_with_context(logic_id, eval_data.data(), &context_value)
2436 .map_err(|e| format!("Failed to evaluate dependent logic '{}': {}", eval_key, e))?;
2437 Ok(result)
2438 } else {
2439 Ok(value.clone())
2441 }
2442 }
2443 Value::Object(map) if map.contains_key("$evaluation") => {
2446 Err("Dependent evaluation contains unparsed $evaluation - schema was not properly parsed".to_string())
2447 }
2448 _ => Ok(value.clone()),
2450 }
2451 }
2452
2453 pub fn validate(
2456 &mut self,
2457 data: &str,
2458 context: Option<&str>,
2459 paths: Option<&[String]>
2460 ) -> Result<ValidationResult, String> {
2461 let _lock = self.eval_lock.lock().unwrap();
2463
2464 let old_data = self.eval_data.clone_data_without(&["$params"]);
2466
2467 let data_value = json_parser::parse_json_str(data)?;
2469 let context_value = if let Some(ctx) = context {
2470 json_parser::parse_json_str(ctx)?
2471 } else {
2472 Value::Object(serde_json::Map::new())
2473 };
2474
2475 self.eval_data.replace_data_and_context(data_value.clone(), context_value);
2477
2478 let changed_data_paths: Vec<String> = if let Some(obj) = data_value.as_object() {
2481 obj.keys().map(|k| format!("/{}", k)).collect()
2482 } else {
2483 Vec::new()
2484 };
2485 self.purge_cache_for_changed_data_with_comparison(&changed_data_paths, &old_data, &data_value);
2486
2487 drop(_lock);
2489
2490 self.evaluate_others(paths);
2495
2496 self.evaluated_schema = self.get_evaluated_schema(false);
2498
2499 let mut errors: IndexMap<String, ValidationError> = IndexMap::new();
2500
2501 for field_path in self.fields_with_rules.iter() {
2504 if let Some(filter_paths) = paths {
2506 if !filter_paths.is_empty() && !filter_paths.iter().any(|p| field_path.starts_with(p.as_str()) || p.starts_with(field_path.as_str())) {
2507 continue;
2508 }
2509 }
2510
2511 self.validate_field(field_path, &data_value, &mut errors);
2512 }
2513
2514 let has_error = !errors.is_empty();
2515
2516 Ok(ValidationResult {
2517 has_error,
2518 errors,
2519 })
2520 }
2521
2522 fn validate_field(
2524 &self,
2525 field_path: &str,
2526 data: &Value,
2527 errors: &mut IndexMap<String, ValidationError>
2528 ) {
2529 if errors.contains_key(field_path) {
2531 return;
2532 }
2533
2534 let schema_path = path_utils::dot_notation_to_schema_pointer(field_path);
2536
2537 let pointer_path = schema_path.trim_start_matches('#');
2539
2540 let field_schema = match self.evaluated_schema.pointer(pointer_path) {
2542 Some(s) => s,
2543 None => {
2544 let alt_path = format!("/properties{}", pointer_path);
2546 match self.evaluated_schema.pointer(&alt_path) {
2547 Some(s) => s,
2548 None => return,
2549 }
2550 }
2551 };
2552
2553 if let Value::Object(schema_map) = field_schema {
2555 if let Some(Value::Object(condition)) = schema_map.get("condition") {
2556 if let Some(Value::Bool(true)) = condition.get("hidden") {
2557 return;
2558 }
2559 }
2560
2561 let rules = match schema_map.get("rules") {
2563 Some(Value::Object(r)) => r,
2564 _ => return,
2565 };
2566
2567 let field_data = self.get_field_data(field_path, data);
2569
2570 for (rule_name, rule_value) in rules {
2572 self.validate_rule(
2573 field_path,
2574 rule_name,
2575 rule_value,
2576 &field_data,
2577 schema_map,
2578 field_schema,
2579 errors
2580 );
2581 }
2582 }
2583 }
2584
2585 fn get_field_data(&self, field_path: &str, data: &Value) -> Value {
2587 let parts: Vec<&str> = field_path.split('.').collect();
2588 let mut current = data;
2589
2590 for part in parts {
2591 match current {
2592 Value::Object(map) => {
2593 current = map.get(part).unwrap_or(&Value::Null);
2594 }
2595 _ => return Value::Null,
2596 }
2597 }
2598
2599 current.clone()
2600 }
2601
2602 fn validate_rule(
2604 &self,
2605 field_path: &str,
2606 rule_name: &str,
2607 rule_value: &Value,
2608 field_data: &Value,
2609 schema_map: &serde_json::Map<String, Value>,
2610 _schema: &Value,
2611 errors: &mut IndexMap<String, ValidationError>
2612 ) {
2613 if errors.contains_key(field_path) {
2615 return;
2616 }
2617
2618 let mut disabled_field = false;
2619 if let Some(Value::Object(condition)) = schema_map.get("condition") {
2621 if let Some(Value::Bool(true)) = condition.get("disabled") {
2622 disabled_field = true;
2623 }
2624 }
2625
2626 let schema_path = path_utils::dot_notation_to_schema_pointer(field_path);
2629 let rule_path = format!("{}/rules/{}", schema_path.trim_start_matches('#'), rule_name);
2630
2631 let evaluated_rule = if let Some(eval_rule) = self.evaluated_schema.pointer(&rule_path) {
2633 eval_rule.clone()
2634 } else {
2635 rule_value.clone()
2636 };
2637
2638 let (rule_active, rule_message, rule_code, rule_data) = match &evaluated_rule {
2640 Value::Object(rule_obj) => {
2641 let active = rule_obj.get("value").unwrap_or(&Value::Bool(false));
2642
2643 let message = match rule_obj.get("message") {
2645 Some(Value::String(s)) => s.clone(),
2646 Some(Value::Object(msg_obj)) if msg_obj.contains_key("value") => {
2647 msg_obj.get("value")
2648 .and_then(|v| v.as_str())
2649 .unwrap_or("Validation failed")
2650 .to_string()
2651 }
2652 Some(msg_val) => msg_val.as_str().unwrap_or("Validation failed").to_string(),
2653 None => "Validation failed".to_string()
2654 };
2655
2656 let code = rule_obj.get("code")
2657 .and_then(|c| c.as_str())
2658 .map(|s| s.to_string());
2659
2660 let data = rule_obj.get("data").map(|d| {
2662 if let Value::Object(data_obj) = d {
2663 let mut cleaned_data = serde_json::Map::new();
2664 for (key, value) in data_obj {
2665 if let Value::Object(val_obj) = value {
2667 if val_obj.len() == 1 && val_obj.contains_key("value") {
2668 cleaned_data.insert(key.clone(), val_obj["value"].clone());
2669 } else {
2670 cleaned_data.insert(key.clone(), value.clone());
2671 }
2672 } else {
2673 cleaned_data.insert(key.clone(), value.clone());
2674 }
2675 }
2676 Value::Object(cleaned_data)
2677 } else {
2678 d.clone()
2679 }
2680 });
2681
2682 (active.clone(), message, code, data)
2683 }
2684 _ => (evaluated_rule.clone(), "Validation failed".to_string(), None, None)
2685 };
2686
2687 let error_code = rule_code.or_else(|| Some(format!("{}.{}", field_path, rule_name)));
2689
2690 let is_empty = matches!(field_data, Value::Null) ||
2691 (field_data.is_string() && field_data.as_str().unwrap_or("").is_empty()) ||
2692 (field_data.is_array() && field_data.as_array().unwrap().is_empty());
2693
2694 match rule_name {
2695 "required" => {
2696 if !disabled_field && rule_active == Value::Bool(true) {
2697 if is_empty {
2698 errors.insert(field_path.to_string(), ValidationError {
2699 rule_type: "required".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 "minLength" => {
2710 if !is_empty {
2711 if let Some(min) = rule_active.as_u64() {
2712 let len = match field_data {
2713 Value::String(s) => s.len(),
2714 Value::Array(a) => a.len(),
2715 _ => 0
2716 };
2717 if len < min as usize {
2718 errors.insert(field_path.to_string(), ValidationError {
2719 rule_type: "minLength".to_string(),
2720 message: rule_message,
2721 code: error_code.clone(),
2722 pattern: None,
2723 field_value: None,
2724 data: None,
2725 });
2726 }
2727 }
2728 }
2729 }
2730 "maxLength" => {
2731 if !is_empty {
2732 if let Some(max) = rule_active.as_u64() {
2733 let len = match field_data {
2734 Value::String(s) => s.len(),
2735 Value::Array(a) => a.len(),
2736 _ => 0
2737 };
2738 if len > max as usize {
2739 errors.insert(field_path.to_string(), ValidationError {
2740 rule_type: "maxLength".to_string(),
2741 message: rule_message,
2742 code: error_code.clone(),
2743 pattern: None,
2744 field_value: None,
2745 data: None,
2746 });
2747 }
2748 }
2749 }
2750 }
2751 "minValue" => {
2752 if !is_empty {
2753 if let Some(min) = rule_active.as_f64() {
2754 if let Some(val) = field_data.as_f64() {
2755 if val < min {
2756 errors.insert(field_path.to_string(), ValidationError {
2757 rule_type: "minValue".to_string(),
2758 message: rule_message,
2759 code: error_code.clone(),
2760 pattern: None,
2761 field_value: None,
2762 data: None,
2763 });
2764 }
2765 }
2766 }
2767 }
2768 }
2769 "maxValue" => {
2770 if !is_empty {
2771 if let Some(max) = rule_active.as_f64() {
2772 if let Some(val) = field_data.as_f64() {
2773 if val > max {
2774 errors.insert(field_path.to_string(), ValidationError {
2775 rule_type: "maxValue".to_string(),
2776 message: rule_message,
2777 code: error_code.clone(),
2778 pattern: None,
2779 field_value: None,
2780 data: None,
2781 });
2782 }
2783 }
2784 }
2785 }
2786 }
2787 "pattern" => {
2788 if !is_empty {
2789 if let Some(pattern) = rule_active.as_str() {
2790 if let Some(text) = field_data.as_str() {
2791 if let Ok(regex) = regex::Regex::new(pattern) {
2792 if !regex.is_match(text) {
2793 errors.insert(field_path.to_string(), ValidationError {
2794 rule_type: "pattern".to_string(),
2795 message: rule_message,
2796 code: error_code.clone(),
2797 pattern: Some(pattern.to_string()),
2798 field_value: Some(text.to_string()),
2799 data: None,
2800 });
2801 }
2802 }
2803 }
2804 }
2805 }
2806 }
2807 "evaluation" => {
2808 if let Value::Array(eval_array) = &evaluated_rule {
2811 for (idx, eval_item) in eval_array.iter().enumerate() {
2812 if let Value::Object(eval_obj) = eval_item {
2813 let eval_result = eval_obj.get("value").unwrap_or(&Value::Bool(true));
2815
2816 let is_falsy = match eval_result {
2818 Value::Bool(false) => true,
2819 Value::Null => true,
2820 Value::Number(n) => n.as_f64() == Some(0.0),
2821 Value::String(s) => s.is_empty(),
2822 Value::Array(a) => a.is_empty(),
2823 _ => false,
2824 };
2825
2826 if is_falsy {
2827 let eval_code = eval_obj.get("code")
2828 .and_then(|c| c.as_str())
2829 .map(|s| s.to_string())
2830 .or_else(|| Some(format!("{}.evaluation.{}", field_path, idx)));
2831
2832 let eval_message = eval_obj.get("message")
2833 .and_then(|m| m.as_str())
2834 .unwrap_or("Validation failed")
2835 .to_string();
2836
2837 let eval_data = eval_obj.get("data").cloned();
2838
2839 errors.insert(field_path.to_string(), ValidationError {
2840 rule_type: "evaluation".to_string(),
2841 message: eval_message,
2842 code: eval_code,
2843 pattern: None,
2844 field_value: None,
2845 data: eval_data,
2846 });
2847
2848 break;
2850 }
2851 }
2852 }
2853 }
2854 }
2855 _ => {
2856 if !is_empty {
2860 let is_falsy = match &rule_active {
2862 Value::Bool(false) => true,
2863 Value::Null => true,
2864 Value::Number(n) => n.as_f64() == Some(0.0),
2865 Value::String(s) => s.is_empty(),
2866 Value::Array(a) => a.is_empty(),
2867 _ => false,
2868 };
2869
2870 if is_falsy {
2871 errors.insert(field_path.to_string(), ValidationError {
2872 rule_type: "evaluation".to_string(),
2873 message: rule_message,
2874 code: error_code.clone(),
2875 pattern: None,
2876 field_value: None,
2877 data: rule_data,
2878 });
2879 }
2880 }
2881 }
2882 }
2883 }
2884}
2885
2886#[derive(Debug, Clone, Serialize, Deserialize)]
2888pub struct ValidationError {
2889 #[serde(rename = "type")]
2890 pub rule_type: String,
2891 pub message: String,
2892 #[serde(skip_serializing_if = "Option::is_none")]
2893 pub code: Option<String>,
2894 #[serde(skip_serializing_if = "Option::is_none")]
2895 pub pattern: Option<String>,
2896 #[serde(skip_serializing_if = "Option::is_none")]
2897 pub field_value: Option<String>,
2898 #[serde(skip_serializing_if = "Option::is_none")]
2899 pub data: Option<Value>,
2900}
2901
2902#[derive(Debug, Clone, Serialize, Deserialize)]
2904pub struct ValidationResult {
2905 pub has_error: bool,
2906 pub errors: IndexMap<String, ValidationError>,
2907}
2908