Debian Codegraph @

lib/JSON/Schema/Modern/Document.pm

raw
1 use strict;
2 use warnings;
3 package JSON::Schema::Modern::Document;
4 # vim: set ts=8 sts=2 sw=2 tw=100 et :
5 # ABSTRACT: One JSON Schema document
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 Mojo::URL;
22 use Carp 'croak';
23 use List::Util 1.29 'pairs';
24 use builtin::compat qw(refaddr blessed);
25 use MooX::TypeTiny;
26 use Types::Standard 1.016003 qw(InstanceOf HashRef Str Map Dict Tuple ArrayRef Enum ClassName Undef Slurpy Optional Bool);
27 use Types::Common::Numeric 'PositiveOrZeroInt';
28 use JSON::Schema::Modern::Utilities qw(json_pointer_type canonical_uri_type E);
29 use namespace::clean;
30
31 extends 'Mojo::JSON::Pointer';
32
33 has schema => (
34 is => 'ro',
35 required => 1,
36 );
37
38 has canonical_uri => (
39 is => 'rwp',
40 isa => (InstanceOf['Mojo::URL'])->where(q{not defined $_->fragment}),
41 lazy => 1,
42 default => sub { Mojo::URL->new },
43 coerce => sub { blessed($_[0]) && $_[0]->isa('Mojo::URL') ? $_[0] : Mojo::URL->new($_[0]) },
44 );
45
46 # this is also known as the retrieval uri in the OpenAPI specification
47 has original_uri => (
48 is => 'rwp',
49 isa => (InstanceOf['Mojo::URL'])->where(q{not defined $_->fragment}),
50 init_arg => undef,
51 );
52 *retrieval_uri = \&original_uri;
53
54 has metaschema_uri => (
55 is => 'rwp',
56 isa => InstanceOf['Mojo::URL'],
57 coerce => sub { blessed($_[0]) && $_[0]->isa('Mojo::URL') ? $_[0] : Mojo::URL->new($_[0]) },
58 predicate => '_has_metaschema_uri',
59 # default not defined here, but might be defined in a subclass
60 );
61
62 # "A JSON Schema resource is a schema which is canonically identified by an absolute URI."
63 # https://json-schema.org/draft/2020-12/json-schema-core.html#rfc.section.4.3.5
64 has resource_index => (
65 is => 'bare',
66 isa => Map[my $resource_key_type = Str->where('!/#/'), my $resource_type = Dict[
67 canonical_uri => (InstanceOf['Mojo::URL'])->where(q{not defined $_->fragment}),
68 path => json_pointer_type, # JSON pointer relative to the document root
69 specification_version => Enum[qw(draft4 draft6 draft7 draft2019-09 draft2020-12)],
70 # the vocabularies used when evaluating instance data against schema
71 vocabularies => ArrayRef[ClassName->where(q{$_->DOES('JSON::Schema::Modern::Vocabulary')})],
72 anchors => Optional[HashRef[Dict[
73 canonical_uri => canonical_uri_type, # equivalent uri with json pointer fragment
74 path => json_pointer_type, # JSON pointer relative to the document root
75 dynamic => Optional[Bool],
76 ]]],
77 Slurpy[HashRef[Undef]], # no other fields allowed
78 ]],
79 init_arg => undef,
80 default => sub { {} },
81 );
82
83 sub resource_index { $_[0]->{resource_index}->%* }
84 sub resource_pairs { pairs $_[0]->{resource_index}->%* }
85 sub _get_resource { $_[0]->{resource_index}{$_[1]} }
86 sub _canonical_resources { values $_[0]->{resource_index}->%* }
87 sub _add_resource {
88 croak 'uri "'.$_[1].'" conflicts with an existing schema resource' if $_[0]->{resource_index}{$_[1]};
89 $_[0]->{resource_index}{$resource_key_type->($_[1])} = $resource_type->($_[2]);
90 }
91
92 # for internal use only
93 has _checksum => (
94 is => 'rw',
95 isa => Str,
96 init_arg => undef,
97 );
98
99 has errors => (
100 is => 'bare',
101 writer => '_set_errors',
102 isa => ArrayRef[InstanceOf['JSON::Schema::Modern::Error']],
103 lazy => 1,
104 default => sub { [] },
105 );
106
107 sub errors { ($_[0]->{errors}//[])->@* }
108 sub has_errors { scalar(($_[0]->{errors}//[])->@*) }
109 sub _push_errors { push((shift->{errors}//=[])->@*, @_) }
110
111 # an entity is defined as a type of location that can be addressed by a $ref in a document
112 # json pointer => entity name (indexed by integer)
113 has _entities => (
114 is => 'ro',
115 isa => Map[json_pointer_type, PositiveOrZeroInt],
116 lazy => 1,
117 default => sub { {} },
118 );
119
120 # in this class, the only entity type is 'schema', but subclasses add more
121 sub __entities ($) { qw(schema) }
122 sub __entity_type { Enum[$_[0]->__entities] }
123 sub __entity_index ($self, $entity) {
124 my @e = $self->__entities;
125 foreach my $i (0..$#e) { return $i if $e[$i] eq $entity; }
126 return undef;
127 }
128
129 sub _add_entity_location ($self, $location, $entity) {
130 $self->__entity_type->($entity); # verify string
131 $self->_entities->{$location} = $self->__entity_index($entity); # store integer-mapped value
132 }
133
134 sub get_entity_at_location ($self, $location) {
135 return '' if not exists $self->_entities->{$location};
136 ($self->__entities)[ $self->_entities->{$location} ] // croak "missing mapping for ", $self->_entities->{$location};
137 }
138
139 # note: not sorted
140 sub get_entity_locations ($self, $entity) {
141 $self->__entity_type->($entity); # verify string
142 my $index = $self->__entity_index($entity);
143 grep $self->{_entities}{$_} == $index, keys $self->{_entities}->%*;
144 }
145
146 # references to a location in an unknown document are not considered to be errors at document
147 # loading time, but might be checked later on by some other mechanism
148 has _deferred_references => (
149 is => 'rwp',
150 isa => ArrayRef[
151 my $reference_type = Tuple[
152 Str|Undef, # keyword
153 json_pointer_type, # path location
154 InstanceOf['Mojo::URL'], # absolute target
155 Str, # expected entity (should actually be __entity_type)
156 ],
157 ],
158 init_arg => undef,
159 lazy => 1,
160 default => sub { [] },
161 );
162
163 # shims for Mojo::JSON::Pointer
164 sub data { shift->schema(@_) }
165 sub FOREIGNBUILDARGS { () }
166
167 # for JSON serializers
168 sub TO_JSON { shift->schema }
169
170 # note that this is always called, even in subclasses
171 sub BUILD ($self, $args) {
172 # note! not a clone! Please don't change canonical_uri in-place.
173 $self->_set_original_uri($self->canonical_uri);
174
175 # this should extract all identifiers, references, and entities, and set canonical_uri,
176 # metaschema_uri
177 my $state = $self->traverse(
178 $args->{evaluator} // JSON::Schema::Modern->new,
179 {
180 $args->{specification_version} ? $args->%{specification_version} : (),
181 $args->{skip_ref_checks} ? $args->%{skip_ref_checks} : (),
182 },
183 );
184
185 if ($state->{errors}->@*) {
186 $self->_set_errors($state->{errors});
187 return;
188 }
189
190 my $seen_root;
191 foreach my $key (keys $state->{identifiers}->%*) {
192 my $value = $state->{identifiers}{$key};
193 $self->_add_resource($key => $value);
194
195 # we're adding a non-anchor entry for the document root
196 ++$seen_root if $value->{path} eq '';
197 }
198
199 # we only index the original uri if nothing in the schema itself identified a root resource:
200 # otherwise the top of the document would be unreferenceable.
201 $self->_add_resource($self->original_uri.'' => {
202 path => '',
203 canonical_uri => $self->canonical_uri,
204 $state->%{qw(specification_version vocabularies)},
205 })
206 if not $seen_root;
207
208 $self->_set_errors($state->{errors}) if $state->{errors}->@*;
209
210 # set aside unverified references, perhaps to be checked later when new documents are added to the
211 # resource index; updates 'errors' and '_deferred_references'
212 $self->verify_references($args->{evaluator}, $state, $state->{references});
213 }
214
215 # checks a list of references for validity, returning those to unknown documents that cannot be
216 # verified yet; will update errors automatically
217 sub verify_references ($self, $evaluator, $state = undef, $references = undef) {
218 $state //= { # minimum needed for E()
219 initial_schema_uri => $self->canonical_uri,
220 traversed_keyword_path => '',
221 traverse => 1,
222 };
223
224 $references //= $self->_deferred_references;
225
226 $state->{errors} = [];
227 my @deferred_references;
228
229 foreach my $ref ($references->@*) {
230 $reference_type->($ref);
231 $self->__entity_type->($ref->[3]);
232
233 my ($keyword, $path_location, $abs_target, $expected_entity) = @$ref;
234
235 # look for resource locally; fall back to the evaluator's index
236 my $resource = $self->_get_resource(my $base_uri = $abs_target->clone->fragment(undef));
237 my $document = $self;
238
239 if (not $resource) {
240 $resource = $evaluator->_get_resource($base_uri) if $evaluator;
241
242 if (not $resource) {
243 push @deferred_references, [ $keyword, $path_location, $abs_target, $expected_entity ];
244 next;
245 };
246 $document = $resource->{document};
247 }
248
249 my $fragment = $abs_target->fragment;
250 my $target_path;
251 if (not length $fragment) {
252 $target_path = $resource->{path};
253 }
254 elsif ($fragment =~ m{^/}) {
255 # json pointer fragment
256 ()= E({ %$state, keyword_path => $path_location, keyword => $keyword },
257 '%s target "%s" is a non-existent location', $expected_entity, $abs_target), next
258 if not $document->contains($target_path = $resource->{path}.$fragment);
259 }
260 elsif (my $subresource = ($resource->{anchors}//{})->{$fragment}) {
261 # valid anchor
262 $target_path = $subresource->{path};
263 }
264 else {
265 # invalid anchor
266 ()= E({ %$state, keyword_path => $path_location, keyword => $keyword },
267 '%s target "%s" is a non-existent location', $expected_entity, $abs_target);
268 next;
269 }
270
271 my $entity = $document->get_entity_at_location($target_path);
272 ()= E({ %$state, keyword_path => $path_location, keyword => $keyword },
273 '%s target "%s" is not a referenceable location', $expected_entity, $abs_target), next
274 if not $entity;
275
276 ()= E({ %$state, keyword_path => $path_location, keyword => $keyword },
277 '%s target "%s" is the wrong object type (got %s)',
278 $expected_entity, $abs_target, $entity), next
279 if $entity ne $expected_entity;
280 }
281
282 $self->_push_errors($state->{errors}->@*);
283 $self->_set__deferred_references(\@deferred_references);
284 }
285
286 # a subclass's method will override this one
287 sub traverse ($self, $evaluator, $config_override = {}) {
288 die 'wrong class - use JSON::Schema::Modern::Document::OpenAPI instead'
289 if ref $self->schema eq 'HASH' and exists $self->schema->{openapi};
290
291 my $original_uri = $self->original_uri;
292
293 my $state = $evaluator->traverse($self->schema,
294 {
295 initial_schema_uri => $original_uri,
296 $self->_has_metaschema_uri ? (metaschema_uri => $self->metaschema_uri) : (),
297 %$config_override,
298 }
299 );
300
301 die 'original_uri has changed' if $self->original_uri ne $original_uri
302 or refaddr($self->original_uri) != refaddr($original_uri);
303
304 # if the document identified a canonical uri for itself via '$id', or metaschema uri via '$schema',
305 # they overrides the initial values
306 # Note that subclasses of this class may choose to identify these values in a different way
307 # (e.g. "$self" in OpenAPI)
308 $self->_set_canonical_uri($state->{initial_schema_uri});
309 $self->_set_metaschema_uri($state->{metaschema_uri});
310
311 $self->_add_entity_location($_, 'schema') foreach $state->{subschemas}->@*;
312
313 return $state;
314 }
315
316 sub validate ($class, @args) {
317 croak 'bad argument list' if blessed($args[0]);
318
319 my $args = $class->Moo::Object::BUILDARGS(@args);
320 my $document = blessed($class) ? $class : $class->new($args);
321
322 my $doc_result = JSON::Schema::Modern::Result->new(errors => [ $document->errors ]);
323
324 # ideally, the traverse phase run during document construction should have found all errors that a
325 # simple metaschema evaluation would reveal, but we'll do both just to make sure.
326 my $evaluator = $args->{evaluator} // JSON::Schema::Modern->new(validate_formats => 1);
327 my $eval_result = $evaluator->evaluate($document->schema, $document->metaschema_uri);
328
329 if (my ($missing_resource) = grep $_->error =~ /EXCEPTION: unable to find resource/, $eval_result->errors) {
330 $missing_resource->{error} .= ' (did you forget to provide "evaluator" to ->validate?)';
331 }
332
333 return $doc_result & $eval_result;
334 }
335
336 # callback hook for Sereal::Encoder
337 sub FREEZE ($self, $serializer) { +{ %$self } }
338
339 # callback hook for Sereal::Decoder
340 sub THAW ($class, $serializer, $data) {
341 delete $data->{evaluator};
342
343 my $self = bless($data, $class);
344
345 foreach my $attr (qw(schema _entities)) {
346 croak "serialization missing attribute '$attr' on document for identifier '$self->{canonical_uri}': perhaps your serialized data was produced for an older version of $class?"
347 if not exists $self->{$attr};
348 }
349 return $self;
350 }
351
352 1;
353
354 __END__
355
356 =pod
357
358 =encoding UTF-8
359
360 =for stopwords subschema
361
362 =head1 NAME
363
364 JSON::Schema::Modern::Document - One JSON Schema document
365
366 =head1 VERSION
367
368 version 0.650
369
370 I use a linearly-increasing version numbering scheme. No meaning should be
371 presumed or inferred from the version being less than 1.0.
372
373 =head1 SYNOPSIS
374
375 use JSON::Schema::Modern::Document;
376
377 my $document = JSON::Schema::Modern::Document->new(
378 canonical_uri => 'https://example.com/v1/schema',
379 schema => $schema,
380 );
381 my $foo_definition = $document->get('/$defs/foo');
382 my %resource_index = $document->resource_index;
383 my $metaschema_uri = $document->metaschema_uri;
384
385 =head1 DESCRIPTION
386
387 This class represents one JSON Schema document, to be used by L<JSON::Schema::Modern>.
388
389 =head1 CONSTRUCTOR ARGUMENTS
390
391 Unless otherwise noted, these are also available as read-only accessors.
392
393 =head2 schema
394
395 The actual raw data representing the schema. Required.
396
397 =head2 canonical_uri
398
399 As a constructor value, represents the initial URI by which the document should be known, or a base
400 URI to use to determine that value. The URI found in the root schema's C<$id> keyword is resolved
401 against this URI to determine the final value, which is then stored in this accessor. As such, it
402 can be considered the canonical URI for the document as a whole, from which subsequent C<$ref>
403 keywords are resolved.
404
405 The original passed-in value is saved in L</original_uri>.
406
407 =head2 metaschema_uri
408
409 =for stopwords metaschema schemas
410
411 Sets the metaschema that is used to describe the document (or more specifically, any JSON Schemas
412 contained within the document), which determines the
413 specification version and vocabularies used during evaluation.
414 Does not override any C<$schema> keyword actually present in the schema document, and normally you
415 should use this keyword instead.
416
417 =head2 specification_version
418
419 Only a constructor argument, not an accessor method.
420
421 Indicates which version of the JSON Schema specification is used during evaluation. This value is
422 overridden by the value determined from the C<$schema> keyword in the schema used in evaluation
423 (when present), or defaults to the latest version (currently C<draft2020-12>).
424
425 The use of the C<$schema> keyword in your schema is I<HIGHLY> encouraged to ensure continued correct
426 operation of your schema. The current default value will not stay the same over time.
427
428 May be one of:
429
430 =over 4
431
432 =item *
433
434 L<C<draft2020-12> or C<2020-12>|https://json-schema.org/specification-links.html#2020-12>, corresponding to metaschema C<https://json-schema.org/draft/2020-12/schema>
435
436 =item *
437
438 L<C<draft2019-09> or C<2019-09>|https://json-schema.org/specification-links.html#2019-09-formerly-known-as-draft-8>, corresponding to metaschema C<https://json-schema.org/draft/2019-09/schema>
439
440 =item *
441
442 L<C<draft7> or C<7>|https://json-schema.org/specification-links.html#draft-7>, corresponding to metaschema C<http://json-schema.org/draft-07/schema#>
443
444 =item *
445
446 L<C<draft6> or C<6>|https://json-schema.org/specification-links.html#draft-6>, corresponding to metaschema C<http://json-schema.org/draft-06/schema#>
447
448 =item *
449
450 L<C<draft4> or C<4>|https://json-schema.org/specification-links.html#draft-4>, corresponding to metaschema C<http://json-schema.org/draft-04/schema#>
451
452 =back
453
454 =head2 evaluator
455
456 A L<JSON::Schema::Modern> object. Optional, unless custom metaschemas are used (see notes below
457 under L</validate>).
458
459 This argument is not preserved by the constructor, so it is not available as an accessor.
460
461 =head2 skip_ref_checks
462
463 Only a constructor argument, not an accessor method.
464
465 When true, the normal checks for bad reference targets are skipped. This should only be used for
466 large documents that are known to be valid, such as specification metaschemas.
467
468 =head1 METHODS
469
470 =for Pod::Coverage FOREIGNBUILDARGS BUILDARGS BUILD FREEZE THAW traverse has_errors path_to_resource
471 resource_pairs get_entity_at_location get_entity_locations retrieval_uri
472
473 =head2 errors
474
475 Returns a list of L<JSON::Schema::Modern::Error> objects that resulted when the schema document was
476 originally parsed. (If a syntax error occurred, usually there will be just one error, as parse
477 errors halt the parsing process.) Documents with errors cannot be used for evaluation.
478
479 =head2 original_uri
480
481 Returns the original value of L</canonical_uri> that was passed to the document constructor (which
482 C<$id> keywords within the document would have been resolved against, if they were not already
483 absolute). Some subclasses may make use of this value for resolving URIs when matching HTTP requests
484 at runtime.
485
486 This URI is B<not> added to the document's resource index, so if you want the document to be
487 addressable at this location you must add it to the evaluator yourself with the two-argument form of
488 L<JSON::Schema::Modern/add_document>.
489
490 Read-only.
491
492 =head2 resource_index
493
494 An index of URIs to subschemas (JSON pointer to reach the location, and the canonical URI of that
495 location) for all identifiable subschemas found in the document. An entry for URI C<''> is added
496 only when no other suitable identifier can be found for the root schema.
497
498 This attribute should only be used by L<JSON::Schema::Modern> and not intended for use
499 externally (you should use the public accessors in L<JSON::Schema::Modern> instead).
500
501 When called as a method, returns the flattened list of tuples (path, uri). You can also use
502 C<resource_pairs> which returns a list of tuples as arrayrefs.
503
504 =head2 contains
505
506 Check if L</"schema"> contains a value that can be identified with the given JSON Pointer.
507 See L<Mojo::JSON::Pointer/contains>.
508
509 =head2 get
510
511 Extract value from L</"schema"> identified by the given JSON Pointer.
512 See L<Mojo::JSON::Pointer/get>.
513
514 =head2 validate
515
516 $result = JSON::Schema::Modern::Document->validate(<normal constructor arguments>);
517
518 Constructs the document object, and then performs a further sanity check by evaluating the document
519 against its metaschema. (See L<JSON::Schema::Modern/evaluate>.) This is preferred to simply
520 attempting to add the document to the evaluator with L<JSON::Schema::Modern/add_schema> in cases
521 where the document's sanity is not known, as that method will die if errors are encountered.
522
523 As with calling C<new>, if the document's metaschema is one of the core bundled metaschemas (see
524 L<JSON::Schema::Modern/BUNDLED META-SCHEMAS>), the C<$evaluator> argument is optional, as these
525 metaschemas are available to all evaluator instances; otherwise (you are using a custom metaschema),
526 you must provide the same evaluator instance as would be used to construct the document object.
527
528 Returns a L<JSON::Schema::Modern::Result> object containing the final result.
529
530 See also L<JSON::Schema::Modern/validate_schema>, which is nearly equivalent but only works for
531 JSON Schemas, not any potential subclass of JSON::Schema::Modern::Document.
532
533 =head2 verify_references
534
535 my @deferred_references = $doc->verify_references($evaluator);
536
537 Checks the internal list of references that had been deferred due to being in unknown documents;
538 updates the internal list and also returns them; new document errors may be generated.
539
540 Primarily for internal use.
541
542 =head2 TO_JSON
543
544 Returns a data structure suitable for serialization. See L</schema>.
545
546 =head1 SUBCLASSING
547
548 =for stopwords OpenAPI referenceable
549
550 This class can be subclassed to describe documents of other types, which follow the same basic model
551 (has a document-level identifier and may contain internal referenceable identifiers). The overall
552 document itself may not be a JSON Schema, but it may contain JSON Schemas internally. Referenceable
553 entities may or may not be JSON Schemas. As long as the C<traverse> method is implemented and the
554 C<$state> object is respected, any other functionality may be contained by this subclass. The
555 C<traverse> method is responsible for finding any identifiers within the document, setting
556 L</canonical_uri> and L</metaschema_uri>, and finding any C<$ref>abble entities within the document.
557
558 To date, there is one subclass of JSON::Schema::Modern::Document:
559 L<JSON::Schema::Modern::Document::OpenAPI>, which contains entities of type C<schema> as well as
560 others (e.g. C<request-body>, C<response>, C<path-item>, etc). An object of this class represents
561 one OpenAPI document, used by L<OpenAPI::Modern> to specify application APIs.
562
563 =head1 SEE ALSO
564
565 =over 4
566
567 =item *
568
569 L<JSON::Schema::Modern>
570
571 =item *
572
573 L<Mojo::JSON::Pointer>
574
575 =back
576
577 =head1 GIVING THANKS
578
579 =for stopwords MetaCPAN GitHub
580
581 If you found this module to be useful, please show your appreciation by
582 adding a +1 in L<MetaCPAN|https://metacpan.org/dist/JSON-Schema-Modern>
583 and a star in L<GitHub|https://github.com/karenetheridge/JSON-Schema-Modern>.
584
585 =head1 SUPPORT
586
587 Bugs may be submitted through L<https://github.com/karenetheridge/JSON-Schema-Modern/issues>.
588
589 I am also usually active on irc, as 'ether' at C<irc.perl.org> and C<irc.libera.chat>.
590
591 =for stopwords OpenAPI
592
593 You can also find me on the L<JSON Schema Slack server|https://json-schema.slack.com> and L<OpenAPI Slack
594 server|https://open-api.slack.com>, which are also great resources for finding help.
595
596 =head1 AUTHOR
597
598 Karen Etheridge <[email protected]>
599
600 =head1 COPYRIGHT AND LICENCE
601
602 This software is copyright (c) 2020 by Karen Etheridge.
603
604 This is free software; you can redistribute it and/or modify it under
605 the same terms as the Perl 5 programming language system itself.
606
607 Some schema files have their own licence, in share/LICENSE.
608
609 =cut