jsonschema_rs 0.61.2 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/src/evaluation.rs CHANGED
@@ -4,10 +4,7 @@
4
4
  use jsonschema::{output::ErrorDescription, OutputUnit};
5
5
  use magnus::{method, prelude::*, Error, RArray, RHash, RModule, Ruby, Value};
6
6
 
7
- use crate::{
8
- ser::{serialize_to_ruby, value_to_ruby},
9
- static_id::define_rb_intern,
10
- };
7
+ use crate::{ser::value_to_ruby, static_id::define_rb_intern};
11
8
 
12
9
  define_rb_intern!(static ID_SCHEMA_LOCATION: "schemaLocation");
13
10
  define_rb_intern!(static ID_ABSOLUTE_KEYWORD_LOCATION: "absoluteKeywordLocation");
@@ -111,7 +108,7 @@ impl Evaluation {
111
108
  // Builds an output unit straight into a Ruby Hash, with the keys and order the serialized
112
109
  // output has.
113
110
  fn unit_to_ruby(ruby: &Ruby, unit: OutputUnit<'_>, nested: bool) -> Result<RHash, Error> {
114
- // Key-value pairs inserted with one call, the order the serialized output has.
111
+ // Inserted with one `bulk_insert` call.
115
112
  let mut pairs = [ruby.qnil().as_value(); 16];
116
113
  let mut len = 0;
117
114
  let mut push = |key: Value, value: Value| {
@@ -138,13 +135,13 @@ fn unit_to_ruby(ruby: &Ruby, unit: OutputUnit<'_>, nested: bool) -> Result<RHash
138
135
  if let Some(annotations) = unit.annotations() {
139
136
  push(
140
137
  ID_ANNOTATIONS.to_symbol().as_value(),
141
- serialize_to_ruby(ruby, annotations)?,
138
+ value_to_ruby(ruby, annotations.value())?,
142
139
  );
143
140
  }
144
141
  if let Some(annotations) = unit.dropped_annotations() {
145
142
  push(
146
143
  ID_DROPPED_ANNOTATIONS.to_symbol().as_value(),
147
- serialize_to_ruby(ruby, annotations)?,
144
+ value_to_ruby(ruby, annotations.value())?,
148
145
  );
149
146
  }
150
147
  if !unit.errors().is_empty() {
@@ -179,7 +176,6 @@ fn list_units(ruby: &Ruby, unit: OutputUnit<'_>, out: RArray) -> Result<(), Erro
179
176
  /// Messages grouped by keyword in first-seen order: one message as a String, several as an Array.
180
177
  fn errors_to_ruby(ruby: &Ruby, errors: &[ErrorDescription]) -> Result<RHash, Error> {
181
178
  let hash = ruby.hash_new();
182
- // ponytail: quadratic in a unit's errors, which hold about one per keyword.
183
179
  for (index, error) in errors.iter().enumerate() {
184
180
  let keyword = error.keyword();
185
181
  if errors[..index].iter().any(|seen| seen.keyword() == keyword) {
data/src/json_text.rs ADDED
@@ -0,0 +1,239 @@
1
+ //! `JSONSchema::JsonTextValidator`: validates instances given as JSON text.
2
+ use std::panic::AssertUnwindSafe;
3
+
4
+ use jsonschema::json::{Array, JsonNumber, JsonText, JsonTextDocument, JsonTextNode, Node, Object};
5
+ use magnus::{
6
+ function, method, prelude::*, scan_args::scan_args, DataTypeFunctions, Error, RModule, RString,
7
+ Ruby, Value,
8
+ };
9
+
10
+ use crate::{
11
+ build_parsed_options, build_validator, catch_unwind_silent, handle_callback_panic,
12
+ options::{extract_kwargs, CallbackRoots, CompilationRootsRef},
13
+ raise_validation_error,
14
+ ser::to_schema_value,
15
+ to_ruby_error_value, BuiltValidator, Evaluation, InstanceRoot, KeywordCauseScope,
16
+ };
17
+
18
+ /// A validator for instances given as JSON text, without building Ruby objects for them.
19
+ ///
20
+ /// Holds the same GC-protection state as `Validator`.
21
+ #[derive(magnus::TypedData)]
22
+ #[magnus(class = "JSONSchema::JsonTextValidator", free_immediately, size, mark)]
23
+ pub struct JsonTextValidator {
24
+ validator: jsonschema::Validator<JsonText>,
25
+ mask: Option<String>,
26
+ callback_roots: CallbackRoots,
27
+ _compilation_roots: CompilationRootsRef,
28
+ }
29
+
30
+ impl DataTypeFunctions for JsonTextValidator {
31
+ fn mark(&self, marker: &magnus::gc::Marker) {
32
+ // Avoid panicking in Ruby GC mark paths; preserving existing roots is safer than aborting.
33
+ let roots = match self.callback_roots.lock() {
34
+ Ok(roots) => roots,
35
+ Err(poisoned) => poisoned.into_inner(),
36
+ };
37
+ for root in roots.iter().copied() {
38
+ marker.mark(root);
39
+ }
40
+ }
41
+ }
42
+
43
+ // Copied so Ruby code that validation runs cannot change the text under it.
44
+ fn json_text(ruby: &Ruby, instance: Value) -> Result<Vec<u8>, Error> {
45
+ let Some(mut string) = RString::from_value(instance) else {
46
+ return Err(Error::new(
47
+ ruby.exception_type_error(),
48
+ format!(
49
+ "JSON text must be a String, not {}",
50
+ instance.class().inspect()
51
+ ),
52
+ ));
53
+ };
54
+ // As `JSON.parse` does: binary strings are read as UTF-8, other encodings converted to it.
55
+ let encoding = string.enc_get();
56
+ if encoding != ruby.utf8_encindex()
57
+ && encoding != ruby.usascii_encindex()
58
+ && encoding != ruby.ascii8bit_encindex()
59
+ {
60
+ string = string.funcall("encode", ("UTF-8",))?;
61
+ }
62
+ // SAFETY: the bytes are copied before any Ruby code runs.
63
+ #[allow(unsafe_code)]
64
+ let bytes = unsafe { string.as_slice() }.to_vec();
65
+ Ok(bytes)
66
+ }
67
+
68
+ fn parse<'a>(ruby: &Ruby, text: &'a [u8]) -> Result<JsonTextDocument<'a>, Error> {
69
+ JsonText::parse(text)
70
+ .map_err(|error| Error::new(ruby.exception_arg_error(), format!("Invalid JSON: {error}")))
71
+ }
72
+
73
+ /// What `JSON.parse` builds: members in document order, `Integer` for integers, `Float` otherwise.
74
+ pub(crate) fn text_node_to_ruby(ruby: &Ruby, node: &JsonTextNode<'_>) -> Result<Value, Error> {
75
+ if let Some(object) = node.as_object() {
76
+ let hash = ruby.hash_new();
77
+ for (name, value) in object.members() {
78
+ hash.aset(ruby.str_new(&name), text_node_to_ruby(ruby, &value)?)?;
79
+ }
80
+ return Ok(hash.as_value());
81
+ }
82
+ if let Some(array) = node.as_array() {
83
+ let list = ruby.ary_new_capa(array.len());
84
+ for element in array.elements() {
85
+ list.push(text_node_to_ruby(ruby, &element)?)?;
86
+ }
87
+ return Ok(list.as_value());
88
+ }
89
+ if let Some(string) = node.as_string() {
90
+ return Ok(ruby.str_new(&string).as_value());
91
+ }
92
+ if let Some(number) = node.as_number() {
93
+ if let Some(value) = number.as_i64() {
94
+ return Ok(ruby.integer_from_i64(value).as_value());
95
+ }
96
+ let digits = JsonNumber::as_str(&number);
97
+ if digits.contains(['.', 'e', 'E']) {
98
+ // Past `f64` this is infinite, as with `JSON.parse`.
99
+ let value: f64 = digits.parse().expect("a checked number");
100
+ return Ok(ruby.float_from_f64(value).as_value());
101
+ }
102
+ return ruby.str_new(&digits).funcall("to_i", ());
103
+ }
104
+ Ok(match node.as_boolean() {
105
+ Some(true) => ruby.qtrue().as_value(),
106
+ Some(false) => ruby.qfalse().as_value(),
107
+ None => ruby.qnil().as_value(),
108
+ })
109
+ }
110
+
111
+ impl JsonTextValidator {
112
+ fn new_impl(ruby: &Ruby, args: &[Value]) -> Result<Self, Error> {
113
+ let parsed_args = scan_args::<(Value,), (), (), (), _, ()>(args)?;
114
+ let (schema,) = parsed_args.required;
115
+ let kw = extract_kwargs(ruby, parsed_args.keywords)?;
116
+ let json_schema = to_schema_value(ruby, schema)?;
117
+ let parsed = build_parsed_options::<JsonText>(ruby, kw, None)?;
118
+ let BuiltValidator {
119
+ validator,
120
+ callback_roots,
121
+ compilation_roots,
122
+ } = build_validator(
123
+ ruby,
124
+ parsed.options,
125
+ parsed.registry,
126
+ parsed.retriever,
127
+ parsed.callback_roots,
128
+ parsed.compilation_roots,
129
+ &json_schema,
130
+ )?;
131
+ Ok(Self {
132
+ validator,
133
+ mask: parsed.mask,
134
+ callback_roots,
135
+ _compilation_roots: compilation_roots,
136
+ })
137
+ }
138
+
139
+ fn is_valid(ruby: &Ruby, rb_self: &Self, instance: Value) -> Result<bool, Error> {
140
+ let text = json_text(ruby, instance)?;
141
+ let document = parse(ruby, &text)?;
142
+ catch_unwind_silent(AssertUnwindSafe(|| {
143
+ rb_self.validator.is_valid(document.root())
144
+ }))
145
+ .map_err(|err| handle_callback_panic(ruby, err))
146
+ }
147
+
148
+ fn validate(ruby: &Ruby, rb_self: &Self, instance: Value) -> Result<(), Error> {
149
+ let text = json_text(ruby, instance)?;
150
+ let document = parse(ruby, &text)?;
151
+ let _scope = KeywordCauseScope::enter();
152
+ match catch_unwind_silent(AssertUnwindSafe(|| {
153
+ rb_self.validator.validate(document.root())
154
+ })) {
155
+ Ok(Ok(())) => Ok(()),
156
+ Ok(Err(error)) => Err(raise_validation_error(
157
+ ruby,
158
+ error,
159
+ Some(InstanceRoot::Text(document.root())),
160
+ rb_self.mask.as_deref(),
161
+ )),
162
+ Err(err) => Err(handle_callback_panic(ruby, err)),
163
+ }
164
+ }
165
+
166
+ fn iter_errors(ruby: &Ruby, rb_self: &Self, instance: Value) -> Result<Value, Error> {
167
+ let text = json_text(ruby, instance)?;
168
+ let document = parse(ruby, &text)?;
169
+ let _scope = KeywordCauseScope::enter();
170
+ let convert = |error| {
171
+ to_ruby_error_value(
172
+ ruby,
173
+ error,
174
+ Some(InstanceRoot::Text(document.root())),
175
+ rb_self.mask.as_deref(),
176
+ )
177
+ };
178
+ if ruby.block_given() {
179
+ // Building the iterator validates, which can run Ruby callbacks.
180
+ let mut errors = catch_unwind_silent(AssertUnwindSafe(|| {
181
+ rb_self.validator.iter_errors(document.root())
182
+ }))
183
+ .map_err(|err| handle_callback_panic(ruby, err))?;
184
+ loop {
185
+ match catch_unwind_silent(AssertUnwindSafe(|| errors.next())) {
186
+ Ok(Some(error)) => {
187
+ ruby.yield_value::<Value, Value>(convert(error)?)?;
188
+ }
189
+ Ok(None) => return Ok(ruby.qnil().as_value()),
190
+ Err(err) => return Err(handle_callback_panic(ruby, err)),
191
+ }
192
+ }
193
+ }
194
+ let errors = catch_unwind_silent(AssertUnwindSafe(|| {
195
+ rb_self
196
+ .validator
197
+ .iter_errors(document.root())
198
+ .collect::<Vec<_>>()
199
+ }))
200
+ .map_err(|err| handle_callback_panic(ruby, err))?;
201
+ let array = ruby.ary_new_capa(errors.len());
202
+ for error in errors {
203
+ array.push(convert(error)?)?;
204
+ }
205
+ Ok(array.as_value())
206
+ }
207
+
208
+ fn evaluate(ruby: &Ruby, rb_self: &Self, instance: Value) -> Result<Evaluation, Error> {
209
+ let text = json_text(ruby, instance)?;
210
+ let document = parse(ruby, &text)?;
211
+ let _scope = KeywordCauseScope::enter();
212
+ catch_unwind_silent(AssertUnwindSafe(|| {
213
+ rb_self.validator.evaluate(document.root())
214
+ }))
215
+ .map(Evaluation::new)
216
+ .map_err(|err| handle_callback_panic(ruby, err))
217
+ }
218
+
219
+ fn inspect(&self) -> &'static str {
220
+ match self.validator.draft() {
221
+ jsonschema::Draft::Draft4 => "#<JSONSchema::JsonTextValidator: Draft4>",
222
+ jsonschema::Draft::Draft6 => "#<JSONSchema::JsonTextValidator: Draft6>",
223
+ jsonschema::Draft::Draft7 => "#<JSONSchema::JsonTextValidator: Draft7>",
224
+ jsonschema::Draft::Draft201909 => "#<JSONSchema::JsonTextValidator: Draft201909>",
225
+ _ => "#<JSONSchema::JsonTextValidator: Draft202012>",
226
+ }
227
+ }
228
+ }
229
+
230
+ pub fn define_class(ruby: &Ruby, module: &RModule) -> Result<(), Error> {
231
+ let class = module.define_class("JsonTextValidator", ruby.class_object())?;
232
+ class.define_singleton_method("new", function!(JsonTextValidator::new_impl, -1))?;
233
+ class.define_method("valid?", method!(JsonTextValidator::is_valid, 1))?;
234
+ class.define_method("validate!", method!(JsonTextValidator::validate, 1))?;
235
+ class.define_method("each_error", method!(JsonTextValidator::iter_errors, 1))?;
236
+ class.define_method("evaluate", method!(JsonTextValidator::evaluate, 1))?;
237
+ class.define_method("inspect", method!(JsonTextValidator::inspect, 0))?;
238
+ Ok(())
239
+ }