Debian Codegraph @

lib/JSON/Schema/Modern/Result.pm

raw
1 use strict;
2 use warnings;
3 package JSON::Schema::Modern::Result;
4 # vim: set ts=8 sts=2 sw=2 tw=100 et :
5 # ABSTRACT: Contains the result of a JSON Schema evaluation
6
7 our $VERSION = '0.650';
8
9 use 5.020;
10 use Moo;
11 use strictures 2;
12 use stable 0.031 'postderef';
13 use experimental 'signatures';
14 no autovivification warn => qw(fetch store exists delete);
15 use if "$]" >= 5.022, experimental => 're_strict';
16 no if "$]" >= 5.031009, feature => 'indirect';
17 no if "$]" >= 5.033001, feature => 'multidimensional';
18 no if "$]" >= 5.033006, feature => 'bareword_filehandles';
19 no if "$]" >= 5.041009, feature => 'smartmatch';
20 no feature 'switch';
21 use MooX::TypeTiny;
22 use Types::Standard qw(ArrayRef InstanceOf Enum Bool Str Maybe Tuple Map Any);
23 use Types::Common::Numeric 'PositiveInt';
24 use JSON::Schema::Modern::Annotation;
25 use JSON::Schema::Modern::Error;
26 use JSON::Schema::Modern::Utilities qw(true false json_pointer_type jsonp_set);
27 use JSON::PP ();
28 use List::Util 1.45 'uniqstr';
29 use if "$]" < 5.041010, 'List::Util' => qw(any all);
30 use if "$]" >= 5.041010, experimental => qw(keyword_any keyword_all);
31 use Carp 'croak';
32 use builtin::compat qw(refaddr blessed);
33 use namespace::clean;
34
35 use overload
36 '&' => \&combine,
37 '""' => sub { $_[0]->stringify },
38 fallback => 1;
39
40 has valid => (
41 is => 'ro',
42 isa => Bool|InstanceOf('JSON::PP::true')|InstanceOf('JSON::PP::false'),
43 coerce => sub { $_[0] ? true : false }, # might be JSON::PP::* or builtin::* booleans
44 lazy => 1,
45 default => sub ($self) { $self->error_count == 0 },
46 );
47 sub result { goto \&valid } # backcompat only
48
49 has exception => (
50 is => 'ro',
51 isa => Bool,
52 lazy => 1,
53 default => sub ($self) { any { $_->exception or $_->error =~ /^EXCEPTION: / } $self->errors },
54 );
55
56 # has errors
57 # has annotations
58 # turn hashrefs in _errors or _annotations into blessed objects
59 has $_.'s' => (
60 is => 'bare',
61 reader => '__'.$_.'s',
62 isa => ArrayRef[InstanceOf['JSON::Schema::Modern::'.ucfirst]],
63 lazy => 1,
64 default => do {
65 my $type = $_;
66 sub ($self) {
67 return [] if not (($self->{'_'.$type.'s'}//[])->@*);
68
69 # E() and A() in ::Utilities returns an unblessed hashref, which is used to create a real object
70 # by its BUILDARGS sub
71 return [ map +(('JSON::Schema::Modern::'.ucfirst($type))->new($_)), $self->{'_'.$type.'s'}->@* ];
72 };
73 },
74 ) foreach qw(error annotation);
75
76 sub errors { $_[0]->__errors->@* }
77 sub error_count { scalar(($_[0]->{errors}//[])->@*) || scalar(($_[0]->{_errors}//[])->@*) }
78 sub annotations { $_[0]->__annotations->@* }
79 sub annotation_count { scalar(($_[0]->{annotations}//[])->@*) || scalar(($_[0]->{_annotations}//[])->@*) }
80
81 has recommended_response => (
82 is => 'rw',
83 isa => Maybe[Tuple[PositiveInt, Str]],
84 lazy => 1,
85 default => sub ($self) {
86 return if not $self->errors;
87
88 for my $error ($self->errors) {
89 my $pe = $error->recommended_response;
90 return $pe if $pe;
91 }
92
93 return [ 500, 'Internal Server Error' ] if $self->exception;
94 return [ 400, ($self->errors)[0]->stringify ];
95 },
96 );
97
98 # strict_basic can only be used with draft2019-09.
99 use constant OUTPUT_FORMATS => [qw(flag basic strict_basic terse data_only)];
100
101 has output_format => (
102 is => 'rw',
103 isa => Enum(OUTPUT_FORMATS),
104 default => 'basic',
105 );
106
107 has formatted_annotations => (
108 is => 'ro',
109 isa => Bool,
110 default => 1,
111 );
112
113 has defaults => (
114 is => 'ro',
115 isa => Map[json_pointer_type, Any],
116 );
117
118 has data => (
119 is => 'ro',
120 );
121
122 around BUILDARGS => sub ($orig, $class, @args) {
123 my $args = $class->$orig(@args);
124
125 # set unblessed hashrefs aside, and defer creation of blessed objects until needed
126 $args->{_errors} = delete $args->{errors} if
127 exists $args->{errors} and any { !blessed($_) } $args->{errors}->@*;
128 $args->{_annotations} = delete $args->{annotations} if
129 exists $args->{annotations} and any { !blessed($_) } $args->{annotations}->@*;
130
131 croak 'inconsistent inputs: errors is not empty but valid is true'
132 if $args->{valid}
133 and (exists $args->{_errors} and $args->{_errors}->@*
134 or exists $args->{errors} and $args->{errors}->@*);
135
136 croak 'inconsistent inputs: errors is empty but valid is false'
137 if exists $args->{valid} and not $args->{valid}
138 and (not exists $args->{_errors} or not $args->{_errors}->@*)
139 and (not exists $args->{errors} or not $args->{errors}->@*);
140
141 return $args;
142 };
143
144 sub BUILD ($self, $args) {
145 $self->{_errors} = $args->{_errors} if exists $args->{_errors};
146 $self->{_annotations} = $args->{_annotations} if exists $args->{_annotations};
147
148 if (exists $args->{data} and exists $args->{defaults}) {
149 jsonp_set($args->{data}, $args->{defaults}->%{$_}) foreach keys $args->{defaults}->%*;
150 }
151 }
152
153 sub format ($self, $style, $formatted_annotations = undef) {
154 $formatted_annotations //= $self->formatted_annotations;
155
156 if ($style eq 'flag') {
157 return +{ valid => $self->valid ? true : false };
158 }
159 elsif ($style eq 'basic') {
160 return +{
161 valid => $self->valid ? true : false,
162 $self->valid
163 ? ($formatted_annotations && $self->annotation_count ? (annotations => [ map $_->TO_JSON, $self->annotations ]) : ())
164 : (errors => [ map $_->TO_JSON, $self->errors ]),
165 $self->valid && $self->defaults ? (defaults => $self->defaults) : (),
166 };
167 }
168 # note: strict_basic will NOT be supported after draft 2019-09!
169 elsif ($style eq 'strict_basic') {
170 return +{
171 valid => ($self->valid ? true : false),
172 $self->valid
173 ? ($formatted_annotations && $self->annotation_count ? (annotations => [ map _map_uris($_->TO_JSON), $self->annotations ]) : ())
174 : (errors => [ map _map_uris($_->TO_JSON), $self->errors ]),
175 };
176 }
177 elsif ($style eq 'terse') {
178 my (%instance_locations, %keyword_locations);
179
180 my @errors = grep do {
181 my ($keyword, $error) = ($_->keyword, $_->error);
182
183 my $keep = 0+!!(
184 not $keyword
185 or (
186 not grep $keyword eq $_, qw(allOf anyOf if then else dependentSchemas contains propertyNames)
187 and ($keyword ne 'oneOf' or $error ne 'no subschemas are valid')
188 and ($keyword ne 'prefixItems' or $error eq 'item not permitted')
189 and ($keyword ne 'items' or $error eq 'item not permitted' or $error eq 'additional item not permitted')
190 and ($keyword ne 'additionalItems' or $error eq 'additional item not permitted')
191 and (not grep $keyword eq $_, qw(properties patternProperties)
192 or $error eq 'property not permitted')
193 and ($keyword ne 'additionalProperties' or $error eq 'additional property not permitted'))
194 and ($keyword ne 'dependentRequired' or $error ne 'not all dependencies are satisfied')
195 );
196
197 ++$instance_locations{$_->instance_location} if $keep;
198 ++$keyword_locations{$_->keyword_location} if $keep;
199
200 $keep;
201 },
202 $self->errors;
203
204 die 'uh oh, have no errors left to report' if not $self->valid and not @errors;
205
206 return +{
207 valid => $self->valid ? true : false,
208 $self->valid
209 ? ($formatted_annotations && $self->annotation_count ? (annotations => [ map $_->TO_JSON, $self->annotations ]) : ())
210 : (errors => [ map $_->TO_JSON, @errors ]),
211 };
212 }
213 elsif ($style eq 'data_only') {
214 return 'valid' if not $self->error_count;
215 # Note: this output is going to be confusing when coming from a schema with a 'oneOf', 'not',
216 # etc. Perhaps generating the strings with indentation levels, as derived from a nested format,
217 # might be more readable.
218 return join("\n", uniqstr(map $_->stringify, $self->errors));
219 }
220
221 # TODO: support detailed, verbose ?
222 croak 'unsupported output format';
223 }
224
225 sub count { $_[0]->valid ? $_[0]->annotation_count : $_[0]->error_count }
226
227 sub combine ($self, $other, $swap) {
228 croak 'wrong type for & operation' if not blessed($other) or not $other->isa(__PACKAGE__);
229
230 return $self if refaddr($other) == refaddr($self);
231
232 return ref($self)->new(
233 valid => $self->valid && $other->valid,
234 annotations => [
235 $self->annotations,
236 $other->annotations,
237 ],
238 errors => [
239 $self->errors,
240 $other->errors,
241 ],
242 output_format => $self->output_format,
243 formatted_annotations => $self->formatted_annotations || $other->formatted_annotations,
244 $self->defaults || $other->defaults
245 ? (defaults => +{ ($self->defaults//{})->%*, ($other->defaults//{})->%* })
246 : (),
247 );
248 }
249
250 sub stringify ($self) {
251 return $self->format('data_only');
252 }
253
254 sub TO_JSON ($self) {
255 croak 'cannot produce JSON output for data_only format' if $self->output_format eq 'data_only';
256 $self->format($self->output_format);
257 }
258
259 sub dump ($self) {
260 my $encoder = JSON::Schema::Modern::_JSON_BACKEND()->new
261 ->utf8(0)
262 ->convert_blessed(1)
263 ->canonical(1)
264 ->indent(1)
265 ->space_after(1);
266 $encoder->indent_length(2) if $encoder->can('indent_length');
267 $encoder->encode($self);
268 }
269
270 # turns the JSON pointers in instance_location, keyword_location into a URI fragments,
271 # for strict draft-201909 adherence
272 sub _map_uris ($data) {
273 return +{
274 %$data,
275 map +($_ => Mojo::URL->new->fragment($data->{$_})->to_string),
276 qw(instanceLocation keywordLocation),
277 };
278 }
279
280 1;
281
282 __END__
283
284 =pod
285
286 =encoding UTF-8
287
288 =head1 NAME
289
290 JSON::Schema::Modern::Result - Contains the result of a JSON Schema evaluation
291
292 =head1 VERSION
293
294 version 0.650
295
296 I use a linearly-increasing version numbering scheme. No meaning should be
297 presumed or inferred from the version being less than 1.0.
298
299 =head1 SYNOPSIS
300
301 use JSON::Schema::Modern;
302 my $js = JSON::Schema::Modern->new;
303 my $result = $js->evaluate($data, $schema);
304 my @errors = $result->errors;
305
306 my $result_data_encoded = encode_json($result); # calls TO_JSON
307
308 # use in numeric and boolean context
309 say sprintf('got %d %ss', $result, ($result->valid ? 'annotation' : 'error'));
310
311 # use in string context
312 say 'full results: ', $result;
313
314 # combine two results into one:
315 my $overall_result = $result1 & $result2;
316
317 =head1 DESCRIPTION
318
319 This object holds the complete results of evaluating a data payload against a JSON Schema using
320 L<JSON::Schema::Modern>.
321
322 =head1 OVERLOADS
323
324 The object contains a string overload, which evaluates to a potentially multi-line string
325 summarizing the errors within (if any); this is intended to be used as a user-oriented error message
326 that references data locations, but not schema locations.
327
328 =for stopwords iff
329
330 The object also contains a I<bitwise AND> overload (C<&>), for combining two results into one (the
331 result is valid iff both inputs are valid; annotations and errors from the second argument are
332 appended to those of the first in a new Result object).
333
334 =head1 CONSTRUCTOR ARGUMENTS
335
336 Unless otherwise noted, these are also available as read-only accessors.
337
338 =head2 valid
339
340 A boolean. Indicates whether validation was successful or failed.
341
342 Optional, as it can be calculated from the presence of C<errors> or C<annotations>.
343
344 =head2 errors
345
346 An array of L<JSON::Schema::Modern::Error> objects.
347
348 =head2 annotations
349
350 An array of L<JSON::Schema::Modern::Annotation> objects.
351
352 =head2 output_format
353
354 =for stopwords subschema
355
356 Also available as a read/write accessor.
357
358 One of: C<flag>, C<basic>, C<strict_basic>, C<terse>, C<data_only>. Defaults to C<basic>.
359
360 =over 4
361
362 =item *
363
364 C<flag> returns just the result of the evaluation: either C<{"valid": true}> or C<{"valid": false}>.
365
366 =item *
367
368 C<basic> adds the list of C<errors> or C<annotations> to the boolean evaluation result. C<instance_location> and C<keyword_location> are always included, as JSON pointers, describing the path to the evaluation location; C<absolute_keyword_location> is added (as a resolved URI) whenever it is known and different from C<keyword_location>.
369
370 =item *
371
372 C<strict_basic> is like C<basic> but follows the draft-2019-09 specification precisely, including replicating an error fixed in the next draft, in that C<instance_location> and C<keyword_location> values are provided as fragment-only URI references rather than JSON pointers.
373
374 =item *
375
376 C<terse> is not described in any specification; it is like C<basic>, but omits some redundant errors (for example the one for the C<allOf> keyword that is added when any of the subschemas under C<allOf> failed evaluation).
377
378 =item *
379
380 C<data_only> returns a string, not a data structure: it contains a list of errors identified only by their C<instance_location> and error message (or C<keyword_location>, when the error occurred while loading the schema itself). This format is suitable for generating errors when the schema is not published, or for describing errors with the schema itself. This is not an official specification format and may change slightly over time, as it is tested in production environments.
381
382 =back
383
384 =head2 formatted_annotations
385
386 A boolean flag indicating whether L</format> should include annotations in the output. Defaults to true.
387
388 =head2 exception
389
390 Indicates that evaluation stopped due to a severe error.
391
392 =head2 recommended_response
393
394 =for stopwords OpenAPI
395
396 A tuple, consisting of C<[ integer, string ]>, indicating the recommended HTTP response code and
397 string to use for this result (if validating an HTTP request). This could exist for things like a
398 failed authentication check in OpenAPI validation, in which case it would contain
399 C<[ 401, 'Unauthorized' ]>.
400
401 Only populated when there are errors; when not explicitly set by an evaluator, defaults to
402 C<< [ 500, 'Internal Server Error' ] >> if any errors indicate an exception, and
403 C<< [ 400, <first error string> ] >> otherwise. The exact error string is hidden in the case of 500
404 errors because you should not leak internal issues with your application, but you may also wish to
405 obfuscate normal validation errors, in which case you should check for C<400> and change the string
406 to C<'Bad Request'>.
407
408 Also available as a read/write accessor.
409
410 =head2 defaults
411
412 A hashref, mapping json pointer locations in the instance data to the default value assigned
413 to the property at this location, taken from C<default> keywords in the schema under C<properties>
414 and C<patternProperties> keywords (requires the L<JSON::Schema::Modern/defaults> configuration to be
415 enabled). This data will also be included in the "basic" output format when it is defined.
416
417 =head2 data
418
419 Contains a cloned copy of the instance data that was evaluated; includes decoded values from
420 C<contentEncoding> and C<contentMediaType> keywords, and is also populated with defaults if
421 L</defaults> is set (via L<JSON::Schema::Modern/with_defaults>).
422
423 In results coming from L<OpenAPI::Modern>, this value may contain deserialized data from various
424 parts of the HTTP message, such as path and query parameters, header values, and the deserialized
425 message body. Refer to that documentation for more details.
426
427 =head1 METHODS
428
429 =for Pod::Coverage BUILD BUILDARGS OUTPUT_FORMATS result stringify annotation_count error_count
430 true false HAVE_BUILTIN
431
432 =head2 format
433
434 Returns a data structure suitable for serialization; requires one argument specifying the output
435 format to use, which corresponds to the formats documented in
436 L<https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.section.10.4>. The only supported
437 formats at this time are C<flag>, C<basic>, C<strict_basic>, and C<terse>.
438
439 =head2 TO_JSON
440
441 Calls L</format> with the style configured in L</output_format>.
442
443 =head2 count
444
445 Returns the number of annotations when the result is true, or the number of errors when the result
446 is false.
447
448 =head2 combine
449
450 When provided with another result object, returns a new object with the combination of all results.
451 See C<&> at L</OVERLOADS>.
452
453 =head2 dump
454
455 Returns a JSON string representing the result object, using the requested L</format>, according to
456 the L<draft2019-09 specification|https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.section.10>
457 and the L<draft2020-12 specification|https://json-schema.org/draft/2020-12/json-schema-core#section-12>.
458
459 =head1 SERIALIZATION
460
461 Results (and their contained errors and annotations) can be serialized in a number of ways.
462
463 Results have defined L</output_format>s, which can be generated as nested unblessed hashes/arrays
464 and are suitable for serializing using a JSON encoder for use in another application. A JSON string of
465 the result can be obtained directly using L</dump>.
466
467 If it is preferable to omit direct references to the schema (for example in an application where the
468 schema is not published), but still convey some semantic information about the nature of the errors,
469 stringify the object directly. This also means that result objects can be thrown as exceptions, or
470 embedded in error messages.
471
472 If you are embedding the full result inside another data structure, perhaps to be serialized to JSON
473 (or another format) later on, use L</TO_JSON> or L</format>.
474
475 =head1 GIVING THANKS
476
477 =for stopwords MetaCPAN GitHub
478
479 If you found this module to be useful, please show your appreciation by
480 adding a +1 in L<MetaCPAN|https://metacpan.org/dist/JSON-Schema-Modern>
481 and a star in L<GitHub|https://github.com/karenetheridge/JSON-Schema-Modern>.
482
483 =head1 SUPPORT
484
485 Bugs may be submitted through L<https://github.com/karenetheridge/JSON-Schema-Modern/issues>.
486
487 I am also usually active on irc, as 'ether' at C<irc.perl.org> and C<irc.libera.chat>.
488
489 =for stopwords OpenAPI
490
491 You can also find me on the L<JSON Schema Slack server|https://json-schema.slack.com> and L<OpenAPI Slack
492 server|https://open-api.slack.com>, which are also great resources for finding help.
493
494 =head1 AUTHOR
495
496 Karen Etheridge <[email protected]>
497
498 =head1 COPYRIGHT AND LICENCE
499
500 This software is copyright (c) 2020 by Karen Etheridge.
501
502 This is free software; you can redistribute it and/or modify it under
503 the same terms as the Perl 5 programming language system itself.
504
505 Some schema files have their own licence, in share/LICENSE.
506
507 =cut