jsonschema_rs 0.62.0 → 0.63.1
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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +28 -1
- data/Cargo.toml +2 -2
- data/README.md +30 -0
- data/ext/jsonschema/Cargo.lock +324 -354
- data/ext/jsonschema/Cargo.toml +3 -3
- data/lib/jsonschema/version.rb +1 -1
- data/sig/jsonschema.rbs +54 -7
- data/src/json_text.rs +239 -0
- data/src/lib.rs +102 -35
- data/src/options.rs +177 -34
- data/src/ser.rs +1 -1
- metadata +3 -2
data/ext/jsonschema/Cargo.toml
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "jsonschema-rb-ext"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.63.1"
|
|
4
4
|
edition = "2021"
|
|
5
5
|
publish = false
|
|
6
6
|
|
|
@@ -10,10 +10,10 @@ name = "jsonschema_rb"
|
|
|
10
10
|
path = "../../src/lib.rs"
|
|
11
11
|
|
|
12
12
|
[dependencies]
|
|
13
|
-
jsonschema = { version = "0.
|
|
13
|
+
jsonschema = { version = "0.63.1", default-features = false, features = ["magnus", "arbitrary-precision", "resolve-http", "resolve-file", "tls-ring", "macros", "idna", "json-text"] }
|
|
14
14
|
magnus = { version = "0.9", features = ["rb-sys"] }
|
|
15
15
|
rb-sys = "0.9"
|
|
16
|
-
referencing = "0.
|
|
16
|
+
referencing = "0.63.1"
|
|
17
17
|
serde = { version = "1", features = ["derive"] }
|
|
18
18
|
serde_json = { version = "1", features = ["arbitrary_precision"] }
|
|
19
19
|
strum = "0.28.0"
|
data/lib/jsonschema/version.rb
CHANGED
data/sig/jsonschema.rbs
CHANGED
|
@@ -373,6 +373,17 @@ module JSONSchema
|
|
|
373
373
|
?base_uri: String?
|
|
374
374
|
) -> Canonical::CanonicalSchema
|
|
375
375
|
|
|
376
|
+
# A `format` check that reads numbers, for the `formats` option; other instances pass it.
|
|
377
|
+
def self.number_format: (^(Numeric) -> bool check) -> NumberFormat
|
|
378
|
+
|
|
379
|
+
# A `format` check that reads numbers, made by `JSONSchema.number_format`.
|
|
380
|
+
class NumberFormat
|
|
381
|
+
end
|
|
382
|
+
|
|
383
|
+
# The names of the formats with a check under `draft`, sorted and without duplicates: the
|
|
384
|
+
# built-in formats and those in `formats`.
|
|
385
|
+
def self.known_formats: (draft draft, ?formats: Hash[String, (^(String) -> bool) | NumberFormat]?) -> Array[String]
|
|
386
|
+
|
|
376
387
|
# Create a validator with auto-detected draft version.
|
|
377
388
|
def self.validator_for: (
|
|
378
389
|
untyped schema,
|
|
@@ -382,7 +393,7 @@ module JSONSchema
|
|
|
382
393
|
?base_uri: String?,
|
|
383
394
|
?retriever: (^(String) -> untyped)?,
|
|
384
395
|
?mask: String?,
|
|
385
|
-
?formats: Hash[String, ^(String) -> bool]?,
|
|
396
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
386
397
|
?keywords: Hash[String, Class]?,
|
|
387
398
|
?registry: Registry?,
|
|
388
399
|
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
@@ -451,7 +462,7 @@ module JSONSchema
|
|
|
451
462
|
?base_uri: String?,
|
|
452
463
|
?retriever: (^(String) -> untyped)?,
|
|
453
464
|
?mask: String?,
|
|
454
|
-
?formats: Hash[String, ^(String) -> bool]?,
|
|
465
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
455
466
|
?keywords: Hash[String, Class]?,
|
|
456
467
|
?registry: Registry?,
|
|
457
468
|
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
@@ -471,7 +482,7 @@ module JSONSchema
|
|
|
471
482
|
?base_uri: String?,
|
|
472
483
|
?retriever: (^(String) -> untyped)?,
|
|
473
484
|
?mask: String?,
|
|
474
|
-
?formats: Hash[String, ^(String) -> bool]?,
|
|
485
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
475
486
|
?keywords: Hash[String, Class]?,
|
|
476
487
|
?registry: Registry?,
|
|
477
488
|
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
@@ -491,7 +502,7 @@ module JSONSchema
|
|
|
491
502
|
?base_uri: String?,
|
|
492
503
|
?retriever: (^(String) -> untyped)?,
|
|
493
504
|
?mask: String?,
|
|
494
|
-
?formats: Hash[String, ^(String) -> bool]?,
|
|
505
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
495
506
|
?keywords: Hash[String, Class]?,
|
|
496
507
|
?registry: Registry?,
|
|
497
508
|
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
@@ -509,7 +520,7 @@ module JSONSchema
|
|
|
509
520
|
?base_uri: String?,
|
|
510
521
|
?retriever: (^(String) -> untyped)?,
|
|
511
522
|
?mask: String?,
|
|
512
|
-
?formats: Hash[String, ^(String) -> bool]?,
|
|
523
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
513
524
|
?keywords: Hash[String, Class]?,
|
|
514
525
|
?registry: Registry?,
|
|
515
526
|
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
@@ -528,7 +539,7 @@ module JSONSchema
|
|
|
528
539
|
?vocabularies: Array[String]?,
|
|
529
540
|
?base_uri: String?,
|
|
530
541
|
?retriever: (^(String) -> untyped)?,
|
|
531
|
-
?formats: Hash[String, ^(String) -> bool]?,
|
|
542
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
532
543
|
?keywords: Hash[String, Class]?,
|
|
533
544
|
?registry: Registry?,
|
|
534
545
|
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
@@ -549,7 +560,7 @@ module JSONSchema
|
|
|
549
560
|
?base_uri: String?,
|
|
550
561
|
?retriever: (^(String) -> untyped)?,
|
|
551
562
|
?mask: String?,
|
|
552
|
-
?formats: Hash[String, ^(String) -> bool]?,
|
|
563
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
553
564
|
?keywords: Hash[String, Class]?,
|
|
554
565
|
?registry: Registry?,
|
|
555
566
|
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
@@ -573,6 +584,42 @@ module JSONSchema
|
|
|
573
584
|
|
|
574
585
|
def inspect: () -> String
|
|
575
586
|
end
|
|
587
|
+
|
|
588
|
+
# Validates instances given as JSON text, without building Ruby objects for them.
|
|
589
|
+
class JsonTextValidator
|
|
590
|
+
def initialize: (
|
|
591
|
+
untyped schema,
|
|
592
|
+
?draft: draft?,
|
|
593
|
+
?validate_formats: bool?,
|
|
594
|
+
?ignore_unknown_formats: bool?,
|
|
595
|
+
?vocabularies: Array[String]?,
|
|
596
|
+
?base_uri: String?,
|
|
597
|
+
?retriever: (^(String) -> untyped)?,
|
|
598
|
+
?mask: String?,
|
|
599
|
+
?formats: Hash[String, (^(String) -> bool) | NumberFormat]?,
|
|
600
|
+
?keywords: Hash[String, Class]?,
|
|
601
|
+
?registry: Registry?,
|
|
602
|
+
?pattern_options: (RegexOptions | FancyRegexOptions)?,
|
|
603
|
+
?email_options: EmailOptions?,
|
|
604
|
+
?http_options: HttpOptions?,
|
|
605
|
+
?offline: bool?
|
|
606
|
+
) -> void
|
|
607
|
+
|
|
608
|
+
# Whether the JSON text holds a valid document.
|
|
609
|
+
def valid?: (String text) -> bool
|
|
610
|
+
|
|
611
|
+
# Raise on the first error of the document in the JSON text.
|
|
612
|
+
def validate!: (String text) -> nil
|
|
613
|
+
|
|
614
|
+
# Iterate validation errors. Returns Array when no block given, nil when block given.
|
|
615
|
+
def each_error: (String text) -> Array[ValidationError]
|
|
616
|
+
| (String text) { (ValidationError) -> void } -> nil
|
|
617
|
+
|
|
618
|
+
# Evaluate the document in the JSON text and return structured output.
|
|
619
|
+
def evaluate: (String text) -> Evaluation
|
|
620
|
+
|
|
621
|
+
def inspect: () -> String
|
|
622
|
+
end
|
|
576
623
|
public
|
|
577
624
|
|
|
578
625
|
# Validators for every subschema, keyed by URI fragment such as `"#/$defs/User"`.
|
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
|
+
}
|